Update ctors to use new attribute shortcuts.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2010 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 <xercesc/util/Base64.hpp>
32 #include <xsec/dsig/DSIGConstants.hpp>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPResponse.h>
36 #include <xmltooling/security/Credential.h>
37 #include <xmltooling/signature/KeyInfo.h>
38 #include <xmltooling/signature/Signature.h>
39 #include <xmltooling/util/NDC.h>
40 #include <xmltooling/util/PathResolver.h>
41 #include <xmltooling/util/TemplateEngine.h>
42
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
46 using namespace xmlsignature;
47 using namespace xmltooling::logging;
48 using namespace xmltooling;
49 using namespace std;
50
51 namespace opensaml {
52     namespace saml2p {              
53         class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
54         {
55         public:
56             SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple=false);
57             virtual ~SAML2POSTEncoder() {}
58             
59             long encode(
60                 GenericResponse& genericResponse,
61                 XMLObject* xmlObject,
62                 const char* destination,
63                 const EntityDescriptor* recipient=nullptr,
64                 const char* relayState=nullptr,
65                 const ArtifactGenerator* artifactGenerator=nullptr,
66                 const Credential* credential=nullptr,
67                 const XMLCh* signatureAlg=nullptr,
68                 const XMLCh* digestAlg=nullptr
69                 ) const;
70
71         private:        
72             string m_template;
73             bool m_simple;
74         };
75
76         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
77         {
78             return new SAML2POSTEncoder(p.first, p.second, false);
79         }
80
81         MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
82         {
83             return new SAML2POSTEncoder(p.first, p.second, true);
84         }
85     };
86 };
87
88 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
89
90 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple)
91     : m_template(XMLHelper::getAttrString(e, nullptr, _template, ns)), m_simple(simple)
92 {
93     if (m_template.empty())
94         throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
95     XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
96 }
97
98 long SAML2POSTEncoder::encode(
99     GenericResponse& genericResponse,
100     XMLObject* xmlObject,
101     const char* destination,
102     const EntityDescriptor* recipient,
103     const char* relayState,
104     const ArtifactGenerator* artifactGenerator,
105     const Credential* credential,
106     const XMLCh* signatureAlg,
107     const XMLCh* digestAlg
108     ) const
109 {
110 #ifdef _DEBUG
111     xmltooling::NDC ndc("encode");
112 #endif
113     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
114     log.debug("validating input");
115
116     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
117     if (!engine || !destination)
118         throw BindingException("Encoding message using POST requires a TemplateEngine instance and a destination.");
119     HTTPResponse::sanitizeURL(destination);
120     if (xmlObject->getParent())
121         throw BindingException("Cannot encode XML content with parent.");
122     
123     StatusResponseType* response = nullptr;
124     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
125     if (!request) {
126         response = dynamic_cast<StatusResponseType*>(xmlObject);
127         if (!response)
128             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
129     }
130     
131     DOMElement* rootElement = nullptr;
132     if (credential && !m_simple) {
133         // Signature based on native XML signing.
134         if (request ? request->getSignature() : response->getSignature()) {
135             log.debug("message already signed, skipping signature operation");
136         }
137         else {
138             log.debug("signing and marshalling the message");
139
140             // Build a Signature.
141             Signature* sig = SignatureBuilder::buildSignature();
142             request ? request->setSignature(sig) : response->setSignature(sig);    
143             if (signatureAlg)
144                 sig->setSignatureAlgorithm(signatureAlg);
145             if (digestAlg) {
146                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
147                 if (cr)
148                     cr->setDigestAlgorithm(digestAlg);
149             }
150             
151             // Sign response while marshalling.
152             vector<Signature*> sigs(1,sig);
153             rootElement = xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
154         }
155     }
156     else {
157         log.debug("marshalling the message");
158         rootElement = xmlObject->marshall((DOMDocument*)nullptr);
159     }
160     
161     // Serialize the message.
162     TemplateEngine::TemplateParameters pmap;
163     string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
164     XMLHelper::serialize(rootElement, msg);
165     log.debug("marshalled message:\n%s", msg.c_str());
166     
167     // SimpleSign.
168     if (credential && m_simple) {
169         log.debug("applying simple signature to message data");
170         string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
171         if (relayState && *relayState)
172             input = input + "&RelayState=" + relayState;
173         if (!signatureAlg)
174             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
175         auto_ptr_char alg(signatureAlg);
176         pmap.m_map["SigAlg"] = alg.get();
177         input = input + "&SigAlg=" + alg.get();
178
179         char sigbuf[1024];
180         memset(sigbuf,0,sizeof(sigbuf));
181         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
182         pmap.m_map["Signature"] = sigbuf;
183
184         auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
185         if (keyInfo.get()) {
186             string& kstring = pmap.m_map["KeyInfo"];
187             XMLHelper::serialize(keyInfo->marshall((DOMDocument*)nullptr), kstring);
188             xsecsize_t len=0;
189             XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
190             if (!out)
191                 throw BindingException("Base64 encoding of XML failed.");
192             kstring.erase();
193             kstring.append(reinterpret_cast<char*>(out),len);
194 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
195             XMLString::release(&out);
196 #else
197             XMLString::release((char**)&out);
198 #endif
199         }
200     }
201     
202     // Base64 the message.
203     xsecsize_t len=0;
204     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
205     if (!out)
206         throw BindingException("Base64 encoding of XML failed.");
207     msg.erase();
208     msg.append(reinterpret_cast<char*>(out),len);
209 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
210     XMLString::release(&out);
211 #else
212     XMLString::release((char**)&out);
213 #endif
214     
215     // Push the rest of it into template and send result to client.
216     log.debug("message encoded, sending HTML form template to client");
217     ifstream infile(m_template.c_str());
218     if (!infile)
219         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
220     pmap.m_map["action"] = destination;
221     if (relayState && *relayState)
222         pmap.m_map["RelayState"] = relayState;
223     stringstream s;
224     engine->run(infile, s, pmap);
225     genericResponse.setContentType("text/html");
226     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
227     if (httpResponse) {
228         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
229         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
230         httpResponse->setResponseHeader("Pragma", "no-cache");
231     }
232     long ret = genericResponse.sendResponse(s);
233
234     // Cleanup by destroying XML.
235     delete xmlObject;
236     return ret;
237 }