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