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