Settable digest algorithm, enhanced prefix handling in signatures, pending xmlsec...
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTEncoder.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  * SAML1POSTEncoder.cpp
19  * 
20  * SAML 1.x POST binding/profile message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml1/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::saml1p;
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 saml1p {              
45         class SAML_DLLLOCAL SAML1POSTEncoder : public MessageEncoder
46         {
47         public:
48             SAML1POSTEncoder(const DOMElement* e);
49             virtual ~SAML1POSTEncoder() {}
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         protected:
63             /** Pathname of HTML template for transmission of message via POST. */
64             string m_template;
65         };
66
67         MessageEncoder* SAML_DLLLOCAL SAML1POSTEncoderFactory(const DOMElement* const & e)
68         {
69             return new SAML1POSTEncoder(e);
70         }
71     };
72 };
73
74 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
75
76 SAML1POSTEncoder::SAML1POSTEncoder(const DOMElement* e)
77 {
78     if (e) {
79         auto_ptr_char t(e->getAttributeNS(NULL, _template));
80         if (t.get())
81             m_template = t.get();
82     }
83     if (m_template.empty())
84         throw XMLToolingException("SAML1POSTEncoder requires template XML attribute.");
85 }
86
87 long SAML1POSTEncoder::encode(
88     GenericResponse& genericResponse,
89     XMLObject* xmlObject,
90     const char* destination,
91     const char* recipientID,
92     const char* relayState,
93     const Credential* credential,
94     const XMLCh* signatureAlg,
95     const XMLCh* digestAlg
96     ) const
97 {
98 #ifdef _DEBUG
99     xmltooling::NDC ndc("encode");
100 #endif
101     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1POST");
102
103     log.debug("validating input");
104     if (xmlObject->getParent())
105         throw BindingException("Cannot encode XML content with parent.");
106     Response* response = dynamic_cast<Response*>(xmlObject);
107     if (!response)
108         throw BindingException("XML content for SAML 1.x POST Encoder must be a SAML 1.x <Response>.");
109     if (!relayState)
110         throw BindingException("SAML 1.x POST Encoder requires relay state (TARGET) value.");
111     
112     DOMElement* rootElement = NULL;
113     if (credential) {
114         // Signature based on native XML signing.
115         if (response->getSignature()) {
116             log.debug("response already signed, skipping signature operation");
117         }
118         else {
119             log.debug("signing and marshalling the response");
120
121             // Build a Signature.
122             Signature* sig = SignatureBuilder::buildSignature();
123             response->setSignature(sig);
124             if (signatureAlg)
125                 sig->setSignatureAlgorithm(signatureAlg);
126             if (digestAlg) {
127                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
128                 if (cr)
129                     cr->setDigestAlgorithm(digestAlg);
130             }
131     
132             // Sign response while marshalling.
133             vector<Signature*> sigs(1,sig);
134             rootElement = response->marshall((DOMDocument*)NULL,&sigs,credential);
135         }
136     }
137     else {
138         log.debug("marshalling the response");
139         rootElement = response->marshall();
140     }
141     
142     string xmlbuf;
143     XMLHelper::serialize(rootElement, xmlbuf);
144     unsigned int len=0;
145     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
146     if (out) {
147         xmlbuf.erase();
148         xmlbuf.append(reinterpret_cast<char*>(out),len);
149         XMLString::release(&out);
150     }
151     else {
152         throw BindingException("Base64 encoding of XML failed.");
153     }
154
155     // Push message into template and send result to client.
156     log.debug("message encoded, sending HTML form template to client");
157     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
158     if (!engine)
159         throw BindingException("Encoding response using POST requires a TemplateEngine instance.");
160     ifstream infile(m_template.c_str());
161     if (!infile)
162         throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
163     TemplateEngine::TemplateParameters params;
164     params.m_map["action"] = destination;
165     params.m_map["SAMLResponse"] = xmlbuf;
166     params.m_map["TARGET"] = relayState;
167     stringstream s;
168     engine->run(infile, s, params);
169     genericResponse.setContentType("text/html");
170     long ret = genericResponse.sendResponse(s);
171
172     // Cleanup by destroying XML.
173     delete xmlObject;
174     return ret;
175 }