6c3f32436e7905693aa33fde28bc03c978d5308c
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTDecoder.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML1POSTDecoder.cpp
23  * 
24  * SAML 1.x POST binding/profile message decoder.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "binding/SecurityPolicy.h"
30 #include "saml1/binding/SAML1MessageDecoder.h"
31 #include "saml1/core/Assertions.h"
32 #include "saml1/core/Protocols.h"
33 #include "saml2/metadata/Metadata.h"
34 #include "saml2/metadata/MetadataProvider.h"
35
36 #include <xercesc/framework/MemBufInputSource.hpp>
37 #include <xercesc/framework/Wrapper4InputSource.hpp>
38 #include <xercesc/util/Base64.hpp>
39 #include <xmltooling/logging.h>
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/io/HTTPRequest.h>
42 #include <xmltooling/util/NDC.h>
43 #include <xmltooling/util/ParserPool.h>
44 #include <xmltooling/validation/ValidatorSuite.h>
45
46 using namespace opensaml::saml2md;
47 using namespace opensaml::saml1p;
48 using namespace opensaml::saml1;
49 using namespace opensaml;
50 using namespace xmltooling::logging;
51 using namespace xmltooling;
52 using namespace std;
53
54 namespace opensaml {
55     namespace saml1p {              
56         class SAML_DLLLOCAL SAML1POSTDecoder : public SAML1MessageDecoder
57         {
58         public:
59             SAML1POSTDecoder() {}
60             virtual ~SAML1POSTDecoder() {}
61
62             xmltooling::XMLObject* decode(
63                 std::string& relayState,
64                 const GenericRequest& genericRequest,
65                 SecurityPolicy& policy
66                 ) const;
67         };                
68
69         MessageDecoder* SAML_DLLLOCAL SAML1POSTDecoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
70         {
71             return new SAML1POSTDecoder();
72         }
73     };
74 };
75
76 XMLObject* SAML1POSTDecoder::decode(
77     string& relayState,
78     const GenericRequest& genericRequest,
79     SecurityPolicy& policy
80     ) const
81 {
82 #ifdef _DEBUG
83     xmltooling::NDC ndc("decode");
84 #endif
85     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML1POST");
86
87     log.debug("validating input");
88     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
89     if (!httpRequest)
90         throw BindingException("Unable to cast request object to HTTPRequest type.");
91     if (strcmp(httpRequest->getMethod(),"POST"))
92         throw BindingException("Invalid HTTP method ($1).", params(1, httpRequest->getMethod()));
93     const char* samlResponse = httpRequest->getParameter("SAMLResponse");
94     const char* TARGET = httpRequest->getParameter("TARGET");
95     if (!samlResponse || !TARGET)
96         throw BindingException("Request missing SAMLResponse or TARGET form parameters.");
97     relayState = TARGET;
98
99     // Decode the base64 into XML.
100     xsecsize_t x;
101     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(samlResponse),&x);
102     if (!decoded)
103         throw BindingException("Unable to decode base64 in POST profile response.");
104     log.debugStream() << "decoded SAML response:\n" << decoded << logging::eol;
105
106     // Parse and bind the document into an XMLObject.
107     MemBufInputSource src(decoded, x, "SAMLResponse", true);
108     Wrapper4InputSource dsrc(&src, false);
109     DOMDocument* doc = (policy.getValidating() ? XMLToolingConfig::getConfig().getValidatingParser()
110         : XMLToolingConfig::getConfig().getParser()).parse(dsrc); 
111     XercesJanitor<DOMDocument> janitor(doc);
112     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
113     janitor.release();
114
115     Response* response = dynamic_cast<Response*>(xmlObject.get());
116     if (!response)
117         throw BindingException("Decoded message was not a SAML 1.x Response.");
118
119     SchemaValidators.validate(response);
120     
121     pair<bool,int> minor = response->getMinorVersion();
122     extractMessageDetails(
123         *response,
124         genericRequest,
125         (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM,
126         policy
127         );
128
129     // Run through the policy.
130     policy.evaluate(*response,&genericRequest);
131     
132     // Check recipient URL.
133     auto_ptr_char recipient(response->getRecipient());
134     const char* recipient2 = httpRequest->getRequestURL();
135     const char* delim = strchr(recipient2, '?');
136     if (!recipient.get() || !*(recipient.get())) {
137         log.error("response missing Recipient attribute");
138         throw BindingException("SAML response did not contain Recipient attribute identifying intended destination.");
139     }
140     else if ((delim && strncmp(recipient.get(), recipient2, delim - recipient2)) || (!delim && strcmp(recipient.get(),recipient2))) {
141         log.error("POST targeted at (%s), but delivered to (%s)", recipient.get(), recipient2);
142         throw BindingException("SAML message delivered with POST to incorrect server URL.");
143     }
144     
145     return xmlObject.release();
146 }