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