0cbab6cd999b819cf4627344dbd9bd1f5c6ea759
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectEncoder.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2RedirectEncoder.cpp
23  * 
24  * SAML 2.0 HTTP-POST binding message encoder.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/MessageEncoder.h"
30 #include "saml2/binding/SAML2Redirect.h"
31 #include "saml2/core/Protocols.h"
32
33 #include <fstream>
34 #include <sstream>
35 #include <xercesc/util/Base64.hpp>
36 #include <xsec/dsig/DSIGConstants.hpp>
37 #include <xmltooling/logging.h>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/io/HTTPResponse.h>
40 #include <xmltooling/security/Credential.h>
41 #include <xmltooling/signature/Signature.h>
42 #include <xmltooling/util/NDC.h>
43 #include <xmltooling/util/URLEncoder.h>
44
45 using namespace opensaml::saml2p;
46 using namespace opensaml::saml2md;
47 using namespace opensaml;
48 using namespace xmlsignature;
49 using namespace xmltooling::logging;
50 using namespace xmltooling;
51 using namespace std;
52
53 namespace opensaml {
54     namespace saml2p {              
55         class SAML_DLLLOCAL SAML2RedirectEncoder : public MessageEncoder
56         {
57         public:
58             SAML2RedirectEncoder() {}
59             virtual ~SAML2RedirectEncoder() {}
60
61             bool isCompact() const {
62                 return true;
63             }
64
65             const XMLCh* getProtocolFamily() const {
66                 return samlconstants::SAML20P_NS;
67             }
68
69             long encode(
70                 GenericResponse& genericResponse,
71                 XMLObject* xmlObject,
72                 const char* destination,
73                 const EntityDescriptor* recipient=nullptr,
74                 const char* relayState=nullptr,
75                 const ArtifactGenerator* artifactGenerator=nullptr,
76                 const Credential* credential=nullptr,
77                 const XMLCh* signatureAlg=nullptr,
78                 const XMLCh* digestAlg=nullptr
79                 ) const;
80         };
81
82         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
83         {
84             return new SAML2RedirectEncoder();
85         }
86     };
87 };
88
89 long SAML2RedirectEncoder::encode(
90     GenericResponse& genericResponse,
91     XMLObject* xmlObject,
92     const char* destination,
93     const EntityDescriptor* recipient,
94     const char* relayState,
95     const ArtifactGenerator* artifactGenerator,
96     const Credential* credential,
97     const XMLCh* signatureAlg,
98     const XMLCh* digestAlg
99     ) const
100 {
101 #ifdef _DEBUG
102     xmltooling::NDC ndc("encode");
103 #endif
104     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Redirect");
105
106     log.debug("validating input");
107     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
108     if (!httpResponse)
109         throw BindingException("Unable to cast response interface to HTTPResponse type.");
110     if (xmlObject->getParent())
111         throw BindingException("Cannot encode XML content with parent.");
112     
113     StatusResponseType* response = nullptr;
114     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
115     if (!request) {
116         response = dynamic_cast<StatusResponseType*>(xmlObject);
117         if (!response)
118             throw BindingException("XML content for SAML 2.0 HTTP-Redirect Encoder must be a SAML 2.0 protocol message.");
119     }
120     
121     // Check for XML signature.
122     if (request ? request->getSignature() : response->getSignature()) {
123         log.debug("message already signed, removing native signature due to size considerations");
124         request ? request->setSignature(nullptr) : response->setSignature(nullptr);
125     }
126     
127     log.debug("marshalling, deflating, base64-encoding the message");
128     DOMElement* rootElement = xmlObject->marshall();
129     string xmlbuf;
130     XMLHelper::serialize(rootElement, xmlbuf);
131     log.debug("marshalled message:\n%s", xmlbuf.c_str());
132     
133     unsigned int len;
134     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
135     if (!deflated)
136         throw BindingException("Failed to deflate message.");
137     
138     xsecsize_t xlen;
139     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated), len, &xlen);
140     delete[] deflated;
141     if (!encoded)
142         throw BindingException("Base64 encoding of XML failed.");
143     
144     // Create beginnings of redirect query string.
145     xmlbuf.erase();
146     for (const XMLByte* xb = encoded; *xb; ++xb) {
147         if (!isspace(*xb))
148             xmlbuf += *xb;
149     }
150 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
151     XMLString::release(&encoded);
152 #else
153     XMLString::release((char**)&encoded);
154 #endif
155     
156     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
157     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
158     if (relayState && *relayState)
159         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
160   
161     if (credential) {
162         log.debug("signing the message");
163         
164         // Sign the query string after adding the algorithm.
165         if (!signatureAlg)
166             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
167         auto_ptr_char alg(signatureAlg);
168         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
169
170         char sigbuf[1024];
171         memset(sigbuf,0,sizeof(sigbuf));
172         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
173         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
174     }
175     
176     // Generate redirect.
177     log.debug("message encoded, sending redirect to client");
178     xmlbuf.insert((string::size_type)0,(string::size_type)1,(strchr(destination,'?') ? '&' : '?'));
179     xmlbuf.insert(0,destination);
180     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
181
182     // Cleanup by destroying XML.
183     delete xmlObject;
184     
185     return ret;
186 }