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/logging.h>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/PathResolver.h>
35 #include <xmltooling/util/TemplateEngine.h>
37 using namespace opensaml::saml2p;
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
40 using namespace xmlsignature;
41 using namespace xmltooling::logging;
42 using namespace xmltooling;
47 class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
50 SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple=false);
51 virtual ~SAML2POSTEncoder() {}
54 GenericResponse& genericResponse,
56 const char* destination,
57 const EntityDescriptor* recipient=NULL,
58 const char* relayState=NULL,
59 const ArtifactGenerator* artifactGenerator=NULL,
60 const Credential* credential=NULL,
61 const XMLCh* signatureAlg=NULL,
62 const XMLCh* digestAlg=NULL
70 MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
72 return new SAML2POSTEncoder(p.first, p.second, false);
75 MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
77 return new SAML2POSTEncoder(p.first, p.second, true);
82 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
84 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple) : m_simple(simple)
87 auto_ptr_char t(e->getAttributeNS(ns, _template));
88 if (t.get() && *t.get())
91 if (m_template.empty())
92 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
93 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
96 long SAML2POSTEncoder::encode(
97 GenericResponse& genericResponse,
99 const char* destination,
100 const EntityDescriptor* recipient,
101 const char* relayState,
102 const ArtifactGenerator* artifactGenerator,
103 const Credential* credential,
104 const XMLCh* signatureAlg,
105 const XMLCh* digestAlg
109 xmltooling::NDC ndc("encode");
111 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
113 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
115 throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
117 log.debug("validating input");
118 if (xmlObject->getParent())
119 throw BindingException("Cannot encode XML content with parent.");
121 StatusResponseType* response = NULL;
122 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
124 response = dynamic_cast<StatusResponseType*>(xmlObject);
126 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
129 DOMElement* rootElement = NULL;
130 if (credential && !m_simple) {
131 // Signature based on native XML signing.
132 if (request ? request->getSignature() : response->getSignature()) {
133 log.debug("message already signed, skipping signature operation");
136 log.debug("signing and marshalling the message");
138 // Build a Signature.
139 Signature* sig = SignatureBuilder::buildSignature();
140 request ? request->setSignature(sig) : response->setSignature(sig);
142 sig->setSignatureAlgorithm(signatureAlg);
144 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
146 cr->setDigestAlgorithm(digestAlg);
149 // Sign response while marshalling.
150 vector<Signature*> sigs(1,sig);
151 rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
155 log.debug("marshalling the message");
156 rootElement = xmlObject->marshall((DOMDocument*)NULL);
159 // Serialize the message.
160 TemplateEngine::TemplateParameters pmap;
161 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
162 XMLHelper::serialize(rootElement, msg);
163 log.debug("marshalled message:\n%s", msg.c_str());
166 if (credential && m_simple) {
167 log.debug("applying simple signature to message data");
168 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
169 if (relayState && *relayState)
170 input = input + "&RelayState=" + relayState;
172 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
173 auto_ptr_char alg(signatureAlg);
174 pmap.m_map["SigAlg"] = alg.get();
175 input = input + "&SigAlg=" + alg.get();
178 memset(sigbuf,0,sizeof(sigbuf));
179 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
180 pmap.m_map["Signature"] = sigbuf;
182 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
184 string& kstring = pmap.m_map["KeyInfo"];
185 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)NULL), kstring);
187 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
189 throw BindingException("Base64 encoding of XML failed.");
191 kstring.append(reinterpret_cast<char*>(out),len);
192 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
193 XMLString::release(&out);
195 XMLString::release((char**)&out);
200 // Base64 the message.
202 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
204 throw BindingException("Base64 encoding of XML failed.");
206 msg.append(reinterpret_cast<char*>(out),len);
207 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
208 XMLString::release(&out);
210 XMLString::release((char**)&out);
213 // Push the rest of it into template and send result to client.
214 log.debug("message encoded, sending HTML form template to client");
215 ifstream infile(m_template.c_str());
217 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
218 pmap.m_map["action"] = destination;
219 if (relayState && *relayState)
220 pmap.m_map["RelayState"] = relayState;
222 engine->run(infile, s, pmap);
223 genericResponse.setContentType("text/html");
224 long ret = genericResponse.sendResponse(s);
226 // Cleanup by destroying XML.