9ff9e26b1d003371c5e140ffbc23b2244bd11470
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectDecoder.cpp
1 /*
2  *  Copyright 2001-2009 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  * SAML2RedirectDecoder.cpp
19  *
20  * SAML 2.0 HTTP Redirect binding message encoder.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/SecurityPolicy.h"
26 #include "saml2/binding/SAML2MessageDecoder.h"
27 #include "saml2/binding/SAML2Redirect.h"
28 #include "saml2/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/MetadataProvider.h"
31
32 #include <xercesc/util/Base64.hpp>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPRequest.h>
36 #include <xmltooling/util/NDC.h>
37 #include <xmltooling/util/ParserPool.h>
38 #include <xmltooling/validation/ValidatorSuite.h>
39
40 using namespace opensaml::saml2md;
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2;
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 SAML2RedirectDecoder : public SAML2MessageDecoder
52         {
53         public:
54             SAML2RedirectDecoder() {}
55             virtual ~SAML2RedirectDecoder() {}
56
57             xmltooling::XMLObject* decode(
58                 std::string& relayState,
59                 const GenericRequest& genericRequest,
60                 SecurityPolicy& policy
61                 ) const;
62         };
63
64         MessageDecoder* SAML_DLLLOCAL SAML2RedirectDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
65         {
66             return new SAML2RedirectDecoder();
67         }
68     };
69 };
70
71 XMLObject* SAML2RedirectDecoder::decode(
72     string& relayState,
73     const GenericRequest& genericRequest,
74     SecurityPolicy& policy
75     ) const
76 {
77 #ifdef _DEBUG
78     xmltooling::NDC ndc("decode");
79 #endif
80     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Redirect");
81
82     log.debug("validating input");
83     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
84     if (!httpRequest)
85         throw BindingException("Unable to cast request object to HTTPRequest type.");
86     const char* msg = httpRequest->getParameter("SAMLResponse");
87     if (!msg)
88         msg = httpRequest->getParameter("SAMLRequest");
89     if (!msg)
90         throw BindingException("Request missing SAMLRequest or SAMLResponse query string parameter.");
91     const char* state = httpRequest->getParameter("RelayState");
92     if (state)
93         relayState = state;
94     else
95         relayState.erase();
96     state = httpRequest->getParameter("SAMLEncoding");
97     if (state && strcmp(state,samlconstants::SAML20_BINDING_URL_ENCODING_DEFLATE)) {
98         log.warn("SAMLEncoding (%s) was not recognized", state);
99         throw BindingException("Unsupported SAMLEncoding value.");
100     }
101
102     // Decode the compressed message into SAML. First we base64-decode it.
103     xsecsize_t x;
104     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
105     if (!decoded)
106         throw BindingException("Unable to decode base64 in Redirect binding message.");
107
108     // Now we have to inflate it.
109     stringstream s;
110     if (inflate(reinterpret_cast<char*>(decoded), x, s)==0) {
111 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
112         XMLString::release(&decoded);
113 #else
114         XMLString::release((char**)&decoded);
115 #endif
116         throw BindingException("Unable to inflate Redirect binding message.");
117     }
118     if (log.isDebugEnabled())
119         log.debug("decoded SAML message:\n%s", s.str().c_str());
120 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
121     XMLString::release(&decoded);
122 #else
123     XMLString::release((char**)&decoded);
124 #endif
125
126     // Parse and bind the document into an XMLObject.
127     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
128         : XMLToolingConfig::getConfig().getParser()).parse(s);
129     XercesJanitor<DOMDocument> janitor(doc);
130     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
131     janitor.release();
132
133     saml2::RootObject* root = NULL;
134     StatusResponseType* response = NULL;
135     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
136     if (!request) {
137         response = dynamic_cast<StatusResponseType*>(xmlObject.get());
138         if (!response)
139             throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
140         root = static_cast<saml2::RootObject*>(response);
141     }
142     else {
143         root = static_cast<saml2::RootObject*>(request);
144     }
145
146     SchemaValidators.validate(root);
147
148     // Run through the policy.
149     extractMessageDetails(*root, genericRequest, samlconstants::SAML20P_NS, policy);
150     policy.evaluate(*root, &genericRequest);
151
152     // Check destination URL.
153     auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
154     const char* dest2 = httpRequest->getRequestURL();
155     const char* delim = strchr(dest2, '?');
156     if ((root->getSignature() || httpRequest->getParameter("Signature")) && (!dest.get() || !*(dest.get()))) {
157         log.error("signed SAML message missing Destination attribute");
158         throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
159     }
160     else if (dest.get() && *dest.get() && ((delim && strncmp(dest.get(), dest2, delim - dest2)) || (!delim && strcmp(dest.get(),dest2)))) {
161         log.error("Redirect targeted at (%s), but delivered to (%s)", dest.get(), dest2);
162         throw BindingException("SAML message delivered with Redirect to incorrect server URL.");
163     }
164
165     return xmlObject.release();
166 }