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