03a0622882e97e4de00317bfd67eef884c81a5cf
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectDecoder.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2RedirectDecoder.cpp
23  *
24  * SAML 2.0 HTTP Redirect binding message encoder.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/SecurityPolicy.h"
30 #include "saml2/binding/SAML2MessageDecoder.h"
31 #include "saml2/binding/SAML2Redirect.h"
32 #include "saml2/core/Protocols.h"
33 #include "saml2/metadata/Metadata.h"
34 #include "saml2/metadata/MetadataProvider.h"
35
36 #include <xercesc/util/Base64.hpp>
37 #include <xmltooling/logging.h>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/io/HTTPRequest.h>
40 #include <xmltooling/util/NDC.h>
41 #include <xmltooling/util/ParserPool.h>
42 #include <xmltooling/validation/ValidatorSuite.h>
43
44 using namespace opensaml::saml2md;
45 using namespace opensaml::saml2p;
46 using namespace opensaml::saml2;
47 using namespace opensaml;
48 using namespace xmlsignature;
49 using namespace xmltooling::logging;
50 using namespace xmltooling;
51 using namespace std;
52
53 namespace opensaml {
54     namespace saml2p {
55         class SAML_DLLLOCAL SAML2RedirectDecoder : public SAML2MessageDecoder
56         {
57         public:
58             SAML2RedirectDecoder() {}
59             virtual ~SAML2RedirectDecoder() {}
60
61             xmltooling::XMLObject* decode(
62                 std::string& relayState,
63                 const GenericRequest& genericRequest,
64                 SecurityPolicy& policy
65                 ) const;
66         };
67
68         MessageDecoder* SAML_DLLLOCAL SAML2RedirectDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
69         {
70             return new SAML2RedirectDecoder();
71         }
72     };
73 };
74
75 XMLObject* SAML2RedirectDecoder::decode(
76     string& relayState,
77     const GenericRequest& genericRequest,
78     SecurityPolicy& policy
79     ) const
80 {
81 #ifdef _DEBUG
82     xmltooling::NDC ndc("decode");
83 #endif
84     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Redirect");
85
86     log.debug("validating input");
87     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
88     if (!httpRequest)
89         throw BindingException("Unable to cast request object to HTTPRequest type.");
90     const char* msg = httpRequest->getParameter("SAMLResponse");
91     if (!msg)
92         msg = httpRequest->getParameter("SAMLRequest");
93     if (!msg)
94         throw BindingException("Request missing SAMLRequest or SAMLResponse query string parameter.");
95     const char* state = httpRequest->getParameter("RelayState");
96     if (state)
97         relayState = state;
98     else
99         relayState.erase();
100     state = httpRequest->getParameter("SAMLEncoding");
101     if (state && strcmp(state,samlconstants::SAML20_BINDING_URL_ENCODING_DEFLATE)) {
102         log.warn("SAMLEncoding (%s) was not recognized", state);
103         throw BindingException("Unsupported SAMLEncoding value.");
104     }
105
106     // Decode the compressed message into SAML. First we base64-decode it.
107     xsecsize_t x;
108     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
109     if (!decoded)
110         throw BindingException("Unable to decode base64 in Redirect binding message.");
111
112     // Now we have to inflate it.
113     stringstream s;
114     if (inflate(reinterpret_cast<char*>(decoded), x, s)==0) {
115 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
116         XMLString::release(&decoded);
117 #else
118         XMLString::release((char**)&decoded);
119 #endif
120         throw BindingException("Unable to inflate Redirect binding message.");
121     }
122     if (log.isDebugEnabled())
123         log.debug("decoded SAML message:\n%s", s.str().c_str());
124 #ifdef OPENSAML_XERCESC_HAS_XMLBYTE_RELEASE
125     XMLString::release(&decoded);
126 #else
127     XMLString::release((char**)&decoded);
128 #endif
129
130     // Parse and bind the document into an XMLObject.
131     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
132         : XMLToolingConfig::getConfig().getParser()).parse(s);
133     XercesJanitor<DOMDocument> janitor(doc);
134     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
135     janitor.release();
136
137     saml2::RootObject* root = nullptr;
138     StatusResponseType* response = nullptr;
139     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
140     if (!request) {
141         response = dynamic_cast<StatusResponseType*>(xmlObject.get());
142         if (!response)
143             throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
144         root = static_cast<saml2::RootObject*>(response);
145     }
146     else {
147         root = static_cast<saml2::RootObject*>(request);
148     }
149
150     SchemaValidators.validate(root);
151
152     // Run through the policy.
153     extractMessageDetails(*root, genericRequest, samlconstants::SAML20P_NS, policy);
154     policy.evaluate(*root, &genericRequest);
155
156     // Check destination URL.
157     auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
158     const char* dest2 = httpRequest->getRequestURL();
159     const char* delim = strchr(dest2, '?');
160     if ((root->getSignature() || httpRequest->getParameter("Signature")) && (!dest.get() || !*(dest.get()))) {
161         log.error("signed SAML message missing Destination attribute");
162         throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
163     }
164     else if (dest.get() && *dest.get() && ((delim && strncmp(dest.get(), dest2, delim - dest2)) || (!delim && strcmp(dest.get(),dest2)))) {
165         log.error("Redirect targeted at (%s), but delivered to (%s)", dest.get(), dest2);
166         throw BindingException("SAML message delivered with Redirect to incorrect server URL.");
167     }
168
169     return xmlObject.release();
170 }