2 * Copyright 2001-2007 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 <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>
38 using namespace opensaml::saml2p;
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmlsignature;
42 using namespace xmltooling::logging;
43 using namespace xmltooling;
48 class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
51 SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple=false);
52 virtual ~SAML2POSTEncoder() {}
55 GenericResponse& genericResponse,
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
71 MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
73 return new SAML2POSTEncoder(p.first, p.second, false);
76 MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
78 return new SAML2POSTEncoder(p.first, p.second, true);
83 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
85 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple) : m_simple(simple)
88 auto_ptr_char t(e->getAttributeNS(ns, _template));
89 if (t.get() && *t.get())
92 if (m_template.empty())
93 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
94 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
97 long SAML2POSTEncoder::encode(
98 GenericResponse& genericResponse,
100 const char* destination,
101 const EntityDescriptor* recipient,
102 const char* relayState,
103 const ArtifactGenerator* artifactGenerator,
104 const Credential* credential,
105 const XMLCh* signatureAlg,
106 const XMLCh* digestAlg
110 xmltooling::NDC ndc("encode");
112 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
114 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
116 throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
118 log.debug("validating input");
119 if (xmlObject->getParent())
120 throw BindingException("Cannot encode XML content with parent.");
122 StatusResponseType* response = NULL;
123 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
125 response = dynamic_cast<StatusResponseType*>(xmlObject);
127 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
130 DOMElement* rootElement = NULL;
131 if (credential && !m_simple) {
132 // Signature based on native XML signing.
133 if (request ? request->getSignature() : response->getSignature()) {
134 log.debug("message already signed, skipping signature operation");
137 log.debug("signing and marshalling the message");
139 // Build a Signature.
140 Signature* sig = SignatureBuilder::buildSignature();
141 request ? request->setSignature(sig) : response->setSignature(sig);
143 sig->setSignatureAlgorithm(signatureAlg);
145 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
147 cr->setDigestAlgorithm(digestAlg);
150 // Sign response while marshalling.
151 vector<Signature*> sigs(1,sig);
152 rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
156 log.debug("marshalling the message");
157 rootElement = xmlObject->marshall((DOMDocument*)NULL);
160 // Serialize the message.
161 TemplateEngine::TemplateParameters pmap;
162 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
163 XMLHelper::serialize(rootElement, msg);
164 log.debug("marshalled message:\n%s", msg.c_str());
167 if (credential && m_simple) {
168 log.debug("applying simple signature to message data");
169 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
170 if (relayState && *relayState)
171 input = input + "&RelayState=" + relayState;
173 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
174 auto_ptr_char alg(signatureAlg);
175 pmap.m_map["SigAlg"] = alg.get();
176 input = input + "&SigAlg=" + alg.get();
179 memset(sigbuf,0,sizeof(sigbuf));
180 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
181 pmap.m_map["Signature"] = sigbuf;
183 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
185 string& kstring = pmap.m_map["KeyInfo"];
186 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)NULL), kstring);
188 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
190 throw BindingException("Base64 encoding of XML failed.");
192 kstring.append(reinterpret_cast<char*>(out),len);
193 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
194 XMLString::release(&out);
196 XMLString::release((char**)&out);
201 // Base64 the message.
203 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
205 throw BindingException("Base64 encoding of XML failed.");
207 msg.append(reinterpret_cast<char*>(out),len);
208 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
209 XMLString::release(&out);
211 XMLString::release((char**)&out);
214 // Push the rest of it into template and send result to client.
215 log.debug("message encoded, sending HTML form template to client");
216 ifstream infile(m_template.c_str());
218 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
219 pmap.m_map["action"] = destination;
220 if (relayState && *relayState)
221 pmap.m_map["RelayState"] = relayState;
223 engine->run(infile, s, pmap);
224 genericResponse.setContentType("text/html");
225 HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
227 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
228 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
229 httpResponse->setResponseHeader("Pragma", "no-cache");
231 long ret = genericResponse.sendResponse(s);
233 // Cleanup by destroying XML.