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() {}
59 const XMLCh* getProtocolFamily() const {
60 return samlconstants::SAML20P_NS;
63 const char* getShortName() const {
64 return m_simple ? "POST-SimpleSign" : "POST";
68 GenericResponse& genericResponse,
70 const char* destination,
71 const EntityDescriptor* recipient=nullptr,
72 const char* relayState=nullptr,
73 const ArtifactGenerator* artifactGenerator=nullptr,
74 const Credential* credential=nullptr,
75 const XMLCh* signatureAlg=nullptr,
76 const XMLCh* digestAlg=nullptr
84 MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
86 return new SAML2POSTEncoder(p.first, p.second, false);
89 MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
91 return new SAML2POSTEncoder(p.first, p.second, true);
96 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
98 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple)
99 : m_template(XMLHelper::getAttrString(e, "bindingTemplate.html", _template, ns)), m_simple(simple)
101 if (m_template.empty())
102 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
103 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
106 long SAML2POSTEncoder::encode(
107 GenericResponse& genericResponse,
108 XMLObject* xmlObject,
109 const char* destination,
110 const EntityDescriptor* recipient,
111 const char* relayState,
112 const ArtifactGenerator* artifactGenerator,
113 const Credential* credential,
114 const XMLCh* signatureAlg,
115 const XMLCh* digestAlg
119 xmltooling::NDC ndc("encode");
121 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
122 log.debug("validating input");
124 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
125 if (!engine || !destination)
126 throw BindingException("Encoding message using POST requires a TemplateEngine instance and a destination.");
127 HTTPResponse::sanitizeURL(destination);
128 if (xmlObject->getParent())
129 throw BindingException("Cannot encode XML content with parent.");
131 StatusResponseType* response = nullptr;
132 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
134 response = dynamic_cast<StatusResponseType*>(xmlObject);
136 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
139 DOMElement* rootElement = nullptr;
140 if (credential && !m_simple) {
141 // Signature based on native XML signing.
142 if (request ? request->getSignature() : response->getSignature()) {
143 log.debug("message already signed, skipping signature operation");
146 log.debug("signing and marshalling the message");
148 // Build a Signature.
149 Signature* sig = SignatureBuilder::buildSignature();
150 request ? request->setSignature(sig) : response->setSignature(sig);
152 sig->setSignatureAlgorithm(signatureAlg);
154 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
156 cr->setDigestAlgorithm(digestAlg);
159 // Sign response while marshalling.
160 vector<Signature*> sigs(1,sig);
161 rootElement = xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
165 log.debug("marshalling the message");
166 rootElement = xmlObject->marshall((DOMDocument*)nullptr);
169 // Serialize the message.
170 TemplateEngine::TemplateParameters pmap;
171 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
172 XMLHelper::serialize(rootElement, msg);
173 log.debug("marshalled message:\n%s", msg.c_str());
176 if (credential && m_simple) {
177 log.debug("applying simple signature to message data");
178 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
179 if (relayState && *relayState)
180 input = input + "&RelayState=" + relayState;
182 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
183 auto_ptr_char alg(signatureAlg);
184 pmap.m_map["SigAlg"] = alg.get();
185 input = input + "&SigAlg=" + alg.get();
188 memset(sigbuf,0,sizeof(sigbuf));
189 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
190 pmap.m_map["Signature"] = sigbuf;
192 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
194 string& kstring = pmap.m_map["KeyInfo"];
195 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)nullptr), kstring);
197 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
199 throw BindingException("Base64 encoding of XML failed.");
201 kstring.append(reinterpret_cast<char*>(out),len);
202 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
203 XMLString::release(&out);
205 XMLString::release((char**)&out);
210 // Base64 the message.
212 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
214 throw BindingException("Base64 encoding of XML failed.");
216 msg.append(reinterpret_cast<char*>(out),len);
217 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
218 XMLString::release(&out);
220 XMLString::release((char**)&out);
223 // Push the rest of it into template and send result to client.
224 log.debug("message encoded, sending HTML form template to client");
225 ifstream infile(m_template.c_str());
227 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
228 pmap.m_map["action"] = destination;
229 if (relayState && *relayState)
230 pmap.m_map["RelayState"] = relayState;
232 engine->run(infile, s, pmap);
233 genericResponse.setContentType("text/html");
234 HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
236 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
237 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
238 httpResponse->setResponseHeader("Pragma", "no-cache");
240 long ret = genericResponse.sendResponse(s);
242 // Cleanup by destroying XML.