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