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