Convert from NULL macro to nullptr, remove unused zlib code.
[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             long encode(
62                 GenericResponse& genericResponse,
63                 XMLObject* xmlObject,
64                 const char* destination,
65                 const EntityDescriptor* recipient=nullptr,
66                 const char* relayState=nullptr,
67                 const ArtifactGenerator* artifactGenerator=nullptr,
68                 const Credential* credential=nullptr,
69                 const XMLCh* signatureAlg=nullptr,
70                 const XMLCh* digestAlg=nullptr
71                 ) const;
72         };
73
74         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
75         {
76             return new SAML2RedirectEncoder();
77         }
78     };
79 };
80
81 long SAML2RedirectEncoder::encode(
82     GenericResponse& genericResponse,
83     XMLObject* xmlObject,
84     const char* destination,
85     const EntityDescriptor* recipient,
86     const char* relayState,
87     const ArtifactGenerator* artifactGenerator,
88     const Credential* credential,
89     const XMLCh* signatureAlg,
90     const XMLCh* digestAlg
91     ) const
92 {
93 #ifdef _DEBUG
94     xmltooling::NDC ndc("encode");
95 #endif
96     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
97
98     log.debug("validating input");
99     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
100     if (!httpResponse)
101         throw BindingException("Unable to cast response interface to HTTPResponse type.");
102     if (xmlObject->getParent())
103         throw BindingException("Cannot encode XML content with parent.");
104     
105     StatusResponseType* response = nullptr;
106     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
107     if (!request) {
108         response = dynamic_cast<StatusResponseType*>(xmlObject);
109         if (!response)
110             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
111     }
112     
113     // Check for XML signature.
114     if (request ? request->getSignature() : response->getSignature()) {
115         log.debug("message already signed, removing native signature due to size considerations");
116         request ? request->setSignature(nullptr) : response->setSignature(nullptr);
117     }
118     
119     log.debug("marshalling, deflating, base64-encoding the message");
120     DOMElement* rootElement = xmlObject->marshall();
121     string xmlbuf;
122     XMLHelper::serialize(rootElement, xmlbuf);
123     log.debug("marshalled message:\n%s", xmlbuf.c_str());
124     
125     unsigned int len;
126     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
127     if (!deflated)
128         throw BindingException("Failed to deflate message.");
129     
130     xsecsize_t xlen;
131     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated), len, &xlen);
132     delete[] deflated;
133     if (!encoded)
134         throw BindingException("Base64 encoding of XML failed.");
135     
136     // Create beginnings of redirect query string.
137     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
138     xmlbuf.erase();
139     xmlbuf.append(reinterpret_cast<char*>(encoded), xlen);
140 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
141     XMLString::release(&encoded);
142 #else
143     XMLString::release((char**)&encoded);
144 #endif
145     
146     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
147     if (relayState && *relayState)
148         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
149   
150     if (credential) {
151         log.debug("signing the message");
152         
153         // Sign the query string after adding the algorithm.
154         if (!signatureAlg)
155             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
156         auto_ptr_char alg(signatureAlg);
157         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
158
159         char sigbuf[1024];
160         memset(sigbuf,0,sizeof(sigbuf));
161         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
162         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
163     }
164     
165     // Generate redirect.
166     log.debug("message encoded, sending redirect to client");
167     xmlbuf.insert((string::size_type)0,(string::size_type)1,(strchr(destination,'?') ? '&' : '?'));
168     xmlbuf.insert(0,destination);
169     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
170
171     // Cleanup by destroying XML.
172     delete xmlObject;
173     
174     return ret;
175 }