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/util/NDC.h>
38 #include <xmltooling/util/PathResolver.h>
39 #include <xmltooling/util/TemplateEngine.h>
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2md;
43 using namespace opensaml;
44 using namespace xmlsignature;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
51 class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
54 SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple=false);
55 virtual ~SAML2POSTEncoder() {}
58 GenericResponse& genericResponse,
60 const char* destination,
61 const EntityDescriptor* recipient=NULL,
62 const char* relayState=NULL,
63 const ArtifactGenerator* artifactGenerator=NULL,
64 const Credential* credential=NULL,
65 const XMLCh* signatureAlg=NULL,
66 const XMLCh* digestAlg=NULL
74 MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
76 return new SAML2POSTEncoder(p.first, p.second, false);
79 MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
81 return new SAML2POSTEncoder(p.first, p.second, true);
86 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
88 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple) : m_simple(simple)
91 auto_ptr_char t(e->getAttributeNS(ns, _template));
92 if (t.get() && *t.get())
95 if (m_template.empty())
96 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
97 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
100 long SAML2POSTEncoder::encode(
101 GenericResponse& genericResponse,
102 XMLObject* xmlObject,
103 const char* destination,
104 const EntityDescriptor* recipient,
105 const char* relayState,
106 const ArtifactGenerator* artifactGenerator,
107 const Credential* credential,
108 const XMLCh* signatureAlg,
109 const XMLCh* digestAlg
113 xmltooling::NDC ndc("encode");
115 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
117 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
119 throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
121 log.debug("validating input");
122 if (xmlObject->getParent())
123 throw BindingException("Cannot encode XML content with parent.");
125 StatusResponseType* response = NULL;
126 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
128 response = dynamic_cast<StatusResponseType*>(xmlObject);
130 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
133 DOMElement* rootElement = NULL;
134 if (credential && !m_simple) {
135 // Signature based on native XML signing.
136 if (request ? request->getSignature() : response->getSignature()) {
137 log.debug("message already signed, skipping signature operation");
140 log.debug("signing and marshalling the message");
142 // Build a Signature.
143 Signature* sig = SignatureBuilder::buildSignature();
144 request ? request->setSignature(sig) : response->setSignature(sig);
146 sig->setSignatureAlgorithm(signatureAlg);
148 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
150 cr->setDigestAlgorithm(digestAlg);
153 // Sign response while marshalling.
154 vector<Signature*> sigs(1,sig);
155 rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
159 log.debug("marshalling the message");
160 rootElement = xmlObject->marshall((DOMDocument*)NULL);
163 // Serialize the message.
164 TemplateEngine::TemplateParameters pmap;
165 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
166 XMLHelper::serialize(rootElement, msg);
167 log.debug("marshalled message:\n%s", msg.c_str());
170 if (credential && m_simple) {
171 log.debug("applying simple signature to message data");
172 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
173 if (relayState && *relayState)
174 input = input + "&RelayState=" + relayState;
176 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
177 auto_ptr_char alg(signatureAlg);
178 pmap.m_map["SigAlg"] = alg.get();
179 input = input + "&SigAlg=" + alg.get();
182 memset(sigbuf,0,sizeof(sigbuf));
183 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
184 pmap.m_map["Signature"] = sigbuf;
186 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
188 string& kstring = pmap.m_map["KeyInfo"];
189 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)NULL), kstring);
191 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
193 throw BindingException("Base64 encoding of XML failed.");
195 kstring.append(reinterpret_cast<char*>(out),len);
196 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
197 XMLString::release(&out);
199 XMLString::release((char**)&out);
204 // Base64 the message.
206 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
208 throw BindingException("Base64 encoding of XML failed.");
210 msg.append(reinterpret_cast<char*>(out),len);
211 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
212 XMLString::release(&out);
214 XMLString::release((char**)&out);
217 // Push the rest of it into template and send result to client.
218 log.debug("message encoded, sending HTML form template to client");
219 ifstream infile(m_template.c_str());
221 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
222 pmap.m_map["action"] = destination;
223 if (relayState && *relayState)
224 pmap.m_map["RelayState"] = relayState;
226 engine->run(infile, s, pmap);
227 genericResponse.setContentType("text/html");
228 HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
230 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
231 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
232 httpResponse->setResponseHeader("Pragma", "no-cache");
234 long ret = genericResponse.sendResponse(s);
236 // Cleanup by destroying XML.