Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTDecoder.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  * SAML2POSTDecoder.cpp
19  * 
20  * SAML 2.0 HTTP POST binding message encoder
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 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataProvider.h"
30
31 #include <xercesc/framework/MemBufInputSource.hpp>
32 #include <xercesc/framework/Wrapper4InputSource.hpp>
33 #include <xercesc/util/Base64.hpp>
34 #include <xmltooling/logging.h>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/io/HTTPRequest.h>
37 #include <xmltooling/util/NDC.h>
38 #include <xmltooling/validation/ValidatorSuite.h>
39
40 using namespace opensaml::saml2md;
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2;
43 using namespace opensaml;
44 using namespace xmltooling::logging;
45 using namespace xmltooling;
46 using namespace std;
47
48 namespace opensaml {
49     namespace saml2p {              
50         class SAML_DLLLOCAL SAML2POSTDecoder : public SAML2MessageDecoder
51         {
52         public:
53             SAML2POSTDecoder() {}
54             virtual ~SAML2POSTDecoder() {}
55             
56             xmltooling::XMLObject* decode(
57                 std::string& relayState,
58                 const GenericRequest& genericRequest,
59                 SecurityPolicy& policy
60                 ) const;
61         };                
62
63         MessageDecoder* SAML_DLLLOCAL SAML2POSTDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
64         {
65             return new SAML2POSTDecoder();
66         }
67     };
68 };
69
70 XMLObject* SAML2POSTDecoder::decode(
71     std::string& relayState,
72     const GenericRequest& genericRequest,
73     SecurityPolicy& policy
74     ) const
75 {
76 #ifdef _DEBUG
77     xmltooling::NDC ndc("decode");
78 #endif
79     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2POST");
80
81     log.debug("validating input");
82     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
83     if (!httpRequest)
84         throw BindingException("Unable to cast request object to HTTPRequest type.");
85     if (strcmp(httpRequest->getMethod(),"POST"))
86         throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
87     const char* msg = httpRequest->getParameter("SAMLResponse");
88     if (!msg)
89         msg = httpRequest->getParameter("SAMLRequest");
90     if (!msg)
91         throw BindingException("Request missing SAMLRequest or SAMLResponse form parameter.");
92     const char* state = httpRequest->getParameter("RelayState");
93     if (state)
94         relayState = state;
95     else
96         relayState.erase();
97
98     // Decode the base64 into SAML.
99     xsecsize_t x;
100     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
101     if (!decoded)
102         throw BindingException("Unable to decode base64 in POST binding message.");
103     log.debugStream() << "decoded SAML message:\n" << decoded << logging::eol;
104     
105     // Parse and bind the document into an XMLObject.
106     MemBufInputSource src(decoded, x, "SAMLMessage", true);
107     Wrapper4InputSource dsrc(&src, false);
108     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
109         : XMLToolingConfig::getConfig().getParser()).parse(dsrc); 
110     XercesJanitor<DOMDocument> janitor(doc);
111     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
112     janitor.release();
113
114     saml2::RootObject* root = NULL;
115     StatusResponseType* response = NULL;
116     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
117     if (!request) {
118         response = dynamic_cast<StatusResponseType*>(xmlObject.get());
119         if (!response)
120             throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
121         root = static_cast<saml2::RootObject*>(response);
122     }
123     else {
124         root = static_cast<saml2::RootObject*>(request);
125     }
126     
127     SchemaValidators.validate(root);
128
129     // Run through the policy.
130     extractMessageDetails(*root, genericRequest, samlconstants::SAML20P_NS, policy);
131     policy.evaluate(*root, &genericRequest);
132     
133     // Check destination URL.
134     auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
135     const char* dest2 = httpRequest->getRequestURL();
136     const char* delim = strchr(dest2, '?');
137     if ((root->getSignature() || httpRequest->getParameter("Signature")) && (!dest.get() || !*(dest.get()))) {
138         log.error("signed SAML message missing Destination attribute");
139         throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
140     }
141     else if (dest.get() && *dest.get() && ((delim && strncmp(dest.get(), dest2, delim - dest2)) || (!delim && strcmp(dest.get(),dest2)))) {
142         log.error("POST targeted at (%s), but delivered to (%s)", dest.get(), dest2);
143         throw BindingException("SAML message delivered with POST to incorrect server URL.");
144     }
145     
146     return xmlObject.release();
147 }