https://issues.shibboleth.net/jira/browse/SSPCPP-255
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTEncoder.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  * SAML1POSTEncoder.cpp
19  * 
20  * SAML 1.x POST binding/profile message encoder.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml1/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <xercesc/util/Base64.hpp>
32 #include <xsec/framework/XSECDefs.hpp>
33 #include <xmltooling/io/HTTPResponse.h>
34 #include <xmltooling/logging.h>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/signature/Signature.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/TemplateEngine.h>
40
41 using namespace opensaml::saml1p;
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 saml1p {              
51         class SAML_DLLLOCAL SAML1POSTEncoder : public MessageEncoder
52         {
53         public:
54             SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns);
55             virtual ~SAML1POSTEncoder() {}
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         protected:
70             /** Pathname of HTML template for transmission of message via POST. */
71             string m_template;
72         };
73
74         MessageEncoder* SAML_DLLLOCAL SAML1POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
75         {
76             return new SAML1POSTEncoder(p.first, p.second);
77         }
78     };
79 };
80
81 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
82
83 SAML1POSTEncoder::SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns)
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("SAML1POSTEncoder requires template XML attribute.");
92     XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
93 }
94
95 long SAML1POSTEncoder::encode(
96     GenericResponse& genericResponse,
97     XMLObject* xmlObject,
98     const char* destination,
99     const EntityDescriptor* recipient,
100     const char* relayState,
101     const ArtifactGenerator* artifactGenerator,
102     const Credential* credential,
103     const XMLCh* signatureAlg,
104     const XMLCh* digestAlg
105     ) const
106 {
107 #ifdef _DEBUG
108     xmltooling::NDC ndc("encode");
109 #endif
110     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1POST");
111     log.debug("validating input");
112
113     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
114     if (!engine || !destination)
115         throw BindingException("Encoding response using POST requires a TemplateEngine instance and a destination.");
116     HTTPResponse::sanitizeURL(destination);
117     if (xmlObject->getParent())
118         throw BindingException("Cannot encode XML content with parent.");
119     Response* response = dynamic_cast<Response*>(xmlObject);
120     if (!response)
121         throw BindingException("XML content for SAML 1.x POST Encoder must be a SAML 1.x <Response>.");
122     if (!relayState)
123         throw BindingException("SAML 1.x POST Encoder requires relay state (TARGET) value.");
124     
125     DOMElement* rootElement = NULL;
126     if (credential) {
127         // Signature based on native XML signing.
128         if (response->getSignature()) {
129             log.debug("response already signed, skipping signature operation");
130         }
131         else {
132             log.debug("signing and marshalling the response");
133
134             // Build a Signature.
135             Signature* sig = SignatureBuilder::buildSignature();
136             response->setSignature(sig);
137             if (signatureAlg)
138                 sig->setSignatureAlgorithm(signatureAlg);
139             if (digestAlg) {
140                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
141                 if (cr)
142                     cr->setDigestAlgorithm(digestAlg);
143             }
144     
145             // Sign response while marshalling.
146             vector<Signature*> sigs(1,sig);
147             rootElement = response->marshall((DOMDocument*)NULL,&sigs,credential);
148         }
149     }
150     else {
151         log.debug("marshalling the response");
152         rootElement = response->marshall();
153     }
154
155     // Push message into template.
156     TemplateEngine::TemplateParameters pmap;
157     string& xmlbuf = pmap.m_map["SAMLResponse"];
158     XMLHelper::serialize(rootElement, xmlbuf);
159     log.debug("marshalled response:\n%s", xmlbuf.c_str());
160     
161     // Replace with base-64 encoded version.
162     xsecsize_t len=0;
163     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
164     if (out) {
165         xmlbuf.erase();
166         xmlbuf.append(reinterpret_cast<char*>(out),len);
167 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
168         XMLString::release(&out);
169 #else
170         XMLString::release((char**)&out);
171 #endif
172     }
173     else {
174         throw BindingException("Base64 encoding of XML failed.");
175     }
176
177     // Fill in the rest of the data and send to the client.
178     log.debug("message encoded, sending HTML form template to client");
179     ifstream infile(m_template.c_str());
180     if (!infile)
181         throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
182     pmap.m_map["action"] = destination;
183     pmap.m_map["TARGET"] = relayState;
184     stringstream s;
185     engine->run(infile, s, pmap);
186     genericResponse.setContentType("text/html");
187     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
188     if (httpResponse) {
189         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
190         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
191         httpResponse->setResponseHeader("Pragma", "no-cache");
192     }
193     long ret = genericResponse.sendResponse(s);
194
195     // Cleanup by destroying XML.
196     delete xmlObject;
197     return ret;
198 }