https://issues.shibboleth.net/jira/browse/SSPCPP-255
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactEncoder.cpp
1 /*
2  *  Copyright 2001-2009 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * SAML2ArtifactEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-Artifact binding message encoder.
21  */
22
23 #include "internal.h"
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"
31
32 #include <fstream>
33 #include <sstream>
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>
42
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;
49 using namespace std;
50
51 namespace opensaml {
52     namespace saml2p {              
53         class SAML_DLLLOCAL SAML2ArtifactEncoder : public MessageEncoder
54         {
55         public:
56             SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns);
57             virtual ~SAML2ArtifactEncoder() {}
58             
59             long encode(
60                 GenericResponse& genericResponse,
61                 XMLObject* xmlObject,
62                 const char* destination,
63                 const EntityDescriptor* recipient=NULL,
64                 const char* relayState=NULL,
65                 const ArtifactGenerator* artifactGenerator=NULL,
66                 const Credential* credential=NULL,
67                 const XMLCh* signatureAlg=NULL,
68                 const XMLCh* digestAlg=NULL
69                 ) const;
70         
71         private:
72             bool m_post;
73             string m_template;
74         };
75
76         MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
77         {
78             return new SAML2ArtifactEncoder(p.first, p.second);
79         }
80     };
81
82     static const XMLCh _template[] =    UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
83     static const XMLCh postArtifact[] = UNICODE_LITERAL_12(p,o,s,t,A,r,t,i,f,a,c,t);
84 };
85
86 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns) : m_post(false)
87 {
88     if (e) {
89         const XMLCh* flag = e->getAttributeNS(ns, postArtifact);
90         m_post = (flag && (*flag==chLatin_t || *flag==chDigit_1));
91         if (m_post) {
92             auto_ptr_char t(e->getAttributeNS(ns, _template));
93             if (t.get() && *t.get()) {
94                 m_template = t.get();
95                 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
96             }
97         }
98     }
99 }
100
101 long SAML2ArtifactEncoder::encode(
102     GenericResponse& genericResponse,
103     XMLObject* xmlObject,
104     const char* destination,
105     const EntityDescriptor* recipient,
106     const char* relayState,
107     const ArtifactGenerator* artifactGenerator,
108     const Credential* credential,
109     const XMLCh* signatureAlg,
110     const XMLCh* digestAlg
111     ) const
112 {
113 #ifdef _DEBUG
114     xmltooling::NDC ndc("encode");
115 #endif
116     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Artifact");
117     log.debug("validating input");
118     if (!destination)
119         throw BindingException("Encoding response requires a destination.");
120     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
121     if (!httpResponse)
122         throw BindingException("Unable to cast response interface to HTTPResponse type.");
123     if (relayState && strlen(relayState)>80)
124         throw BindingException("RelayState cannot exceed 80 bytes in length.");
125     if (xmlObject->getParent())
126         throw BindingException("Cannot encode XML content with parent.");
127
128     StatusResponseType* response = NULL;
129     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
130     if (!request) {
131         response = dynamic_cast<StatusResponseType*>(xmlObject);
132         if (!response)
133             throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
134     }
135     
136     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
137     if (!mapper)
138         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
139
140     // Obtain a fresh artifact.
141     if (!artifactGenerator)
142         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
143     auto_ptr_char recipientID(recipient ? recipient->getEntityID() : NULL);
144     log.debug("obtaining new artifact for relying party (%s)", recipientID.get() ? recipientID.get() : "unknown");
145     auto_ptr<SAMLArtifact> artifact(artifactGenerator->generateSAML2Artifact(recipient));
146
147     if (credential) {
148         // Signature based on native XML signing.
149         if (request ? request->getSignature() : response->getSignature()) {
150             log.debug("message already signed, skipping signature operation");
151         }
152         else {
153             log.debug("signing the message");
154
155             // Build a Signature.
156             Signature* sig = SignatureBuilder::buildSignature();
157             request ? request->setSignature(sig) : response->setSignature(sig);    
158             if (signatureAlg)
159                 sig->setSignatureAlgorithm(signatureAlg);
160             if (digestAlg) {
161                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
162                 if (cr)
163                     cr->setDigestAlgorithm(digestAlg);
164             }
165             
166             // Sign response while marshalling.
167             vector<Signature*> sigs(1,sig);
168             xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
169         }
170     }
171
172     if (log.isDebugEnabled())
173         log.debugStream() << "marshalled message:" << logging::eol << *xmlObject << logging::eol;
174     
175     // Store the message. Last step in storage will be to delete the XML.
176     log.debug("storing artifact and content in map");
177     mapper->storeContent(xmlObject, artifact.get(), recipientID.get());
178
179     if (m_template.empty()) {
180         // Generate redirect.
181         string loc = destination;
182         loc += (strchr(destination,'?') ? '&' : '?');
183         const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
184         loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
185         if (relayState && *relayState)
186             loc = loc + "&RelayState=" + escaper->encode(relayState);
187         log.debug("message encoded, sending redirect to client");
188         return httpResponse->sendRedirect(loc.c_str());
189     }
190     else {
191         // Push message into template and send result to client. 
192         log.debug("message encoded, sending HTML form template to client");
193         TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
194         if (!engine)
195             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
196         HTTPResponse::sanitizeURL(destination);
197         ifstream infile(m_template.c_str());
198         if (!infile)
199             throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
200         TemplateEngine::TemplateParameters params;
201         params.m_map["action"] = destination;
202         params.m_map["SAMLart"] = artifact->encode();
203         if (relayState && *relayState)
204             params.m_map["RelayState"] = relayState;
205         stringstream s;
206         engine->run(infile, s, params);
207         httpResponse->setContentType("text/html");
208         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
209         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
210         httpResponse->setResponseHeader("Pragma", "no-cache");
211         return httpResponse->sendResponse(s);
212     }
213 }