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