3a5fe2592160befb8e62cb1f9cfbb96938962797
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2006 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  * SAML2POSTEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/HTTPResponse.h"
26 #include "saml2/binding/SAML2POSTEncoder.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <log4cpp/Category.hh>
32 #include <xercesc/util/Base64.hpp>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/TemplateEngine.h>
35
36 using namespace opensaml::saml2p;
37 using namespace opensaml;
38 using namespace xmlsignature;
39 using namespace xmltooling;
40 using namespace log4cpp;
41 using namespace std;
42
43 namespace opensaml {
44     namespace saml2p {              
45         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const DOMElement* const & e)
46         {
47             return new SAML2POSTEncoder(e, false);
48         }
49
50         MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const DOMElement* const & e)
51         {
52             return new SAML2POSTEncoder(e, true);
53         }
54     };
55 };
56
57 static const XMLCh templat[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
58
59 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, bool simple) : m_simple(simple)
60 {
61     if (e) {
62         auto_ptr_char t(e->getAttributeNS(NULL, templat));
63         if (t.get())
64             m_template = t.get();
65     }
66     if (m_template.empty())
67         throw XMLToolingException("SAML2POSTEncoder requires template attribute.");
68 }
69
70 SAML2POSTEncoder::~SAML2POSTEncoder() {}
71
72 long SAML2POSTEncoder::encode(
73     GenericResponse& genericResponse,
74     XMLObject* xmlObject,
75     const char* destination,
76     const char* recipientID,
77     const char* relayState,
78     const CredentialResolver* credResolver,
79     const XMLCh* sigAlgorithm
80     ) const
81 {
82 #ifdef _DEBUG
83     xmltooling::NDC ndc("encode");
84 #endif
85     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
86
87     log.debug("validating input");
88     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
89     if (!httpResponse)
90         throw BindingException("Unable to cast response interface to HTTPResponse type.");
91     if (xmlObject->getParent())
92         throw BindingException("Cannot encode XML content with parent.");
93     
94     StatusResponseType* response = NULL;
95     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
96     if (!request) {
97         response = dynamic_cast<StatusResponseType*>(xmlObject);
98         if (!response)
99             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
100     }
101     
102     DOMElement* rootElement = NULL;
103     vector<Signature*> sigs;
104     if (credResolver && !m_simple) {
105         // Signature based on native XML signing.
106         if (request ? request->getSignature() : response->getSignature()) {
107             log.debug("message already signed, skipping signature operation");
108         }
109         else {
110             log.debug("signing and marshalling the message");
111
112             // Build a Signature.
113             Signature* sig = buildSignature(credResolver, sigAlgorithm);
114             
115             // Append Signature.
116             request ? request->setSignature(sig) : response->setSignature(sig);    
117         
118             // Sign response while marshalling.
119             sigs.push_back(sig);
120         }
121     }
122     else {
123         log.debug("marshalling the message");
124     }
125     
126     rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs);
127     
128     // Start tracking data.
129     map<string,string> pmap;
130     if (relayState)
131         pmap["RelayState"] = relayState;
132
133     // Base64 the message.
134     string& msg = pmap[(request ? "SAMLRequest" : "SAMLResponse")];
135     XMLHelper::serialize(rootElement, msg);
136     unsigned int len=0;
137     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
138     if (!out)
139         throw BindingException("Base64 encoding of XML failed.");
140     msg.erase();
141     msg.append(reinterpret_cast<char*>(out),len);
142     XMLString::release(&out);
143     
144     if (credResolver && m_simple) {
145         log.debug("applying simple signature to message data");
146         string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
147         if (relayState)
148             input = input + "&RelayState=" + relayState;
149         if (!sigAlgorithm)
150             sigAlgorithm = DSIGConstants::s_unicodeStrURIRSA_SHA1;
151         auto_ptr_char alg(sigAlgorithm);
152         pmap["SigAlg"] = alg.get();
153         input = input + "&SigAlg=" + alg.get();
154
155         char sigbuf[1024];
156         memset(sigbuf,0,sizeof(sigbuf));
157         auto_ptr<XSECCryptoKey> key(credResolver->getKey());
158         Signature::createRawSignature(key.get(), sigAlgorithm, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
159         pmap["Signature"] = sigbuf;
160     }
161     
162     // Push message into template and send result to client.
163     log.debug("message encoded, sending HTML form template to client");
164     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
165     if (!engine)
166         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
167     ifstream infile(m_template.c_str());
168     if (!infile)
169         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
170     pmap["action"] = destination;
171     stringstream s;
172     engine->run(infile, s, pmap);
173     httpResponse->setContentType("text/html");
174     long ret = httpResponse->sendResponse(s, HTTPResponse::SAML_HTTP_STATUS_OK);
175
176     // Cleanup by destroying XML.
177     delete xmlObject;
178     return ret;
179 }