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