1 /**
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.
6  *
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
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20 
21 /**
22  * SAML2ArtifactEncoder.cpp
23  *
24  * SAML 2.0 HTTP-Artifact binding message encoder.
25  */
26 
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/ArtifactMap.h"
30 #include "saml2/binding/SAML2Artifact.h"
31 #include "saml2/binding/SAML2MessageEncoder.h"
32 #include "saml2/core/Protocols.h"
33 #include "saml2/metadata/Metadata.h"
34 #include "signature/ContentReference.h"
35 
36 #include <fstream>
37 #include <sstream>
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>
46 
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;
53 using namespace std;
54 
55 using boost::scoped_ptr;
56 
57 namespace opensaml {
58     namespace saml2p {
59         class SAML_DLLLOCAL SAML2ArtifactEncoder : public SAML2MessageEncoder
60         {
61         public:
62             SAML2ArtifactEncoder(const DOMElement* e);
~SAML2ArtifactEncoder()63             virtual ~SAML2ArtifactEncoder() {}
64 
65             long encode(
66                 GenericResponse& genericResponse,
67                 XMLObject* xmlObject,
68                 const char* destination,
69                 const EntityDescriptor* recipient=nullptr,
70                 const char* relayState=nullptr,
71                 const ArtifactGenerator* artifactGenerator=nullptr,
72                 const Credential* credential=nullptr,
73                 const XMLCh* signatureAlg=nullptr,
74                 const XMLCh* digestAlg=nullptr
75                 ) const;
76 
77         private:
78             string m_template;
79         };
80 
SAML2ArtifactEncoderFactory(const DOMElement * const & e,bool)81         MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const DOMElement* const & e, bool)
82         {
83             return new SAML2ArtifactEncoder(e);
84         }
85     };
86 
87 };
88 
SAML2ArtifactEncoder(const DOMElement * e)89 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e)
90 {
91     // Fishy alert: we ignore the namespace and look for a matching DOM Attr node by name only.
92     // Can't use DOM 1 calls, so we have to walk the attribute list by hand.
93 
94     static const XMLCh postArtifact[] = UNICODE_LITERAL_12(p, o, s, t, A, r, t, i, f, a, c, t);
95     static const XMLCh _template[] = UNICODE_LITERAL_8(t, e, m, p, l, a, t, e);
96 
97     const DOMNamedNodeMap* attributes = e ? e->getAttributes() : nullptr;
98     XMLSize_t size = attributes ? attributes->getLength() : 0;
99 
100     bool post = false;
101     for (XMLSize_t i = 0; i < size; ++i) {
102         const DOMNode* attr = attributes->item(i);
103         if (XMLString::equals(attr->getLocalName(), postArtifact)) {
104             const XMLCh* val = attr->getNodeValue();
105             if (val) {
106                 if (*val == chLatin_t || *val == chDigit_1)
107                     post = true;
108             }
109         }
110     }
111 
112     if (post) {
113         for (XMLSize_t i = 0; i < size; ++i) {
114             const DOMNode* attr = attributes->item(i);
115             if (XMLString::equals(attr->getLocalName(), _template)) {
116                 auto_ptr_char val(attr->getNodeValue());
117                 if (val.get())
118                     m_template = val.get();
119             }
120         }
121 
122         if (m_template.empty())
123             m_template = "bindingTemplate.html";
124 
125         XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
126     }
127 }
128 
encode(GenericResponse & genericResponse,XMLObject * xmlObject,const char * destination,const EntityDescriptor * recipient,const char * relayState,const ArtifactGenerator * artifactGenerator,const Credential * credential,const XMLCh * signatureAlg,const XMLCh * digestAlg) const129 long SAML2ArtifactEncoder::encode(
130     GenericResponse& genericResponse,
131     XMLObject* xmlObject,
132     const char* destination,
133     const EntityDescriptor* recipient,
134     const char* relayState,
135     const ArtifactGenerator* artifactGenerator,
136     const Credential* credential,
137     const XMLCh* signatureAlg,
138     const XMLCh* digestAlg
139     ) const
140 {
141 #ifdef _DEBUG
142     xmltooling::NDC ndc("encode");
143 #endif
144     Category& log = Category::getInstance(SAML_LOGCAT ".MessageEncoder.SAML2Artifact");
145     log.debug("validating input");
146     if (!destination)
147         throw BindingException("Encoding response requires a destination.");
148     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
149     if (!httpResponse)
150         throw BindingException("Unable to cast response interface to HTTPResponse type.");
151     if (relayState && strlen(relayState)>80)
152         throw BindingException("RelayState cannot exceed 80 bytes in length.");
153     if (xmlObject->getParent())
154         throw BindingException("Cannot encode XML content with parent.");
155 
156     StatusResponseType* response = nullptr;
157     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
158     if (request) {
159         preserveCorrelationID(*httpResponse, *request, relayState);
160     }
161     else {
162         response = dynamic_cast<StatusResponseType*>(xmlObject);
163         if (!response)
164             throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
165     }
166 
167     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
168     if (!mapper)
169         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
170 
171     // Obtain a fresh artifact.
172     if (!artifactGenerator)
173         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
174     auto_ptr_char recipientID(recipient ? recipient->getEntityID() : nullptr);
175     log.debug("obtaining new artifact for relying party (%s)", recipientID.get() ? recipientID.get() : "unknown");
176     scoped_ptr<SAMLArtifact> artifact(artifactGenerator->generateSAML2Artifact(recipient));
177 
178     if (credential) {
179         // Signature based on native XML signing.
180         if (request ? request->getSignature() : response->getSignature()) {
181             log.debug("message already signed, skipping signature operation");
182         }
183         else {
184             log.debug("signing the message");
185 
186             // Build a Signature.
187             Signature* sig = SignatureBuilder::buildSignature();
188             request ? request->setSignature(sig) : response->setSignature(sig);
189             if (signatureAlg)
190                 sig->setSignatureAlgorithm(signatureAlg);
191             if (digestAlg) {
192                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
193                 if (cr)
194                     cr->setDigestAlgorithm(digestAlg);
195             }
196 
197             // Sign response while marshalling.
198             vector<Signature*> sigs(1,sig);
199             xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
200         }
201     }
202 
203     if (log.isDebugEnabled())
204         log.debugStream() << "marshalled message:" << logging::eol << *xmlObject << logging::eol;
205 
206     // Store the message. Last step in storage will be to delete the XML.
207     log.debug("storing artifact and content in map");
208     mapper->storeContent(xmlObject, artifact.get(), recipientID.get());
209 
210     if (m_template.empty()) {
211         // Generate redirect.
212         string loc = destination;
213         loc += (strchr(destination,'?') ? '&' : '?');
214         const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
215         loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
216         if (relayState && *relayState)
217             loc = loc + "&RelayState=" + escaper->encode(relayState);
218         log.debug("message encoded, sending redirect to client");
219         return httpResponse->sendRedirect(loc.c_str());
220     }
221     else {
222         // Push message into template and send result to client.
223         log.debug("message encoded, sending HTML form template to client");
224         TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
225         if (!engine)
226             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
227         HTTPResponse::sanitizeURL(destination);
228         ifstream infile(m_template.c_str());
229         if (!infile)
230             throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
231         TemplateEngine::TemplateParameters params;
232         params.m_map["action"] = destination;
233         params.m_map["SAMLart"] = artifact->encode();
234         if (relayState && *relayState)
235             params.m_map["RelayState"] = relayState;
236         stringstream s;
237         engine->run(infile, s, params);
238         httpResponse->setContentType("text/html");
239         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
240         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
241         httpResponse->setResponseHeader("Pragma", "no-cache");
242         return httpResponse->sendResponse(s);
243     }
244 }
245