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