82308f9e9d4118f376e1335e81840a3bba499a68
[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                 xmltooling::XMLObject* xmlObject,
55                 const char* destination,
56                 const char* recipientID=NULL,
57                 const char* relayState=NULL,
58                 const xmltooling::CredentialResolver* credResolver=NULL,
59                 const XMLCh* sigAlgorithm=NULL
60                 ) const;
61         };
62
63         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const DOMElement* const & e)
64         {
65             return new SAML2RedirectEncoder(e);
66         }
67     };
68 };
69
70 long SAML2RedirectEncoder::encode(
71     GenericResponse& genericResponse,
72     XMLObject* xmlObject,
73     const char* destination,
74     const char* recipientID,
75     const char* relayState,
76     const CredentialResolver* credResolver,
77     const XMLCh* sigAlgorithm
78     ) const
79 {
80 #ifdef _DEBUG
81     xmltooling::NDC ndc("encode");
82 #endif
83     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
84
85     log.debug("validating input");
86     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
87     if (!httpResponse)
88         throw BindingException("Unable to cast response interface to HTTPResponse type.");
89     if (xmlObject->getParent())
90         throw BindingException("Cannot encode XML content with parent.");
91     
92     StatusResponseType* response = NULL;
93     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
94     if (!request) {
95         response = dynamic_cast<StatusResponseType*>(xmlObject);
96         if (!response)
97             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
98     }
99     
100     // Check for XML signature.
101     if (request ? request->getSignature() : response->getSignature()) {
102         log.debug("message already signed, removing native signature due to size considerations");
103         request ? request->setSignature(NULL) : response->setSignature(NULL);
104     }
105     
106     log.debug("marshalling, deflating, base64-encoding the message");
107     DOMElement* rootElement = xmlObject->marshall();
108     string xmlbuf;
109     XMLHelper::serialize(rootElement, xmlbuf);
110     
111     unsigned int len;
112     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
113     if (!deflated)
114         throw BindingException("Failed to deflate message.");
115     
116     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated),len,&len);
117     delete[] deflated;
118     if (!encoded)
119         throw BindingException("Base64 encoding of XML failed.");
120     
121     // Create beginnings of redirect query string.
122     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
123     xmlbuf.erase();
124     xmlbuf.append(reinterpret_cast<char*>(encoded),len);
125     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
126     if (relayState)
127         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
128   
129     if (credResolver) {
130         // Sign the query string after adding the algorithm.
131         if (!sigAlgorithm)
132             sigAlgorithm = DSIGConstants::s_unicodeStrURIRSA_SHA1;
133         auto_ptr_char alg(sigAlgorithm);
134         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
135
136         char sigbuf[1024];
137         memset(sigbuf,0,sizeof(sigbuf));
138         auto_ptr<XSECCryptoKey> key(credResolver->getKey());
139         Signature::createRawSignature(key.get(), sigAlgorithm, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
140         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
141     }
142     
143     // Generate redirect.
144     log.debug("message encoded, sending redirect to client");
145     xmlbuf.insert(0,1,(strchr(destination,'?') ? '&' : '?'));
146     xmlbuf.insert(0,destination);
147     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
148
149     // Cleanup by destroying XML.
150     delete xmlObject;
151     
152     return ret;
153 }