2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * SAML2ArtifactEncoder.cpp
24 * SAML 2.0 HTTP-Artifact binding message encoder.
28 #include "exceptions.h"
29 #include "binding/ArtifactMap.h"
30 #include "binding/MessageEncoder.h"
31 #include "saml2/binding/SAML2Artifact.h"
32 #include "saml2/core/Protocols.h"
33 #include "saml2/metadata/Metadata.h"
34 #include "signature/ContentReference.h"
38 #include <xmltooling/logging.h>
39 #include <xmltooling/XMLToolingConfig.h>
40 #include <xmltooling/io/HTTPResponse.h>
41 #include <xmltooling/signature/Signature.h>
42 #include <xmltooling/util/NDC.h>
43 #include <xmltooling/util/PathResolver.h>
44 #include <xmltooling/util/TemplateEngine.h>
45 #include <xmltooling/util/URLEncoder.h>
47 using namespace opensaml::saml2p;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
50 using namespace xmlsignature;
51 using namespace xmltooling::logging;
52 using namespace xmltooling;
57 class SAML_DLLLOCAL SAML2ArtifactEncoder : public MessageEncoder
60 SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns);
61 virtual ~SAML2ArtifactEncoder() {}
63 const XMLCh* getProtocolFamily() const {
64 return samlconstants::SAML20P_NS;
68 GenericResponse& genericResponse,
70 const char* destination,
71 const EntityDescriptor* recipient=nullptr,
72 const char* relayState=nullptr,
73 const ArtifactGenerator* artifactGenerator=nullptr,
74 const Credential* credential=nullptr,
75 const XMLCh* signatureAlg=nullptr,
76 const XMLCh* digestAlg=nullptr
83 MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
85 return new SAML2ArtifactEncoder(p.first, p.second);
89 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
90 static const XMLCh postArtifact[] = UNICODE_LITERAL_12(p,o,s,t,A,r,t,i,f,a,c,t);
93 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns)
95 if (XMLHelper::getAttrBool(e, false, postArtifact, ns)) {
96 m_template = XMLHelper::getAttrString(e, "bindingTemplate.html", _template, ns);
97 if (!m_template.empty())
98 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
102 long SAML2ArtifactEncoder::encode(
103 GenericResponse& genericResponse,
104 XMLObject* xmlObject,
105 const char* destination,
106 const EntityDescriptor* recipient,
107 const char* relayState,
108 const ArtifactGenerator* artifactGenerator,
109 const Credential* credential,
110 const XMLCh* signatureAlg,
111 const XMLCh* digestAlg
115 xmltooling::NDC ndc("encode");
117 Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Artifact");
118 log.debug("validating input");
120 throw BindingException("Encoding response requires a destination.");
121 HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
123 throw BindingException("Unable to cast response interface to HTTPResponse type.");
124 if (relayState && strlen(relayState)>80)
125 throw BindingException("RelayState cannot exceed 80 bytes in length.");
126 if (xmlObject->getParent())
127 throw BindingException("Cannot encode XML content with parent.");
129 StatusResponseType* response = nullptr;
130 RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
132 response = dynamic_cast<StatusResponseType*>(xmlObject);
134 throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
137 ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
139 throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
141 // Obtain a fresh artifact.
142 if (!artifactGenerator)
143 throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
144 auto_ptr_char recipientID(recipient ? recipient->getEntityID() : nullptr);
145 log.debug("obtaining new artifact for relying party (%s)", recipientID.get() ? recipientID.get() : "unknown");
146 auto_ptr<SAMLArtifact> artifact(artifactGenerator->generateSAML2Artifact(recipient));
149 // Signature based on native XML signing.
150 if (request ? request->getSignature() : response->getSignature()) {
151 log.debug("message already signed, skipping signature operation");
154 log.debug("signing the message");
156 // Build a Signature.
157 Signature* sig = SignatureBuilder::buildSignature();
158 request ? request->setSignature(sig) : response->setSignature(sig);
160 sig->setSignatureAlgorithm(signatureAlg);
162 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
164 cr->setDigestAlgorithm(digestAlg);
167 // Sign response while marshalling.
168 vector<Signature*> sigs(1,sig);
169 xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
173 if (log.isDebugEnabled())
174 log.debugStream() << "marshalled message:" << logging::eol << *xmlObject << logging::eol;
176 // Store the message. Last step in storage will be to delete the XML.
177 log.debug("storing artifact and content in map");
178 mapper->storeContent(xmlObject, artifact.get(), recipientID.get());
180 if (m_template.empty()) {
181 // Generate redirect.
182 string loc = destination;
183 loc += (strchr(destination,'?') ? '&' : '?');
184 const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
185 loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
186 if (relayState && *relayState)
187 loc = loc + "&RelayState=" + escaper->encode(relayState);
188 log.debug("message encoded, sending redirect to client");
189 return httpResponse->sendRedirect(loc.c_str());
192 // Push message into template and send result to client.
193 log.debug("message encoded, sending HTML form template to client");
194 TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
196 throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
197 HTTPResponse::sanitizeURL(destination);
198 ifstream infile(m_template.c_str());
200 throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
201 TemplateEngine::TemplateParameters params;
202 params.m_map["action"] = destination;
203 params.m_map["SAMLart"] = artifact->encode();
204 if (relayState && *relayState)
205 params.m_map["RelayState"] = relayState;
207 engine->run(infile, s, params);
208 httpResponse->setContentType("text/html");
209 httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
210 httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
211 httpResponse->setResponseHeader("Pragma", "no-cache");
212 return httpResponse->sendResponse(s);