Switch encoders to metadata-based recipient parameter.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * SAML2POSTEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <log4cpp/Category.hh>
32 #include <xercesc/util/Base64.hpp>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/TemplateEngine.h>
35
36 using namespace opensaml::saml2p;
37 using namespace opensaml::saml2md;
38 using namespace opensaml;
39 using namespace xmlsignature;
40 using namespace xmltooling;
41 using namespace log4cpp;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml2p {              
46         class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
47         {
48         public:
49             SAML2POSTEncoder(const DOMElement* e, bool simple=false);
50             virtual ~SAML2POSTEncoder() {}
51             
52             long encode(
53                 GenericResponse& genericResponse,
54                 XMLObject* xmlObject,
55                 const char* destination,
56                 const EntityDescriptor* recipient=NULL,
57                 const char* relayState=NULL,
58                 const Credential* credential=NULL,
59                 const XMLCh* signatureAlg=NULL,
60                 const XMLCh* digestAlg=NULL
61                 ) const;
62
63         private:        
64             string m_template;
65             bool m_simple;
66         };
67
68         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const DOMElement* const & e)
69         {
70             return new SAML2POSTEncoder(e, false);
71         }
72
73         MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const DOMElement* const & e)
74         {
75             return new SAML2POSTEncoder(e, true);
76         }
77     };
78 };
79
80 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
81
82 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, bool simple) : m_simple(simple)
83 {
84     if (e) {
85         auto_ptr_char t(e->getAttributeNS(NULL, _template));
86         if (t.get())
87             m_template = t.get();
88     }
89     if (m_template.empty())
90         throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
91 }
92
93 long SAML2POSTEncoder::encode(
94     GenericResponse& genericResponse,
95     XMLObject* xmlObject,
96     const char* destination,
97     const EntityDescriptor* recipient,
98     const char* relayState,
99     const Credential* credential,
100     const XMLCh* signatureAlg,
101     const XMLCh* digestAlg
102     ) const
103 {
104 #ifdef _DEBUG
105     xmltooling::NDC ndc("encode");
106 #endif
107     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
108
109     log.debug("validating input");
110     if (xmlObject->getParent())
111         throw BindingException("Cannot encode XML content with parent.");
112     
113     StatusResponseType* response = NULL;
114     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
115     if (!request) {
116         response = dynamic_cast<StatusResponseType*>(xmlObject);
117         if (!response)
118             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
119     }
120     
121     DOMElement* rootElement = NULL;
122     if (credential && !m_simple) {
123         // Signature based on native XML signing.
124         if (request ? request->getSignature() : response->getSignature()) {
125             log.debug("message already signed, skipping signature operation");
126         }
127         else {
128             log.debug("signing and marshalling the message");
129
130             // Build a Signature.
131             Signature* sig = SignatureBuilder::buildSignature();
132             request ? request->setSignature(sig) : response->setSignature(sig);    
133             if (signatureAlg)
134                 sig->setSignatureAlgorithm(signatureAlg);
135             if (digestAlg) {
136                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
137                 if (cr)
138                     cr->setDigestAlgorithm(digestAlg);
139             }
140             
141             // Sign response while marshalling.
142             vector<Signature*> sigs(1,sig);
143             rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
144         }
145     }
146     else {
147         log.debug("marshalling the message");
148         rootElement = xmlObject->marshall((DOMDocument*)NULL);
149     }
150     
151     // Start tracking data.
152     TemplateEngine::TemplateParameters pmap;
153     if (relayState && *relayState)
154         pmap.m_map["RelayState"] = relayState;
155
156     // Serialize the message.
157     string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
158     XMLHelper::serialize(rootElement, msg);
159
160     // SimpleSign.
161     if (credential && m_simple) {
162         log.debug("applying simple signature to message data");
163         string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
164         if (relayState && *relayState)
165             input = input + "&RelayState=" + relayState;
166         if (!signatureAlg)
167             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
168         auto_ptr_char alg(signatureAlg);
169         pmap.m_map["SigAlg"] = alg.get();
170         input = input + "&SigAlg=" + alg.get();
171
172         char sigbuf[1024];
173         memset(sigbuf,0,sizeof(sigbuf));
174         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
175         pmap.m_map["Signature"] = sigbuf;
176     }
177     
178     // Base64 the message.
179     unsigned int len=0;
180     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
181     if (!out)
182         throw BindingException("Base64 encoding of XML failed.");
183     msg.erase();
184     msg.append(reinterpret_cast<char*>(out),len);
185     XMLString::release(&out);
186     
187     // Push message into template and send result to client.
188     log.debug("message encoded, sending HTML form template to client");
189     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
190     if (!engine)
191         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
192     ifstream infile(m_template.c_str());
193     if (!infile)
194         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
195     pmap.m_map["action"] = destination;
196     stringstream s;
197     engine->run(infile, s, pmap);
198     genericResponse.setContentType("text/html");
199     long ret = genericResponse.sendResponse(s);
200
201     // Cleanup by destroying XML.
202     delete xmlObject;
203     return ret;
204 }