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