Add short name to encoders/decoders for endpoint generation.
[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             const char* getShortName() const {
66                 return "Redirect";
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     const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
146     xmlbuf.erase();
147     xmlbuf.append(reinterpret_cast<char*>(encoded), xlen);
148 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
149     XMLString::release(&encoded);
150 #else
151     XMLString::release((char**)&encoded);
152 #endif
153     
154     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
155     if (relayState && *relayState)
156         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
157   
158     if (credential) {
159         log.debug("signing the message");
160         
161         // Sign the query string after adding the algorithm.
162         if (!signatureAlg)
163             signatureAlg = DSIGConstants::s_unicodeStrURIRSA_SHA1;
164         auto_ptr_char alg(signatureAlg);
165         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
166
167         char sigbuf[1024];
168         memset(sigbuf,0,sizeof(sigbuf));
169         Signature::createRawSignature(credential->getPrivateKey(), signatureAlg, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
170         xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
171     }
172     
173     // Generate redirect.
174     log.debug("message encoded, sending redirect to client");
175     xmlbuf.insert((string::size_type)0,(string::size_type)1,(strchr(destination,'?') ? '&' : '?'));
176     xmlbuf.insert(0,destination);
177     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
178
179     // Cleanup by destroying XML.
180     delete xmlObject;
181     
182     return ret;
183 }