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