Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTDecoder.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  * SAML1POSTDecoder.cpp
19  * 
20  * SAML 1.x POST binding/profile message decoder.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/SecurityPolicy.h"
26 #include "saml1/binding/SAML1MessageDecoder.h"
27 #include "saml1/core/Assertions.h"
28 #include "saml1/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/MetadataProvider.h"
31
32 #include <xercesc/framework/MemBufInputSource.hpp>
33 #include <xercesc/framework/Wrapper4InputSource.hpp>
34 #include <xercesc/util/Base64.hpp>
35 #include <xmltooling/logging.h>
36 #include <xmltooling/XMLToolingConfig.h>
37 #include <xmltooling/io/HTTPRequest.h>
38 #include <xmltooling/util/NDC.h>
39 #include <xmltooling/util/ParserPool.h>
40 #include <xmltooling/validation/ValidatorSuite.h>
41
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml1p;
44 using namespace opensaml::saml1;
45 using namespace opensaml;
46 using namespace xmltooling::logging;
47 using namespace xmltooling;
48 using namespace std;
49
50 namespace opensaml {
51     namespace saml1p {              
52         class SAML_DLLLOCAL SAML1POSTDecoder : public SAML1MessageDecoder
53         {
54         public:
55             SAML1POSTDecoder() {}
56             virtual ~SAML1POSTDecoder() {}
57             
58             xmltooling::XMLObject* decode(
59                 std::string& relayState,
60                 const GenericRequest& genericRequest,
61                 SecurityPolicy& policy
62                 ) const;
63         };                
64
65         MessageDecoder* SAML_DLLLOCAL SAML1POSTDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
66         {
67             return new SAML1POSTDecoder();
68         }
69     };
70 };
71
72 XMLObject* SAML1POSTDecoder::decode(
73     string& relayState,
74     const GenericRequest& genericRequest,
75     SecurityPolicy& policy
76     ) const
77 {
78 #ifdef _DEBUG
79     xmltooling::NDC ndc("decode");
80 #endif
81     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML1POST");
82
83     log.debug("validating input");
84     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
85     if (!httpRequest)
86         throw BindingException("Unable to cast request object to HTTPRequest type.");
87     if (strcmp(httpRequest->getMethod(),"POST"))
88         throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
89     const char* samlResponse = httpRequest->getParameter("SAMLResponse");
90     const char* TARGET = httpRequest->getParameter("TARGET");
91     if (!samlResponse || !TARGET)
92         throw BindingException("Request missing SAMLResponse or TARGET form parameters.");
93     relayState = TARGET;
94
95     // Decode the base64 into XML.
96     xsecsize_t x;
97     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(samlResponse),&x);
98     if (!decoded)
99         throw BindingException("Unable to decode base64 in POST profile response.");
100     log.debugStream() << "decoded SAML response:\n" << decoded << logging::eol;
101
102     // Parse and bind the document into an XMLObject.
103     MemBufInputSource src(decoded, x, "SAMLResponse", true);
104     Wrapper4InputSource dsrc(&src, false);
105     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
106         : XMLToolingConfig::getConfig().getParser()).parse(dsrc); 
107     XercesJanitor<DOMDocument> janitor(doc);
108     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
109     janitor.release();
110
111     Response* response = dynamic_cast<Response*>(xmlObject.get());
112     if (!response)
113         throw BindingException("Decoded message was not a SAML 1.x Response.");
114
115     SchemaValidators.validate(response);
116     
117     pair<bool,int> minor = response->getMinorVersion();
118     extractMessageDetails(
119         *response,
120         genericRequest,
121         (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM,
122         policy
123         );
124
125     // Run through the policy.
126     policy.evaluate(*response,&genericRequest);
127     
128     // Check recipient URL.
129     auto_ptr_char recipient(response->getRecipient());
130     const char* recipient2 = httpRequest->getRequestURL();
131     const char* delim = strchr(recipient2, '?');
132     if (!recipient.get() || !*(recipient.get())) {
133         log.error("response missing Recipient attribute");
134         throw BindingException("SAML response did not contain Recipient attribute identifying intended destination.");
135     }
136     else if ((delim && strncmp(recipient.get(), recipient2, delim - recipient2)) || (!delim && strcmp(recipient.get(),recipient2))) {
137         log.error("POST targeted at (%s), but delivered to (%s)", recipient.get(), recipient2);
138         throw BindingException("SAML message delivered with POST to incorrect server URL.");
139     }
140     
141     return xmlObject.release();
142 }