1f30f5b71a860e8c3ecef00aed43f87789ddca2d
[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                 xmltooling::XMLObject* xmlObject,
53                 const char* destination,
54                 const char* recipientID=NULL,
55                 const char* relayState=NULL,
56                 const xmltooling::CredentialResolver* credResolver=NULL,
57                 const XMLCh* sigAlgorithm=NULL
58                 ) const;
59
60         private:        
61             std::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 CredentialResolver* credResolver,
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     vector<Signature*> sigs;
119     if (credResolver && !m_simple) {
120         // Signature based on native XML signing.
121         if (request ? request->getSignature() : response->getSignature()) {
122             log.debug("message already signed, skipping signature operation");
123         }
124         else {
125             log.debug("signing and marshalling the message");
126
127             // Build a Signature.
128             Signature* sig = buildSignature(credResolver, sigAlgorithm);
129             
130             // Append Signature.
131             request ? request->setSignature(sig) : response->setSignature(sig);    
132         
133             // Sign response while marshalling.
134             sigs.push_back(sig);
135         }
136     }
137     else {
138         log.debug("marshalling the message");
139     }
140     
141     rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs);
142     
143     // Start tracking data.
144     TemplateEngine::TemplateParameters pmap;
145     if (relayState)
146         pmap.m_map["RelayState"] = relayState;
147
148     // Serialize the message.
149     string& msg = pmap.m_map[(request ? "SAMLRequest" : "SAMLResponse")];
150     XMLHelper::serialize(rootElement, msg);
151
152     // SimpleSign.
153     if (credResolver && m_simple) {
154         log.debug("applying simple signature to message data");
155         string input = (request ? "SAMLRequest=" : "SAMLResponse=") + msg;
156         if (relayState)
157             input = input + "&RelayState=" + relayState;
158         if (!sigAlgorithm)
159             sigAlgorithm = DSIGConstants::s_unicodeStrURIRSA_SHA1;
160         auto_ptr_char alg(sigAlgorithm);
161         pmap.m_map["SigAlg"] = alg.get();
162         input = input + "&SigAlg=" + alg.get();
163
164         char sigbuf[1024];
165         memset(sigbuf,0,sizeof(sigbuf));
166         auto_ptr<XSECCryptoKey> key(credResolver->getKey());
167         Signature::createRawSignature(key.get(), sigAlgorithm, input.c_str(), input.length(), sigbuf, sizeof(sigbuf)-1);
168         pmap.m_map["Signature"] = sigbuf;
169     }
170     
171     // Base64 the message.
172     unsigned int len=0;
173     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(msg.data()),msg.size(),&len);
174     if (!out)
175         throw BindingException("Base64 encoding of XML failed.");
176     msg.erase();
177     msg.append(reinterpret_cast<char*>(out),len);
178     XMLString::release(&out);
179     
180     // Push message into template and send result to client.
181     log.debug("message encoded, sending HTML form template to client");
182     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
183     if (!engine)
184         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
185     ifstream infile(m_template.c_str());
186     if (!infile)
187         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
188     pmap.m_map["action"] = destination;
189     stringstream s;
190     engine->run(infile, s, pmap);
191     genericResponse.setContentType("text/html");
192     long ret = genericResponse.sendResponse(s);
193
194     // Cleanup by destroying XML.
195     delete xmlObject;
196     return ret;
197 }