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