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