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