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/TemplateEngine.h>
36 using namespace opensaml::saml2p;
37 using namespace opensaml::saml2md;
38 using namespace opensaml;
39 using namespace xmlsignature;
40 using namespace xmltooling::logging;
41 using namespace xmltooling;
46 class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
49 SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple=false);
50 virtual ~SAML2POSTEncoder() {}
53 GenericResponse& genericResponse,
55 const char* destination,
56 const EntityDescriptor* recipient=NULL,
57 const char* relayState=NULL,
58 const ArtifactGenerator* artifactGenerator=NULL,
59 const Credential* credential=NULL,
60 const XMLCh* signatureAlg=NULL,
61 const XMLCh* digestAlg=NULL
69 MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
71 return new SAML2POSTEncoder(p.first, p.second, false);
74 MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
76 return new SAML2POSTEncoder(p.first, p.second, true);
81 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
83 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, const XMLCh* ns, bool simple) : m_simple(simple)
86 auto_ptr_char t(e->getAttributeNS(ns, _template));
87 if (t.get() && *t.get())
90 if (m_template.empty())
91 throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
94 long SAML2POSTEncoder::encode(
95 GenericResponse& genericResponse,
97 const char* destination,
98 const EntityDescriptor* recipient,
99 const char* relayState,
100 const ArtifactGenerator* artifactGenerator,
101 const Credential* credential,
102 const XMLCh* signatureAlg,
103 const XMLCh* digestAlg
107 xmltooling::NDC ndc("encode");
109 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
111 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
113 throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
115 log.debug("validating input");
116 if (xmlObject->getParent())
117 throw BindingException("Cannot encode XML content with parent.");
119 StatusResponseType* response = NULL;
120 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
122 response = dynamic_cast<StatusResponseType*>(xmlObject);
124 throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
127 DOMElement* rootElement = NULL;
128 if (credential && !m_simple) {
129 // Signature based on native XML signing.
130 if (request ? request->getSignature() : response->getSignature()) {
131 log.debug("message already signed, skipping signature operation");
134 log.debug("signing and marshalling the message");
136 // Build a Signature.
137 Signature* sig = SignatureBuilder::buildSignature();
138 request ? request->setSignature(sig) : response->setSignature(sig);
140 sig->setSignatureAlgorithm(signatureAlg);
142 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
144 cr->setDigestAlgorithm(digestAlg);
147 // Sign response while marshalling.
148 vector<Signature*> sigs(1,sig);
149 rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
153 log.debug("marshalling the message");
154 rootElement = xmlObject->marshall((DOMDocument*)NULL);
157 // Serialize the message.
158 TemplateEngine::TemplateParameters pmap;
159 string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
160 XMLHelper::serialize(rootElement, msg);
161 log.debug("marshalled message: %s", msg.c_str());
164 if (credential && m_simple) {
165 log.debug("applying simple signature to message data");
166 string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
167 if (relayState && *relayState)
168 input = input + "&RelayState=" + relayState;
170 signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
171 auto_ptr_char alg(signatureAlg);
172 pmap.m_map["SigAlg"] = alg.get();
173 input = input + "&SigAlg=" + alg.get();
176 memset(sigbuf,0,sizeof(sigbuf));
177 Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
178 pmap.m_map["Signature"] = sigbuf;
180 auto_ptr<KeyInfo> keyInfo(credential->getKeyInfo());
182 string& kstring = pmap.m_map["KeyInfo"];
183 XMLHelper::serialize(keyInfo->marshall((DOMDocument*)NULL), kstring);
185 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(kstring.data()),kstring.size(),&len);
187 throw BindingException("Base64 encoding of XML failed.");
189 kstring.append(reinterpret_cast<char*>(out),len);
190 XMLString::release(&out);
194 // Base64 the message.
196 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
198 throw BindingException("Base64 encoding of XML failed.");
200 msg.append(reinterpret_cast<char*>(out),len);
201 XMLString::release(&out);
203 // Push the rest of it into template and send result to client.
204 log.debug("message encoded, sending HTML form template to client");
205 ifstream infile(m_template.c_str());
207 throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
208 pmap.m_map["action"] = destination;
209 if (relayState && *relayState)
210 pmap.m_map["RelayState"] = relayState;
212 engine->run(infile, s, pmap);
213 genericResponse.setContentType("text/html");
214 long ret = genericResponse.sendResponse(s);
216 // Cleanup by destroying XML.