f2f7714415c60871d1b80f0b299ecb133ebec3ee
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2009 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=NULL,
64                 const char* relayState=NULL,
65                 const ArtifactGenerator* artifactGenerator=NULL,
66                 const Credential* credential=NULL,
67                 const XMLCh* signatureAlg=NULL,
68                 const XMLCh* digestAlg=NULL
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) : m_simple(simple)
91 {
92     if (e) {
93         auto_ptr_char t(e->getAttributeNS(ns, _template));
94         if (t.get() && *t.get())
95             m_template = t.get();
96     }
97     if (m_template.empty())
98         throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
99     XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
100 }
101
102 long SAML2POSTEncoder::encode(
103     GenericResponse& genericResponse,
104     XMLObject* xmlObject,
105     const char* destination,
106     const EntityDescriptor* recipient,
107     const char* relayState,
108     const ArtifactGenerator* artifactGenerator,
109     const Credential* credential,
110     const XMLCh* signatureAlg,
111     const XMLCh* digestAlg
112     ) const
113 {
114 #ifdef _DEBUG
115     xmltooling::NDC ndc("encode");
116 #endif
117     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
118
119     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
120     if (!engine)
121         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
122     
123     log.debug("validating input");
124     if (xmlObject->getParent())
125         throw BindingException("Cannot encode XML content with parent.");
126     
127     StatusResponseType* response = NULL;
128     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
129     if (!request) {
130         response = dynamic_cast<StatusResponseType*>(xmlObject);
131         if (!response)
132             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
133     }
134     
135     DOMElement* rootElement = NULL;
136     if (credential && !m_simple) {
137         // Signature based on native XML signing.
138         if (request ? request->getSignature() : response->getSignature()) {
139             log.debug("message already signed, skipping signature operation");
140         }
141         else {
142             log.debug("signing and marshalling the message");
143
144             // Build a Signature.
145             Signature* sig = SignatureBuilder::buildSignature();
146             request ? request->setSignature(sig) : response->setSignature(sig);    
147             if (signatureAlg)
148                 sig->setSignatureAlgorithm(signatureAlg);
149             if (digestAlg) {
150                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
151                 if (cr)
152                     cr->setDigestAlgorithm(digestAlg);
153             }
154             
155             // Sign response while marshalling.
156             vector<Signature*> sigs(1,sig);
157             rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
158         }
159     }
160     else {
161         log.debug("marshalling the message");
162         rootElement = xmlObject->marshall((DOMDocument*)NULL);
163     }
164     
165     // Serialize the message.
166     TemplateEngine::TemplateParameters pmap;
167     string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
168     XMLHelper::serialize(rootElement, msg);
169     log.debug("marshalled message:\n%s", msg.c_str());
170     
171     // SimpleSign.
172     if (credential && m_simple) {
173         log.debug("applying simple signature to message data");
174         string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
175         if (relayState && *relayState)
176             input = input + "&RelayState=" + relayState;
177         if (!signatureAlg)
178             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
179         auto_ptr_char alg(signatureAlg);
180         pmap.m_map["SigAlg"] = alg.get();
181         input = input + "&SigAlg=" + alg.get();
182
183         char sigbuf[1024];
184         memset(sigbuf,0,sizeof(sigbuf));
185         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
186         pmap.m_map["Signature"] = sigbuf;
187
188         auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
189         if (keyInfo.get()) {
190             string& kstring = pmap.m_map["KeyInfo"];
191             XMLHelper::serialize(keyInfo->marshall((DOMDocument*)NULL), kstring);
192             xsecsize_t len=0;
193             XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
194             if (!out)
195                 throw BindingException("Base64 encoding of XML failed.");
196             kstring.erase();
197             kstring.append(reinterpret_cast<char*>(out),len);
198 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
199             XMLString::release(&out);
200 #else
201             XMLString::release((char**)&out);
202 #endif
203         }
204     }
205     
206     // Base64 the message.
207     xsecsize_t len=0;
208     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
209     if (!out)
210         throw BindingException("Base64 encoding of XML failed.");
211     msg.erase();
212     msg.append(reinterpret_cast<char*>(out),len);
213 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
214     XMLString::release(&out);
215 #else
216     XMLString::release((char**)&out);
217 #endif
218     
219     // Push the rest of it into template and send result to client.
220     log.debug("message encoded, sending HTML form template to client");
221     ifstream infile(m_template.c_str());
222     if (!infile)
223         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
224     pmap.m_map["action"] = destination;
225     if (relayState && *relayState)
226         pmap.m_map["RelayState"] = relayState;
227     stringstream s;
228     engine->run(infile, s, pmap);
229     genericResponse.setContentType("text/html");
230     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
231     if (httpResponse) {
232         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
233         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
234         httpResponse->setResponseHeader("Pragma", "no-cache");
235     }
236     long ret = genericResponse.sendResponse(s);
237
238     // Cleanup by destroying XML.
239     delete xmlObject;
240     return ret;
241 }