2 * Copyright 2001-2009 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=NULL,
64 const char* relayState=NULL,
65 const ArtifactGenerator* artifactGenerator=NULL,
66 const Credential* credential=NULL,
67 const XMLCh* signatureAlg=NULL,
68 const XMLCh* digestAlg=NULL
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) : m_simple(simple)
93 auto_ptr_char t(e->getAttributeNS(ns, _template));
94 if (t.get() && *t.get())
97 if (m_template.empty())
98 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
99 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
102 long SAML2POSTEncoder::encode(
103 GenericResponse& genericResponse,
104 XMLObject* xmlObject,
105 const char* destination,
106 const EntityDescriptor* recipient,
107 const char* relayState,
108 const ArtifactGenerator* artifactGenerator,
109 const Credential* credential,
110 const XMLCh* signatureAlg,
111 const XMLCh* digestAlg
115 xmltooling::NDC ndc("encode");
117 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
119 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
121 throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
123 log.debug("validating input");
124 if (xmlObject->getParent())
125 throw BindingException("Cannot encode XML content with parent.");
127 StatusResponseType* response = NULL;
128 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
130 response = dynamic_cast<StatusResponseType*>(xmlObject);
132 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
135 DOMElement* rootElement = NULL;
136 if (credential && !m_simple) {
137 // Signature based on native XML signing.
138 if (request ? request->getSignature() : response->getSignature()) {
139 log.debug("message already signed, skipping signature operation");
142 log.debug("signing and marshalling the message");
144 // Build a Signature.
145 Signature* sig = SignatureBuilder::buildSignature();
146 request ? request->setSignature(sig) : response->setSignature(sig);
148 sig->setSignatureAlgorithm(signatureAlg);
150 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
152 cr->setDigestAlgorithm(digestAlg);
155 // Sign response while marshalling.
156 vector<Signature*> sigs(1,sig);
157 rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
161 log.debug("marshalling the message");
162 rootElement = xmlObject->marshall((DOMDocument*)NULL);
165 // Serialize the message.
166 TemplateEngine::TemplateParameters pmap;
167 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
168 XMLHelper::serialize(rootElement, msg);
169 log.debug("marshalled message:\n%s", msg.c_str());
172 if (credential && m_simple) {
173 log.debug("applying simple signature to message data");
174 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
175 if (relayState && *relayState)
176 input = input + "&RelayState=" + relayState;
178 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
179 auto_ptr_char alg(signatureAlg);
180 pmap.m_map["SigAlg"] = alg.get();
181 input = input + "&SigAlg=" + alg.get();
184 memset(sigbuf,0,sizeof(sigbuf));
185 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
186 pmap.m_map["Signature"] = sigbuf;
188 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
190 string& kstring = pmap.m_map["KeyInfo"];
191 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)NULL), kstring);
193 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
195 throw BindingException("Base64 encoding of XML failed.");
197 kstring.append(reinterpret_cast<char*>(out),len);
198 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
199 XMLString::release(&out);
201 XMLString::release((char**)&out);
206 // Base64 the message.
208 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
210 throw BindingException("Base64 encoding of XML failed.");
212 msg.append(reinterpret_cast<char*>(out),len);
213 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
214 XMLString::release(&out);
216 XMLString::release((char**)&out);
219 // Push the rest of it into template and send result to client.
220 log.debug("message encoded, sending HTML form template to client");
221 ifstream infile(m_template.c_str());
223 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
224 pmap.m_map["action"] = destination;
225 if (relayState && *relayState)
226 pmap.m_map["RelayState"] = relayState;
228 engine->run(infile, s, pmap);
229 genericResponse.setContentType("text/html");
230 HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
232 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
233 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
234 httpResponse->setResponseHeader("Pragma", "no-cache");
236 long ret = genericResponse.sendResponse(s);
238 // Cleanup by destroying XML.