First SOAP encoder.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2RedirectDecoder.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  * SAML2RedirectDecoder.cpp
19  * 
20  * SAML 2.0 HTTP Redirect binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/HTTPRequest.h"
26 #include "saml2/binding/SAML2Redirect.h"
27 #include "saml2/binding/SAML2RedirectDecoder.h"
28 #include "saml2/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30 #include "saml2/metadata/MetadataProvider.h"
31
32 #include <log4cpp/Category.hh>
33 #include <xercesc/util/Base64.hpp>
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/validation/ValidatorSuite.h>
36
37 using namespace opensaml::saml2md;
38 using namespace opensaml::saml2p;
39 using namespace opensaml::saml2;
40 using namespace opensaml;
41 using namespace xmlsignature;
42 using namespace xmltooling;
43 using namespace log4cpp;
44 using namespace std;
45
46 namespace opensaml {
47     namespace saml2p {              
48         MessageDecoder* SAML_DLLLOCAL SAML2RedirectDecoderFactory(const DOMElement* const & e)
49         {
50             return new SAML2RedirectDecoder(e);
51         }
52     };
53 };
54
55 SAML2RedirectDecoder::SAML2RedirectDecoder(const DOMElement* e) {}
56
57 XMLObject* SAML2RedirectDecoder::decode(
58     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.SAML2Redirect");
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(),"GET"))
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     state = httpRequest->getParameter("SAMLEncoding");
87     if (state && strcmp(state,samlconstants::SAML20_BINDING_URL_ENCODING_DEFLATE)) {
88         log.warn("SAMLEncoding (%s) was not recognized", state);
89         return NULL;
90     }
91
92     // Decode the compressed message into SAML. First we base64-decode it.
93     unsigned int x;
94     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
95     if (!decoded)
96         throw BindingException("Unable to decode base64 in Redirect binding message.");
97     
98     // Now we have to inflate it.
99     stringstream s;
100     if (inflate((char*)decoded, x, s)==0) {
101         XMLString::release(&decoded);
102         throw BindingException("Unable to inflate Redirect binding message.");
103     }
104     if (log.isDebugEnabled())
105         log.debug("decoded SAML message:\n%s", s.str().c_str());
106     XMLString::release(&decoded);
107     
108     // Parse and bind the document into an XMLObject.
109     DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
110         : XMLToolingConfig::getConfig().getParser()).parse(s);
111     XercesJanitor<DOMDocument> janitor(doc);
112     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
113     janitor.release();
114
115     saml2::RootObject* root = NULL;
116     StatusResponseType* response = NULL;
117     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject.get());
118     if (!request) {
119         response = dynamic_cast<StatusResponseType*>(xmlObject.get());
120         if (!response)
121             throw BindingException("XML content for SAML 2.0 HTTP-POST Decoder must be a SAML 2.0 protocol message.");
122         root = static_cast<saml2::RootObject*>(response);
123     }
124     else {
125         root = static_cast<saml2::RootObject*>(request);
126     }
127     
128     
129     try {
130         if (!m_validate)
131             SchemaValidators.validate(xmlObject.get());
132         
133         // Check destination URL.
134         auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
135         const char* dest2 = httpRequest->getRequestURL();
136         if ((root->getSignature() || httpRequest->getParameter("Signature")) && !dest.get() || !*(dest.get())) {
137             log.error("signed SAML message missing Destination attribute");
138             throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
139         }
140         else if (dest.get() && (!dest2 || !*dest2 || strcmp(dest.get(),dest2))) {
141             log.error("Redirect targeted at (%s), but delivered to (%s)", dest.get(), dest2 ? dest2 : "none");
142             throw BindingException("SAML message delivered with Redirect to incorrect server URL.");
143         }
144
145         // Run through the policy.
146         policy.evaluate(genericRequest, *root);
147     }
148     catch (XMLToolingException& ex) {
149         // This is just to maximize the likelihood of attaching a source to the message for support purposes.
150         if (policy.getIssuerMetadata())
151             annotateException(&ex,policy.getIssuerMetadata()); // throws it
152
153         const Issuer* claimedIssuer = root->getIssuer();
154         if (!claimedIssuer || !claimedIssuer->getName())
155             throw;
156         const EntityDescriptor* provider=NULL;
157         if (!policy.getMetadataProvider() ||
158                 !(provider=policy.getMetadataProvider()->getEntityDescriptor(claimedIssuer->getName(), false))) {
159             // Just record it.
160             auto_ptr_char iname(claimedIssuer->getName());
161             if (iname.get())
162                 ex.addProperty("entityID", iname.get());
163             throw;
164         }
165
166         if (policy.getRole()) {
167             const RoleDescriptor* roledesc=provider->getRoleDescriptor(*(policy.getRole()), samlconstants::SAML20P_NS);
168             if (roledesc) annotateException(&ex,roledesc); // throws it
169         }
170         annotateException(&ex,provider);  // throws it
171     }
172
173     xmlObject.release();
174     return root;
175 }