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