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