f216a8d2c099d85500c7ef930be7fec08c70674a
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTDecoder.cpp
1 /*
2  *  Copyright 2001-2006 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/HTTPRequest.h"
26 #include "saml2/binding/SAML2POSTDecoder.h"
27 #include "saml2/core/Protocols.h"
28 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataProvider.h"
30
31 #include <log4cpp/Category.hh>
32 #include <xercesc/util/Base64.hpp>
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;
41 using namespace log4cpp;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml2p {              
46         MessageDecoder* SAML_DLLLOCAL SAML2POSTDecoderFactory(const DOMElement* const & e)
47         {
48             return new SAML2POSTDecoder(e);
49         }
50     };
51 };
52
53 SAML2POSTDecoder::SAML2POSTDecoder(const DOMElement* e) {}
54
55 SAML2POSTDecoder::~SAML2POSTDecoder() {}
56
57 saml2::RootObject* SAML2POSTDecoder::decode(
58     std::string& relayState,
59     const GenericRequest& genericRequest,
60     SecurityPolicy& policy
61     ) const
62 {
63 #ifdef _DEBUG
64     xmltooling::NDC ndc("decode");
65 #endif
66     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2POST");
67
68     log.debug("validating input");
69     const HTTPRequest* httpRequest=dynamic_cast<const HTTPRequest*>(&genericRequest);
70     if (!httpRequest) {
71         log.error("unable to cast request to HTTPRequest type");
72         return NULL;
73     }
74     if (strcmp(httpRequest->getMethod(),"POST"))
75         return NULL;
76     const char* msg = httpRequest->getParameter("SAMLResponse");
77     if (!msg)
78         msg = httpRequest->getParameter("SAMLRequest");
79     if (!msg)
80         return NULL;
81     const char* state = httpRequest->getParameter("RelayState");
82     if (state)
83         relayState = state;
84     else
85         relayState.erase();
86
87     // Decode the base64 into SAML.
88     unsigned int x;
89     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
90     if (!decoded)
91         throw BindingException("Unable to decode base64 in POST binding message.");
92     log.debug("decoded SAML message:\n%s", decoded);
93     istringstream is(reinterpret_cast<char*>(decoded));
94     XMLString::release(&decoded);
95     
96     // Parse and bind the document into an XMLObject.
97     DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
98         : XMLToolingConfig::getConfig().getParser()).parse(is); 
99     XercesJanitor<DOMDocument> janitor(doc);
100     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
101     janitor.release();
102
103     saml2::RootObject* root = NULL;
104     StatusResponseType* response = NULL;
105     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
106     if (!request) {
107         response = dynamic_cast<StatusResponseType*>(xmlObject.get());
108         if (!response)
109             throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
110         root = static_cast<saml2::RootObject*>(response);
111     }
112     else {
113         root = static_cast<saml2::RootObject*>(request);
114     }
115     
116     try {
117         if (!m_validate)
118             SchemaValidators.validate(xmlObject.get());
119         
120         // Check destination URL.
121         auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
122         const char* dest2 = httpRequest->getRequestURL();
123         if ((root->getSignature() || httpRequest->getParameter("Signature")) && !dest.get() || !*(dest.get())) {
124             log.error("signed SAML message missing Destination attribute");
125             throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
126         }
127         else if (dest.get() && (!dest2 || !*dest2 || strcmp(dest.get(),dest2))) {
128             log.error("POST targeted at (%s), but delivered to (%s)", dest.get(), dest2 ? dest2 : "none");
129             throw BindingException("SAML message delivered with POST to incorrect server URL.");
130         }
131         
132         // Run through the policy.
133         policy.evaluate(genericRequest, *root);
134     }
135     catch (XMLToolingException& ex) {
136         // This is just to maximize the likelihood of attaching a source to the message for support purposes.
137         if (policy.getIssuerMetadata())
138             annotateException(&ex,policy.getIssuerMetadata()); // throws it
139
140         const Issuer* claimedIssuer = root->getIssuer();
141         if (!claimedIssuer) {
142             // Check for assertions.
143             const Response* assbag = dynamic_cast<Response*>(response);
144             if (assbag) {
145                 const vector<Assertion*>& assertions=assbag->getAssertions();
146                 if (!assertions.empty())
147                     claimedIssuer = assertions.front()->getIssuer();
148             }
149         }
150     
151         if (!claimedIssuer || !claimedIssuer->getName())
152             throw;
153         const EntityDescriptor* provider=NULL;
154         if (!policy.getMetadataProvider() ||
155                 !(provider=policy.getMetadataProvider()->getEntityDescriptor(claimedIssuer->getName(), false))) {
156             // Just record it.
157             auto_ptr_char iname(claimedIssuer->getName());
158             if (iname.get())
159                 ex.addProperty("entityID", iname.get());
160             throw;
161         }
162
163         if (policy.getRole()) {
164             const RoleDescriptor* roledesc=provider->getRoleDescriptor(*(policy.getRole()), samlconstants::SAML20P_NS);
165             if (roledesc) annotateException(&ex,roledesc); // throws it
166         }
167         annotateException(&ex,provider);  // throws it
168     }
169
170     xmlObject.release();
171     return root;
172 }