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