Major revamp of credential and trust handling code, PKIX engine still needs work.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.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  * 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/MessageEncoder.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         class SAML_DLLLOCAL SAML2POSTEncoder : public MessageEncoder
45         {
46         public:
47             SAML2POSTEncoder(const DOMElement* e, bool simple=false);
48             virtual ~SAML2POSTEncoder() {}
49             
50             long encode(
51                 GenericResponse& genericResponse,
52                 XMLObject* xmlObject,
53                 const char* destination,
54                 const char* recipientID=NULL,
55                 const char* relayState=NULL,
56                 const Credential* credential=NULL,
57                 const XMLCh* sigAlgorithm=NULL
58                 ) const;
59
60         private:        
61             string m_template;
62             bool m_simple;
63         };
64
65         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const DOMElement* const & e)
66         {
67             return new SAML2POSTEncoder(e, false);
68         }
69
70         MessageEncoder* SAML_DLLLOCAL SAML2POSTSimpleSignEncoderFactory(const DOMElement* const & e)
71         {
72             return new SAML2POSTEncoder(e, true);
73         }
74     };
75 };
76
77 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
78
79 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e, bool simple) : m_simple(simple)
80 {
81     if (e) {
82         auto_ptr_char t(e->getAttributeNS(NULL, _template));
83         if (t.get())
84             m_template = t.get();
85     }
86     if (m_template.empty())
87         throw XMLToolingException("SAML2POSTEncoder requires template XML attribute.");
88 }
89
90 long SAML2POSTEncoder::encode(
91     GenericResponse& genericResponse,
92     XMLObject* xmlObject,
93     const char* destination,
94     const char* recipientID,
95     const char* relayState,
96     const Credential* credential,
97     const XMLCh* sigAlgorithm
98     ) const
99 {
100 #ifdef _DEBUG
101     xmltooling::NDC ndc("encode");
102 #endif
103     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
104
105     log.debug("validating input");
106     if (xmlObject->getParent())
107         throw BindingException("Cannot encode XML content with parent.");
108     
109     StatusResponseType* response = NULL;
110     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
111     if (!request) {
112         response = dynamic_cast<StatusResponseType*>(xmlObject);
113         if (!response)
114             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
115     }
116     
117     DOMElement* rootElement = NULL;
118     if (credential && !m_simple) {
119         // Signature based on native XML signing.
120         if (request ? request->getSignature() : response->getSignature()) {
121             log.debug("message already signed, skipping signature operation");
122         }
123         else {
124             log.debug("signing and marshalling the message");
125
126             // Build a Signature.
127             Signature* sig = SignatureBuilder::buildSignature();
128             request ? request->setSignature(sig) : response->setSignature(sig);    
129             if (sigAlgorithm)
130                 sig->setSignatureAlgorithm(sigAlgorithm);
131             
132             // Sign response while marshalling.
133             vector<Signature*> sigs(1,sig);
134             rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
135         }
136     }
137     else {
138         log.debug("marshalling the message");
139         rootElement = xmlObject->marshall((DOMDocument*)NULL);
140     }
141     
142     // Start tracking data.
143     TemplateEngine::TemplateParameters pmap;
144     if (relayState)
145         pmap.m_map["RelayState"] = relayState;
146
147     // Serialize the message.
148     string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
149     XMLHelper::serialize(rootElement, msg);
150
151     // SimpleSign.
152     if (credential && m_simple) {
153         log.debug("applying simple signature to message data");
154         string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
155         if (relayState)
156             input = input + "&RelayState=" + relayState;
157         if (!sigAlgorithm)
158             sigAlgorithm = DSIGConstants::s_unicodeStrURIRSA_SHA1;
159         auto_ptr_char alg(sigAlgorithm);
160         pmap.m_map["SigAlg"] = alg.get();
161         input = input + "&SigAlg=" + alg.get();
162
163         char sigbuf[1024];
164         memset(sigbuf,0,sizeof(sigbuf));
165         Signature::createRawSignature(credential->getPrivateKey(), sigAlgorithm, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
166         pmap.m_map["Signature"] = sigbuf;
167     }
168     
169     // Base64 the message.
170     unsigned int len=0;
171     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
172     if (!out)
173         throw BindingException("Base64 encoding of XML failed.");
174     msg.erase();
175     msg.append(reinterpret_cast<char*>(out),len);
176     XMLString::release(&out);
177     
178     // Push message into template and send result to client.
179     log.debug("message encoded, sending HTML form template to client");
180     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
181     if (!engine)
182         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
183     ifstream infile(m_template.c_str());
184     if (!infile)
185         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
186     pmap.m_map["action"] = destination;
187     stringstream s;
188     engine->run(infile, s, pmap);
189     genericResponse.setContentType("text/html");
190     long ret = genericResponse.sendResponse(s);
191
192     // Cleanup by destroying XML.
193     delete xmlObject;
194     return ret;
195 }