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