2 * Copyright 2001-2010 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 * SAML2ArtifactEncoder.cpp
20 * SAML 2.0 HTTP-Artifact binding message encoder.
24 #include "exceptions.h"
25 #include "binding/ArtifactMap.h"
26 #include "binding/MessageEncoder.h"
27 #include "saml2/binding/SAML2Artifact.h"
28 #include "saml2/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "signature/ContentReference.h"
34 #include <xmltooling/logging.h>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/io/HTTPResponse.h>
37 #include <xmltooling/signature/Signature.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/PathResolver.h>
40 #include <xmltooling/util/TemplateEngine.h>
41 #include <xmltooling/util/URLEncoder.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 SAML2ArtifactEncoder : public MessageEncoder
56 SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns);
57 virtual ~SAML2ArtifactEncoder() {}
60 GenericResponse& genericResponse,
62 const char* destination,
63 const EntityDescriptor* recipient=nullptr,
64 const char* relayState=nullptr,
65 const ArtifactGenerator* artifactGenerator=nullptr,
66 const Credential* credential=nullptr,
67 const XMLCh* signatureAlg=nullptr,
68 const XMLCh* digestAlg=nullptr
75 MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
77 return new SAML2ArtifactEncoder(p.first, p.second);
81 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
82 static const XMLCh postArtifact[] = UNICODE_LITERAL_12(p,o,s,t,A,r,t,i,f,a,c,t);
85 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns)
87 if (XMLHelper::getAttrBool(e, false, postArtifact, ns)) {
88 m_template = XMLHelper::getAttrString(e, nullptr, _template, ns);
89 if (!m_template.empty())
90 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
94 long SAML2ArtifactEncoder::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.SAML2Artifact");
110 log.debug("validating input");
112 throw BindingException("Encoding response requires a destination.");
113 HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
115 throw BindingException("Unable to cast response interface to HTTPResponse type.");
116 if (relayState && strlen(relayState)>80)
117 throw BindingException("RelayState cannot exceed 80 bytes in length.");
118 if (xmlObject->getParent())
119 throw BindingException("Cannot encode XML content with parent.");
121 StatusResponseType* response = nullptr;
122 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
124 response = dynamic_cast<StatusResponseType*>(xmlObject);
126 throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
129 ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
131 throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
133 // Obtain a fresh artifact.
134 if (!artifactGenerator)
135 throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
136 auto_ptr_char recipientID(recipient ? recipient->getEntityID() : nullptr);
137 log.debug("obtaining new artifact for relying party (%s)", recipientID.get() ? recipientID.get() : "unknown");
138 auto_ptr<SAMLArtifact> artifact(artifactGenerator->generateSAML2Artifact(recipient));
141 // Signature based on native XML signing.
142 if (request ? request->getSignature() : response->getSignature()) {
143 log.debug("message already signed, skipping signature operation");
146 log.debug("signing the message");
148 // Build a Signature.
149 Signature* sig = SignatureBuilder::buildSignature();
150 request ? request->setSignature(sig) : response->setSignature(sig);
152 sig->setSignatureAlgorithm(signatureAlg);
154 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
156 cr->setDigestAlgorithm(digestAlg);
159 // Sign response while marshalling.
160 vector<Signature*> sigs(1,sig);
161 xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
165 if (log.isDebugEnabled())
166 log.debugStream() << "marshalled message:" << logging::eol << *xmlObject << logging::eol;
168 // Store the message. Last step in storage will be to delete the XML.
169 log.debug("storing artifact and content in map");
170 mapper->storeContent(xmlObject, artifact.get(), recipientID.get());
172 if (m_template.empty()) {
173 // Generate redirect.
174 string loc = destination;
175 loc += (strchr(destination,'?') ? '&' : '?');
176 const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
177 loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
178 if (relayState && *relayState)
179 loc = loc + "&RelayState=" + escaper->encode(relayState);
180 log.debug("message encoded, sending redirect to client");
181 return httpResponse->sendRedirect(loc.c_str());
184 // Push message into template and send result to client.
185 log.debug("message encoded, sending HTML form template to client");
186 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
188 throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
189 HTTPResponse::sanitizeURL(destination);
190 ifstream infile(m_template.c_str());
192 throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
193 TemplateEngine::TemplateParameters params;
194 params.m_map["action"] = destination;
195 params.m_map["SAMLart"] = artifact->encode();
196 if (relayState && *relayState)
197 params.m_map["RelayState"] = relayState;
199 engine->run(infile, s, params);
200 httpResponse->setContentType("text/html");
201 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
202 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
203 httpResponse->setResponseHeader("Pragma", "no-cache");
204 return httpResponse->sendResponse(s);