Add Destination check.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ECPDecoder.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  * SAML2ECPDecoder.cpp
19  * 
20  * SAML 2.0 ECP profile message decoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "saml2/binding/SAML2MessageDecoder.h"
26 #include "saml2/core/Protocols.h"
27
28 #include <xmltooling/logging.h>
29 #include <xmltooling/io/HTTPRequest.h>
30 #include <xmltooling/soap/SOAP.h>
31 #include <xmltooling/util/NDC.h>
32 #include <xmltooling/validation/ValidatorSuite.h>
33
34 using namespace opensaml::saml2p;
35 using namespace opensaml;
36 using namespace soap11;
37 using namespace xmltooling::logging;
38 using namespace xmltooling;
39 using namespace std;
40
41 namespace opensaml {
42     namespace saml2p {              
43         class SAML_DLLLOCAL SAML2ECPDecoder : public SAML2MessageDecoder
44         {
45         public:
46             SAML2ECPDecoder() {}
47             virtual ~SAML2ECPDecoder() {}
48
49             xmltooling::XMLObject* decode(
50                 std::string& relayState,
51                 const GenericRequest& genericRequest,
52                 SecurityPolicy& policy
53                 ) const;
54         };                
55
56         MessageDecoder* SAML_DLLLOCAL SAML2ECPDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
57         {
58             return new SAML2ECPDecoder();
59         }
60     };
61 };
62
63 XMLObject* SAML2ECPDecoder::decode(
64     string& relayState,
65     const GenericRequest& genericRequest,
66     SecurityPolicy& policy
67     ) const
68 {
69 #ifdef _DEBUG
70     xmltooling::NDC ndc("decode");
71 #endif
72     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2ECP");
73
74     log.debug("validating input");
75     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
76     if (!httpRequest)
77         throw BindingException("Unable to cast request object to HTTPRequest type.");
78     string s = genericRequest.getContentType();
79     if (s.find("application/vnd.paos+xml") == string::npos) {
80         log.warn("ignoring incorrect content type (%s)", s.c_str() ? s.c_str() : "none");
81         throw BindingException("Invalid content type for PAOS message.");
82     }
83
84     const char* data = genericRequest.getRequestBody();
85     if (!data)
86         throw BindingException("PAOS message had an empty request body.");
87     istringstream is(data);
88     
89     // Parse and bind the document into an XMLObject.
90     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
91         : XMLToolingConfig::getConfig().getParser()).parse(is); 
92     XercesJanitor<DOMDocument> janitor(doc);
93     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
94     janitor.release();
95
96     Envelope* env = dynamic_cast<Envelope*>(xmlObject.get());
97     if (!env)
98         throw BindingException("Decoded message was not a SOAP 1.1 Envelope.");
99
100     if (!policy.getValidating())
101         SchemaValidators.validate(env);
102     
103     Body* body = env->getBody();
104     if (body && body->hasChildren()) {
105         Response* response = dynamic_cast<Response*>(body->getUnknownXMLObjects().front());
106         if (response) {
107             // Run through the policy at two layers.
108             extractMessageDetails(*env, genericRequest, samlconstants::SAML20P_NS, policy);
109             policy.evaluate(*env, &genericRequest);
110             policy.reset(true);
111             extractMessageDetails(*response, genericRequest, samlconstants::SAML20P_NS, policy);
112             policy.evaluate(*response, &genericRequest);
113
114             // Check destination URL.
115             auto_ptr_char dest(response->getDestination());
116             const char* dest2 = httpRequest->getRequestURL();
117             const char* delim = strchr(dest2, '?');
118             if (response->getSignature() && (!dest.get() || !*(dest.get()))) {
119                 log.error("signed SAML message missing Destination attribute");
120                 throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
121             }
122             else if (dest.get() && *dest.get() && ((delim && strncmp(dest.get(), dest2, delim - dest2)) || (!delim && strcmp(dest.get(),dest2)))) {
123                 log.error("PAOS response targeted at (%s), but delivered to (%s)", dest.get(), dest2);
124                 throw BindingException("SAML message delivered with PAOS to incorrect server URL.");
125             }
126
127             // Check for RelayState header.
128             if (env->getHeader()) {
129                 const vector<XMLObject*>& blocks = const_cast<const Header*>(env->getHeader())->getUnknownXMLObjects();
130                 for (vector<XMLObject*>::const_iterator h = blocks.begin(); h != blocks.end(); ++h) {
131                     static const XMLCh RelayState[] = UNICODE_LITERAL_10(R,e,l,a,y,S,t,a,t,e);
132                     if (XMLString::equals((*h)->getElementQName().getLocalPart(), RelayState) &&
133                             XMLString::equals((*h)->getElementQName().getNamespaceURI(), samlconstants::SAML20ECP_NS)) {
134                         const ElementProxy* ep = dynamic_cast<const ElementProxy*>(*h);
135                         if (ep) {
136                             auto_ptr_char rs(ep->getTextContent());
137                             if (rs.get()) {
138                                 relayState = rs.get();
139                                 break;
140                             }
141                         }
142                     }
143                 }
144             }
145             
146             xmlObject.release();
147             body->detach(); // frees Envelope
148             response->detach();   // frees Body
149             return response;
150         }
151     }
152     
153     throw BindingException("SOAP Envelope did not contain a SAML Response.");
154 }