SSPCPP-616 - clean up concatenated string literals
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactEncoder.cpp
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 "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"
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 namespace opensaml {
56     namespace saml2p {              
57         class SAML_DLLLOCAL SAML2ArtifactEncoder : public MessageEncoder
58         {
59         public:
60             SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns);
61             virtual ~SAML2ArtifactEncoder() {}
62
63             const XMLCh* getProtocolFamily() const {
64                 return samlconstants::SAML20P_NS;
65             }
66
67             long encode(
68                 GenericResponse& genericResponse,
69                 XMLObject* xmlObject,
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
77                 ) const;
78         
79         private:
80             string m_template;
81         };
82
83         MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
84         {
85             return new SAML2ArtifactEncoder(p.first, p.second);
86         }
87     };
88
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);
91 };
92
93 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns)
94 {
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);
99     }
100 }
101
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
112     ) const
113 {
114 #ifdef _DEBUG
115     xmltooling::NDC ndc("encode");
116 #endif
117     Category& log = Category::getInstance(SAML_LOGCAT ".MessageEncoder.SAML2Artifact");
118     log.debug("validating input");
119     if (!destination)
120         throw BindingException("Encoding response requires a destination.");
121     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
122     if (!httpResponse)
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.");
128
129     StatusResponseType* response = nullptr;
130     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
131     if (!request) {
132         response = dynamic_cast<StatusResponseType*>(xmlObject);
133         if (!response)
134             throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
135     }
136     
137     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
138     if (!mapper)
139         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
140
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));
147
148     if (credential) {
149         // Signature based on native XML signing.
150         if (request ? request->getSignature() : response->getSignature()) {
151             log.debug("message already signed, skipping signature operation");
152         }
153         else {
154             log.debug("signing the message");
155
156             // Build a Signature.
157             Signature* sig = SignatureBuilder::buildSignature();
158             request ? request->setSignature(sig) : response->setSignature(sig);    
159             if (signatureAlg)
160                 sig->setSignatureAlgorithm(signatureAlg);
161             if (digestAlg) {
162                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
163                 if (cr)
164                     cr->setDigestAlgorithm(digestAlg);
165             }
166             
167             // Sign response while marshalling.
168             vector<Signature*> sigs(1,sig);
169             xmlObject->marshall((DOMDocument*)nullptr,&sigs,credential);
170         }
171     }
172
173     if (log.isDebugEnabled())
174         log.debugStream() << "marshalled message:" << logging::eol << *xmlObject << logging::eol;
175     
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());
179
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());
190     }
191     else {
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();
195         if (!engine)
196             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
197         HTTPResponse::sanitizeURL(destination);
198         ifstream infile(m_template.c_str());
199         if (!infile)
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;
206         stringstream s;
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);
213     }
214 }