Settable digest algorithm, enhanced prefix handling in signatures, pending xmlsec...
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectEncoder.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  * SAML2RedirectEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/HTTPResponse.h"
26 #include "binding/MessageEncoder.h"
27 #include "saml2/binding/SAML2Redirect.h"
28 #include "saml2/core/Protocols.h"
29
30 #include <fstream>
31 #include <sstream>
32 #include <log4cpp/Category.hh>
33 #include <xercesc/util/Base64.hpp>
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/util/URLEncoder.h>
36
37 using namespace opensaml::saml2p;
38 using namespace opensaml;
39 using namespace xmlsignature;
40 using namespace xmltooling;
41 using namespace log4cpp;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml2p {              
46         class SAML_DLLLOCAL SAML2RedirectEncoder : public MessageEncoder
47         {
48         public:
49             SAML2RedirectEncoder(const DOMElement* e) {}
50             virtual ~SAML2RedirectEncoder() {}
51             
52             long encode(
53                 GenericResponse& genericResponse,
54                 XMLObject* xmlObject,
55                 const char* destination,
56                 const char* recipientID=NULL,
57                 const char* relayState=NULL,
58                 const Credential* credential=NULL,
59                 const XMLCh* signatureAlg=NULL,
60                 const XMLCh* digestAlg=NULL
61                 ) const;
62         };
63
64         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const DOMElement* const & e)
65         {
66             return new SAML2RedirectEncoder(e);
67         }
68     };
69 };
70
71 long SAML2RedirectEncoder::encode(
72     GenericResponse& genericResponse,
73     XMLObject* xmlObject,
74     const char* destination,
75     const char* recipientID,
76     const char* relayState,
77     const Credential* credential,
78     const XMLCh* signatureAlg,
79     const XMLCh* digestAlg
80     ) const
81 {
82 #ifdef _DEBUG
83     xmltooling::NDC ndc("encode");
84 #endif
85     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
86
87     log.debug("validating input");
88     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
89     if (!httpResponse)
90         throw BindingException("Unable to cast response interface to HTTPResponse type.");
91     if (xmlObject->getParent())
92         throw BindingException("Cannot encode XML content with parent.");
93     
94     StatusResponseType* response = NULL;
95     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
96     if (!request) {
97         response = dynamic_cast<StatusResponseType*>(xmlObject);
98         if (!response)
99             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
100     }
101     
102     // Check for XML signature.
103     if (request ? request->getSignature() : response->getSignature()) {
104         log.debug("message already signed, removing native signature due to size considerations");
105         request ? request->setSignature(NULL) : response->setSignature(NULL);
106     }
107     
108     log.debug("marshalling, deflating, base64-encoding the message");
109     DOMElement* rootElement = xmlObject->marshall();
110     string xmlbuf;
111     XMLHelper::serialize(rootElement, xmlbuf);
112     
113     unsigned int len;
114     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
115     if (!deflated)
116         throw BindingException("Failed to deflate message.");
117     
118     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated),len,&len);
119     delete[] deflated;
120     if (!encoded)
121         throw BindingException("Base64 encoding of XML failed.");
122     
123     // Create beginnings of redirect query string.
124     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
125     xmlbuf.erase();
126     xmlbuf.append(reinterpret_cast<char*>(encoded),len);
127     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
128     if (relayState)
129         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
130   
131     if (credential) {
132         // Sign the query string after adding the algorithm.
133         if (!signatureAlg)
134             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
135         auto_ptr_char alg(signatureAlg);
136         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
137
138         char sigbuf[1024];
139         memset(sigbuf,0,sizeof(sigbuf));
140         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
141         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
142     }
143     
144     // Generate redirect.
145     log.debug("message encoded, sending redirect to client");
146     xmlbuf.insert(0,1,(strchr(destination,'?') ? '&' : '?'));
147     xmlbuf.insert(0,destination);
148     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
149
150     // Cleanup by destroying XML.
151     delete xmlObject;
152     
153     return ret;
154 }