2 * Copyright 2001-2010 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SAML2POSTEncoder.cpp
20 * SAML 2.0 HTTP-POST binding message encoder.
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml2/core/Protocols.h"
31 #include <xercesc/util/Base64.hpp>
32 #include <xsec/dsig/DSIGConstants.hpp>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPResponse.h>
36 #include <xmltooling/security/Credential.h>
37 #include <xmltooling/signature/KeyInfo.h>
38 #include <xmltooling/signature/Signature.h>
39 #include <xmltooling/util/NDC.h>
40 #include <xmltooling/util/PathResolver.h>
41 #include <xmltooling/util/TemplateEngine.h>
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2md;
45 using namespace opensaml;
46 using namespace xmlsignature;
47 using namespace xmltooling::logging;
48 using namespace xmltooling;
53 class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
56 SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple=false);
57 virtual ~SAML2POSTEncoder() {}
60 GenericResponse& genericResponse,
62 const char* destination,
63 const EntityDescriptor* recipient=nullptr,
64 const char* relayState=nullptr,
65 const ArtifactGenerator* artifactGenerator=nullptr,
66 const Credential* credential=nullptr,
67 const XMLCh* signatureAlg=nullptr,
68 const XMLCh* digestAlg=nullptr
76 MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
78 return new SAML2POSTEncoder(p.first, p.second, false);
81 MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
83 return new SAML2POSTEncoder(p.first, p.second, true);
88 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
90 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple)
91 : m_template(XMLHelper::getAttrString(e, "bindingTemplate.html", _template, ns)), m_simple(simple)
93 if (m_template.empty())
94 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
95 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
98 long SAML2POSTEncoder::encode(
99 GenericResponse& genericResponse,
100 XMLObject* xmlObject,
101 const char* destination,
102 const EntityDescriptor* recipient,
103 const char* relayState,
104 const ArtifactGenerator* artifactGenerator,
105 const Credential* credential,
106 const XMLCh* signatureAlg,
107 const XMLCh* digestAlg
111 xmltooling::NDC ndc("encode");
113 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
114 log.debug("validating input");
116 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
117 if (!engine || !destination)
118 throw BindingException("Encoding message using POST requires a TemplateEngine instance and a destination.");
119 HTTPResponse::sanitizeURL(destination);
120 if (xmlObject->getParent())
121 throw BindingException("Cannot encode XML content with parent.");
123 StatusResponseType* response = nullptr;
124 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
126 response = dynamic_cast<StatusResponseType*>(xmlObject);
128 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
131 DOMElement* rootElement = nullptr;
132 if (credential && !m_simple) {
133 // Signature based on native XML signing.
134 if (request ? request->getSignature() : response->getSignature()) {
135 log.debug("message already signed, skipping signature operation");
138 log.debug("signing and marshalling the message");
140 // Build a Signature.
141 Signature* sig = SignatureBuilder::buildSignature();
142 request ? request->setSignature(sig) : response->setSignature(sig);
144 sig->setSignatureAlgorithm(signatureAlg);
146 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
148 cr->setDigestAlgorithm(digestAlg);
151 // Sign response while marshalling.
152 vector<Signature*> sigs(1,sig);
153 rootElement = xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
157 log.debug("marshalling the message");
158 rootElement = xmlObject->marshall((DOMDocument*)nullptr);
161 // Serialize the message.
162 TemplateEngine::TemplateParameters pmap;
163 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
164 XMLHelper::serialize(rootElement, msg);
165 log.debug("marshalled message:\n%s", msg.c_str());
168 if (credential && m_simple) {
169 log.debug("applying simple signature to message data");
170 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
171 if (relayState && *relayState)
172 input = input + "&RelayState=" + relayState;
174 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
175 auto_ptr_char alg(signatureAlg);
176 pmap.m_map["SigAlg"] = alg.get();
177 input = input + "&SigAlg=" + alg.get();
180 memset(sigbuf,0,sizeof(sigbuf));
181 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
182 pmap.m_map["Signature"] = sigbuf;
184 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
186 string& kstring = pmap.m_map["KeyInfo"];
187 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)nullptr), kstring);
189 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
191 throw BindingException("Base64 encoding of XML failed.");
193 kstring.append(reinterpret_cast<char*>(out),len);
194 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
195 XMLString::release(&out);
197 XMLString::release((char**)&out);
202 // Base64 the message.
204 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
206 throw BindingException("Base64 encoding of XML failed.");
208 msg.append(reinterpret_cast<char*>(out),len);
209 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
210 XMLString::release(&out);
212 XMLString::release((char**)&out);
215 // Push the rest of it into template and send result to client.
216 log.debug("message encoded, sending HTML form template to client");
217 ifstream infile(m_template.c_str());
219 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
220 pmap.m_map["action"] = destination;
221 if (relayState && *relayState)
222 pmap.m_map["RelayState"] = relayState;
224 engine->run(infile, s, pmap);
225 genericResponse.setContentType("text/html");
226 HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
228 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
229 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
230 httpResponse->setResponseHeader("Pragma", "no-cache");
232 long ret = genericResponse.sendResponse(s);
234 // Cleanup by destroying XML.