Raw signature trust support, Redirect binding, "simple" signing rule.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectEncoder.cpp
1 /*
2  *  Copyright 2001-2006 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/HTTPResponse.h"
26 #include "binding/URLEncoder.h"
27 #include "saml2/binding/SAML2Redirect.h"
28 #include "saml2/binding/SAML2RedirectEncoder.h"
29 #include "saml2/core/Protocols.h"
30
31 #include <fstream>
32 #include <sstream>
33 #include <log4cpp/Category.hh>
34 #include <xercesc/util/Base64.hpp>
35 #include <xsec/enc/XSECCryptoException.hpp>
36 #include <xsec/enc/XSECCryptoProvider.hpp>
37 #include <xsec/framework/XSECException.hpp>
38 #include <xmltooling/util/NDC.h>
39
40 using namespace opensaml::saml2p;
41 using namespace opensaml;
42 using namespace xmlsignature;
43 using namespace xmltooling;
44 using namespace log4cpp;
45 using namespace std;
46
47 namespace opensaml {
48     namespace saml2p {              
49         MessageEncoder* SAML_DLLLOCAL SAML2RedirectEncoderFactory(const DOMElement* const & e)
50         {
51             return new SAML2RedirectEncoder(e);
52         }
53     };
54 };
55
56 long SAML2RedirectEncoder::encode(
57     GenericResponse& genericResponse,
58     XMLObject* xmlObject,
59     const char* destination,
60     const char* recipientID,
61     const char* relayState,
62     const CredentialResolver* credResolver,
63     const XMLCh* sigAlgorithm
64     ) const
65 {
66 #ifdef _DEBUG
67     xmltooling::NDC ndc("encode");
68 #endif
69     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
70
71     log.debug("validating input");
72     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
73     if (!httpResponse)
74         throw BindingException("Unable to cast response interface to HTTPResponse type.");
75     if (xmlObject->getParent())
76         throw BindingException("Cannot encode XML content with parent.");
77     
78     StatusResponseType* response = NULL;
79     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
80     if (!request) {
81         response = dynamic_cast<StatusResponseType*>(xmlObject);
82         if (!response)
83             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
84     }
85     
86     // Check for XML signature.
87     if (request ? request->getSignature() : response->getSignature()) {
88         log.debug("message already signed, removing native signature due to size considerations");
89         request ? request->setSignature(NULL) : response->setSignature(NULL);
90     }
91     
92     log.debug("marshalling, deflating, base64-encoding the message");
93     DOMElement* rootElement = xmlObject->marshall();
94     string xmlbuf;
95     XMLHelper::serialize(rootElement, xmlbuf);
96     
97     unsigned int len;
98     char* deflated = deflate(const_cast<char*>(xmlbuf.c_str()), xmlbuf.length(), &len);
99     if (!deflated)
100         throw BindingException("Failed to deflate message.");
101     
102     XMLByte* encoded=Base64::encode(reinterpret_cast<XMLByte*>(deflated),len,&len);
103     delete[] deflated;
104     if (!encoded)
105         throw BindingException("Base64 encoding of XML failed.");
106     
107     // Create beginnings of redirect query string.
108     URLEncoder* escaper = SAMLConfig::getConfig().getURLEncoder();
109     xmlbuf.erase();
110     xmlbuf.append(reinterpret_cast<char*>(encoded),len);
111     xmlbuf = (request ? "SAMLRequest=" : "SAMLResponse=") + escaper->encode(xmlbuf.c_str()); 
112     if (relayState)
113         xmlbuf = xmlbuf + "&RelayState=" + escaper->encode(relayState);
114   
115     if (credResolver) {
116         // Sign the query string after adding the algorithm.
117         if (!sigAlgorithm)
118             sigAlgorithm = DSIGConstants::s_unicodeStrURIRSA_SHA1;
119         auto_ptr_char alg(sigAlgorithm);
120         xmlbuf = xmlbuf + "&SigAlg=" + escaper->encode(alg.get());
121
122         try {
123             char sigbuf[1024];
124             memset(sigbuf,0,sizeof(sigbuf));
125             auto_ptr<XSECCryptoKey> key(credResolver->getKey());
126             Signature::createRawSignature(key.get(), sigAlgorithm, xmlbuf.c_str(), xmlbuf.length(), sigbuf, sizeof(sigbuf)-1);
127             xmlbuf = xmlbuf + "&Signature=" + escaper->encode(sigbuf);
128         }
129         catch(XSECException& e) {
130             auto_ptr_char temp(e.getMsg());
131             throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + temp.get());
132         }
133         catch(XSECCryptoException& e) {
134             throw SignatureException(string("Caught an XMLSecurity exception while signing: ") + e.getMsg());
135         }
136     }
137     
138     // Generate redirect.
139     log.debug("message encoded, sending redirect to client");
140     xmlbuf.insert(0,1,(strchr(destination,'?') ? '&' : '?'));
141     xmlbuf.insert(0,destination);
142     long ret = httpResponse->sendRedirect(xmlbuf.c_str());
143
144     // Cleanup by destroying XML.
145     delete xmlObject;
146     
147     return ret;
148 }