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