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