2db3d1471efb3cc9305899b0eaaf6a96bc5a9704
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTEncoder.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML1POSTEncoder.cpp
23  * 
24  * SAML 1.x POST binding/profile message encoder.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/MessageEncoder.h"
30 #include "signature/ContentReference.h"
31 #include "saml1/core/Protocols.h"
32
33 #include <fstream>
34 #include <sstream>
35 #include <xercesc/util/Base64.hpp>
36 #include <xsec/framework/XSECDefs.hpp>
37 #include <xmltooling/io/HTTPResponse.h>
38 #include <xmltooling/logging.h>
39 #include <xmltooling/XMLToolingConfig.h>
40 #include <xmltooling/signature/Signature.h>
41 #include <xmltooling/util/NDC.h>
42 #include <xmltooling/util/PathResolver.h>
43 #include <xmltooling/util/TemplateEngine.h>
44
45 using namespace opensaml::saml1p;
46 using namespace opensaml::saml2md;
47 using namespace opensaml;
48 using namespace xmlsignature;
49 using namespace xmltooling::logging;
50 using namespace xmltooling;
51 using namespace std;
52
53 namespace opensaml {
54     namespace saml1p {              
55         class SAML_DLLLOCAL SAML1POSTEncoder : public MessageEncoder
56         {
57         public:
58             SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns);
59             virtual ~SAML1POSTEncoder() {}
60
61             const XMLCh* getProtocolFamily() const {
62                 return samlconstants::SAML11_PROTOCOL_ENUM;
63             }
64
65             long encode(
66                 GenericResponse& genericResponse,
67                 XMLObject* xmlObject,
68                 const char* destination,
69                 const EntityDescriptor* recipient=nullptr,
70                 const char* relayState=nullptr,
71                 const ArtifactGenerator* artifactGenerator=nullptr,
72                 const Credential* credential=nullptr,
73                 const XMLCh* signatureAlg=nullptr,
74                 const XMLCh* digestAlg=nullptr
75                 ) const;
76
77         protected:
78             /** Pathname of HTML template for transmission of message via POST. */
79             string m_template;
80         };
81
82         MessageEncoder* SAML_DLLLOCAL SAML1POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
83         {
84             return new SAML1POSTEncoder(p.first, p.second);
85         }
86     };
87 };
88
89 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
90
91 SAML1POSTEncoder::SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns)
92     : m_template(XMLHelper::getAttrString(e, "bindingTemplate.html", _template, ns))
93 {
94     if (m_template.empty())
95         throw XMLToolingException("SAML1POSTEncoder requires template XML attribute.");
96     XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
97 }
98
99 long SAML1POSTEncoder::encode(
100     GenericResponse& genericResponse,
101     XMLObject* xmlObject,
102     const char* destination,
103     const EntityDescriptor* recipient,
104     const char* relayState,
105     const ArtifactGenerator* artifactGenerator,
106     const Credential* credential,
107     const XMLCh* signatureAlg,
108     const XMLCh* digestAlg
109     ) const
110 {
111 #ifdef _DEBUG
112     xmltooling::NDC ndc("encode");
113 #endif
114     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1POST");
115     log.debug("validating input");
116
117     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
118     if (!engine || !destination)
119         throw BindingException("Encoding response using POST requires a TemplateEngine instance and a destination.");
120     HTTPResponse::sanitizeURL(destination);
121     if (xmlObject->getParent())
122         throw BindingException("Cannot encode XML content with parent.");
123     Response* response = dynamic_cast<Response*>(xmlObject);
124     if (!response)
125         throw BindingException("XML content for SAML 1.x POST Encoder must be a SAML 1.x <Response>.");
126     if (!relayState)
127         throw BindingException("SAML 1.x POST Encoder requires relay state (TARGET) value.");
128     
129     DOMElement* rootElement = nullptr;
130     if (credential) {
131         // Signature based on native XML signing.
132         if (response->getSignature()) {
133             log.debug("response already signed, skipping signature operation");
134         }
135         else {
136             log.debug("signing and marshalling the response");
137
138             // Build a Signature.
139             Signature* sig = SignatureBuilder::buildSignature();
140             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 = response->marshall((DOMDocument*)nullptr,&sigs,credential);
152         }
153     }
154     else {
155         log.debug("marshalling the response");
156         rootElement = response->marshall();
157     }
158
159     // Push message into template.
160     TemplateEngine::TemplateParameters pmap;
161     string& xmlbuf = pmap.m_map["SAMLResponse"];
162     XMLHelper::serialize(rootElement, xmlbuf);
163     log.debug("marshalled response:\n%s", xmlbuf.c_str());
164     
165     // Replace with base-64 encoded version.
166     xsecsize_t len=0;
167     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
168     if (out) {
169         xmlbuf.erase();
170         xmlbuf.append(reinterpret_cast<char*>(out),len);
171 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
172         XMLString::release(&out);
173 #else
174         XMLString::release((char**)&out);
175 #endif
176     }
177     else {
178         throw BindingException("Base64 encoding of XML failed.");
179     }
180
181     // Fill in the rest of the data and send to the client.
182     log.debug("message encoded, sending HTML form template to client");
183     ifstream infile(m_template.c_str());
184     if (!infile)
185         throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
186     pmap.m_map["action"] = destination;
187     pmap.m_map["TARGET"] = relayState;
188     stringstream s;
189     engine->run(infile, s, pmap);
190     genericResponse.setContentType("text/html");
191     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
192     if (httpResponse) {
193         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
194         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
195         httpResponse->setResponseHeader("Pragma", "no-cache");
196     }
197     long ret = genericResponse.sendResponse(s);
198
199     // Cleanup by destroying XML.
200     delete xmlObject;
201     return ret;
202 }