Revamped binding classes with security policy layer.
[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 "saml2/binding/SAML2Redirect.h"
26 #include "saml2/binding/SAML2RedirectDecoder.h"
27 #include "saml2/core/Protocols.h"
28 #include "saml2/metadata/Metadata.h"
29 #include "saml2/metadata/MetadataProvider.h"
30 #include "security/X509TrustEngine.h"
31
32 #include <log4cpp/Category.hh>
33 #include <xercesc/util/Base64.hpp>
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/util/ReplayCache.h>
36 #include <xmltooling/validation/ValidatorSuite.h>
37
38 using namespace opensaml::saml2md;
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2;
41 using namespace opensaml;
42 using namespace xmlsignature;
43 using namespace xmltooling;
44 using namespace log4cpp;
45 using namespace std;
46
47 namespace opensaml {
48     namespace saml2p {              
49         MessageDecoder* SAML_DLLLOCAL SAML2RedirectDecoderFactory(const DOMElement* const & e)
50         {
51             return new SAML2RedirectDecoder(e);
52         }
53     };
54 };
55
56 SAML2RedirectDecoder::SAML2RedirectDecoder(const DOMElement* e) {}
57
58 SAML2RedirectDecoder::~SAML2RedirectDecoder() {}
59
60 XMLObject* SAML2RedirectDecoder::decode(
61     string& relayState,
62     const RoleDescriptor*& issuer,
63     const XMLCh*& securityMech,
64     const HTTPRequest& httpRequest,
65     const MetadataProvider* metadataProvider,
66     const QName* role,
67     const opensaml::TrustEngine* trustEngine
68     ) const
69 {
70 #ifdef _DEBUG
71     xmltooling::NDC ndc("decode");
72 #endif
73     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML2Redirect");
74
75     log.debug("validating input");
76     if (strcmp(httpRequest.getMethod(),"GET"))
77         return NULL;
78     const char* msg = httpRequest.getParameter("SAMLResponse");
79     if (!msg)
80         msg = httpRequest.getParameter("SAMLRequest");
81     if (!msg)
82         return NULL;
83     const char* state = httpRequest.getParameter("RelayState");
84     if (state)
85         relayState = state;
86     else
87         relayState.erase();
88     state = httpRequest.getParameter("SAMLEncoding");
89     if (state && strcmp(state,samlconstants::SAML20_BINDING_URL_ENCODING_DEFLATE)) {
90         log.warn("SAMLEncoding (%s) was not recognized", state);
91         return NULL;
92     }
93
94     // Decode the compressed message into SAML. First we base64-decode it.
95     unsigned int x;
96     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(msg),&x);
97     if (!decoded)
98         throw BindingException("Unable to decode base64 in Redirect binding message.");
99     
100     // Now we have to inflate it.
101     stringstream str;
102     if (inflate((char*)decoded, x, str)==0) {
103         XMLString::release(&decoded);
104         throw BindingException("Unable to inflate Redirect binding message.");
105     }
106
107     XMLString::release(&decoded);
108     
109     // Parse and bind the document into an XMLObject.
110     DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
111         : XMLToolingConfig::getConfig().getParser()).parse(str);
112     XercesJanitor<DOMDocument> janitor(doc);
113     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
114     janitor.release();
115
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-Redirect Decoder must be a SAML 2.0 protocol message.");
122     }
123     
124     /* For SAML 2, the issuer can be established either from the message, or in some profiles
125      * it's possible to omit it and defer to assertions in a Response.
126      * The Issuer is later matched against metadata, and then trust checking can be applied.
127      */
128     const Issuer* claimedIssuer = request ? request->getIssuer() : response->getIssuer();
129     if (!claimedIssuer) {
130         // Check assertion option. I cannot resist the variable name, for the sake of google.
131         const Response* assbag = dynamic_cast<const Response*>(response);
132         if (assbag) {
133             const vector<Assertion*>& assertions=assbag->getAssertions();
134             if (!assertions.empty())
135                 claimedIssuer = assertions.front()->getIssuer();
136         }
137     }
138
139     const EntityDescriptor* provider=NULL;
140     try {
141         if (!m_validate)
142             SchemaValidators.validate(xmlObject.get());
143         
144         // Check destination URL.
145         auto_ptr_char dest(request ? request->getDestination() : response->getDestination());
146         const char* dest2 = httpRequest.getRequestURL();
147         if (!dest.get() || !*(dest.get())) {
148             log.error("signed SAML message missing Destination attribute");
149             throw BindingException("Signed SAML message missing Destination attribute identifying intended destination.");
150         }
151         else if (dest.get() && (!dest2 || !*dest2 || strcmp(dest.get(),dest2))) {
152             log.error("Redirect targeted at (%s), but delivered to (%s)", dest.get(), dest2 ? dest2 : "none");
153             throw BindingException("SAML message delivered with Redirect to incorrect server URL.");
154         }
155         
156         // Check freshness.
157         time_t now = time(NULL);
158         if ((request ? request->getIssueInstant()->getEpoch() : response->getIssueInstant()->getEpoch())
159                 < now-(2*XMLToolingConfig::getConfig().clock_skew_secs))
160             throw BindingException("Detected expired Redirect binding message.");
161         
162         // Check replay.
163         ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
164         if (replayCache) {
165             auto_ptr_char id(xmlObject->getXMLID());
166             if (!replayCache->check("SAML2Redirect", id.get(), response->getIssueInstant()->getEpoch() + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
167                 log.error("replay detected of message ID (%s)", id.get());
168                 throw BindingException("Rejecting replayed message ID ($1).", params(1,id.get()));
169             }
170         }
171         else
172             log.warn("replay cache was not provided, this is a serious security risk!");
173         
174         issuer = NULL;
175         securityMech = false;
176         log.debug("attempting to establish issuer and integrity of message...");
177         
178         // If we can't identify the issuer, we're done, since we can't lookup or verify anything.
179         if (!claimedIssuer || !claimedIssuer->getName()) {
180             log.warn("unable to establish identity of message issuer");
181             return xmlObject.release();
182         }
183         else if (claimedIssuer->getFormat() && !XMLString::equals(claimedIssuer->getFormat(), NameIDType::ENTITY)) {
184             auto_ptr_char iformat(claimedIssuer->getFormat());
185             log.warn("message issuer was in an unsupported format (%s)", iformat.get());
186             return xmlObject.release();
187         }
188         
189         log.debug("searching metadata for assertion issuer...");
190         provider=metadataProvider ? metadataProvider->getEntityDescriptor(claimedIssuer->getName()) : NULL;
191         if (provider) {
192             log.debug("matched assertion issuer against metadata, searching for applicable role...");
193             issuer=provider->getRoleDescriptor(*role, samlconstants::SAML20P_NS);
194             if (issuer) {
195                 /*
196                 if (trustEngine && signature) {
197                     if (!trustEngine->validate(*signature, *issuer, metadataProvider->getKeyResolver())) {
198                         log.error("unable to verify signature on message with supplied trust engine");
199                         throw BindingException("Message signature failed verification.");
200                     }
201                     else {
202                         securityMech = samlconstants::SAML20P_NS;
203                     }
204                 }
205                 else {
206                     log.warn("unable to authenticate the message, leaving untrusted");
207                 }
208                 */
209             }
210             else {
211                 log.warn("unable to find compatible SAML 2.0 role (%s) in metadata", role->toString().c_str());
212             }
213             if (log.isDebugEnabled()) {
214                 auto_ptr_char iname(provider->getEntityID());
215                 log.debug("message from (%s), integrity %sverified", iname.get(), securityMech ? "" : "NOT ");
216             }
217         }
218         else {
219             auto_ptr_char temp(claimedIssuer->getName());
220             log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
221         }
222     }
223     catch (XMLToolingException& ex) {
224         if (!provider) {
225             if (!claimedIssuer || !claimedIssuer->getName())
226                 throw;
227             if (!metadataProvider || !(provider=metadataProvider->getEntityDescriptor(claimedIssuer->getName(), false))) {
228                 // Just record it.
229                 auto_ptr_char iname(claimedIssuer->getName());
230                 if (iname.get())
231                     ex.addProperty("entityID", iname.get());
232                 throw;
233             }
234         }
235         if (!issuer)
236             issuer=provider->getRoleDescriptor(*role, samlconstants::SAML20P_NS);
237         if (issuer) annotateException(&ex,issuer); // throws it
238         annotateException(&ex,provider);  // throws it
239     }
240
241     return xmlObject.release();
242 }