616d98f727ed9fc5b57867a46a71ca68da3a1fe8
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectEncoder.cpp
1 /*
2  *  Copyright 2001-2010 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/MessageEncoder.h"
26 #include "saml2/binding/SAML2Redirect.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <xercesc/util/Base64.hpp>
32 #include <xsec/dsig/DSIGConstants.hpp>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPResponse.h>
36 #include <xmltooling/security/Credential.h>
37 #include <xmltooling/signature/Signature.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/URLEncoder.h>
40
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2md;
43 using namespace opensaml;
44 using namespace xmlsignature;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
47 using namespace std;
48
49 namespace opensaml {
50     namespace saml2p {              
51         class SAML_DLLLOCAL SAML2RedirectEncoder : public MessageEncoder
52         {
53         public:
54             SAML2RedirectEncoder() {}
55             virtual ~SAML2RedirectEncoder() {}
56
57             bool isCompact() const {
58                 return true;
59             }
60
61             const XMLCh* getProtocolFamily() const {
62                 return samlconstants::SAML20P_NS;
63             }
64
65             long encode(
66                 GenericResponse& genericResponse,
67                 XMLObject* xmlObject,
68                 const char* destination,
69                 const EntityDescriptor* recipient=nullptr,
70                 const char* relayState=nullptr,
71                 const ArtifactGenerator* artifactGenerator=nullptr,
72                 const Credential* credential=nullptr,
73                 const XMLCh* signatureAlg=nullptr,
74                 const XMLCh* digestAlg=nullptr
75                 ) const;
76         };
77
78         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
79         {
80             return new SAML2RedirectEncoder();
81         }
82     };
83 };
84
85 long SAML2RedirectEncoder::encode(
86     GenericResponse& genericResponse,
87     XMLObject* xmlObject,
88     const char* destination,
89     const EntityDescriptor* recipient,
90     const char* relayState,
91     const ArtifactGenerator* artifactGenerator,
92     const Credential* credential,
93     const XMLCh* signatureAlg,
94     const XMLCh* digestAlg
95     ) const
96 {
97 #ifdef _DEBUG
98     xmltooling::NDC ndc("encode");
99 #endif
100     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
101
102     log.debug("validating input");
103     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
104     if (!httpResponse)
105         throw BindingException("Unable to cast response interface to HTTPResponse type.");
106     if (xmlObject->getParent())
107         throw BindingException("Cannot encode XML content with parent.");
108     
109     StatusResponseType* response = nullptr;
110     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
111     if (!request) {
112         response = dynamic_cast<StatusResponseType*>(xmlObject);
113         if (!response)
114             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
115     }
116     
117     // Check for XML signature.
118     if (request ? request->getSignature() : response->getSignature()) {
119         log.debug("message already signed, removing native signature due to size considerations");
120         request ? request->setSignature(nullptr) : response->setSignature(nullptr);
121     }
122     
123     log.debug("marshalling, deflating, base64-encoding the message");
124     DOMElement* rootElement = xmlObject->marshall();
125     string xmlbuf;
126     XMLHelper::serialize(rootElement, xmlbuf);
127     log.debug("marshalled message:\n%s", xmlbuf.c_str());
128     
129     unsigned int len;
130     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
131     if (!deflated)
132         throw BindingException("Failed to deflate message.");
133     
134     xsecsize_t xlen;
135     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated), len, &xlen);
136     delete[] deflated;
137     if (!encoded)
138         throw BindingException("Base64 encoding of XML failed.");
139     
140     // Create beginnings of redirect query string.
141     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
142     xmlbuf.erase();
143     xmlbuf.append(reinterpret_cast<char*>(encoded), xlen);
144 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
145     XMLString::release(&encoded);
146 #else
147     XMLString::release((char**)&encoded);
148 #endif
149     
150     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
151     if (relayState && *relayState)
152         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
153   
154     if (credential) {
155         log.debug("signing the message");
156         
157         // Sign the query string after adding the algorithm.
158         if (!signatureAlg)
159             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
160         auto_ptr_char alg(signatureAlg);
161         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
162
163         char sigbuf[1024];
164         memset(sigbuf,0,sizeof(sigbuf));
165         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
166         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
167     }
168     
169     // Generate redirect.
170     log.debug("message encoded, sending redirect to client");
171     xmlbuf.insert((string::size_type)0,(string::size_type)1,(strchr(destination,'?') ? '&' : '?'));
172     xmlbuf.insert(0,destination);
173     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
174
175     // Cleanup by destroying XML.
176     delete xmlObject;
177     
178     return ret;
179 }