Moved ReplayCache into xmltooling
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTDecoder.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  * SAML1POSTDecoder.cpp
19  * 
20  * SAML 1.x POST binding/profile message decoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "saml1/binding/SAML1POSTDecoder.h"
26 #include "saml2/metadata/Metadata.h"
27 #include "saml2/metadata/MetadataProvider.h"
28 #include "security/X509TrustEngine.h"
29
30 #include <log4cpp/Category.hh>
31 #include <xercesc/util/Base64.hpp>
32 #include <xmltooling/util/NDC.h>
33 #include <xmltooling/util/ReplayCache.h>
34
35 using namespace opensaml::saml2md;
36 using namespace opensaml::saml1p;
37 using namespace opensaml::saml1;
38 using namespace opensaml;
39 using namespace xmlsignature;
40 using namespace xmltooling;
41 using namespace log4cpp;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml1p {              
46         MessageDecoder* SAML_DLLLOCAL SAML1POSTDecoderFactory(const DOMElement* const & e)
47         {
48             return new SAML1POSTDecoder(e);
49         }
50     };
51 };
52
53 SAML1POSTDecoder::SAML1POSTDecoder(const DOMElement* e) {}
54
55 SAML1POSTDecoder::~SAML1POSTDecoder() {}
56
57 Response* SAML1POSTDecoder::decode(
58     string& relayState,
59     const RoleDescriptor*& issuer,
60     bool& issuerTrusted,
61     const HTTPRequest& httpRequest,
62     const MetadataProvider* metadataProvider,
63     const QName* role,
64     const opensaml::TrustEngine* trustEngine
65     ) const
66 {
67 #ifdef _DEBUG
68     xmltooling::NDC ndc("decode");
69 #endif
70     Category& log = Category::getInstance(SAML_LOGCAT".MessageDecoder.SAML1POST");
71
72     log.debug("validating input");
73     if (strcmp(httpRequest.getMethod(),"POST"))
74         return NULL;
75     const char* samlResponse = httpRequest.getParameter("SAMLResponse");
76     const char* TARGET = httpRequest.getParameter("TARGET");
77     if (!samlResponse || !TARGET)
78         return NULL;
79     relayState = TARGET;
80
81     // Decode the base64 into SAML.
82     unsigned int x;
83     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(samlResponse),&x);
84     if (!decoded)
85         throw BindingException("Unable to decode base64 in POST profile response.");
86     log.debug("decoded SAML response:\n%s", decoded);
87     istringstream is(reinterpret_cast<char*>(decoded));
88     XMLString::release(&decoded);
89     
90     // Parse and bind the document into an XMLObject.
91     DOMDocument* doc = (m_validate ? XMLToolingConfig::getConfig().getValidatingParser()
92         : XMLToolingConfig::getConfig().getParser()).parse(is); 
93     XercesJanitor<DOMDocument> janitor(doc);
94     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
95     janitor.release();
96
97     Response* response = dynamic_cast<Response*>(xmlObject.get());
98     if (!response)
99         throw BindingException("Decoded message was not a SAML 1.x Response.");
100
101     const EntityDescriptor* provider=NULL;
102     try {
103         if (!m_validate)
104             SchemaValidators.validate(xmlObject.get());
105         
106         // Check recipient URL.
107         auto_ptr_char recipient(response->getRecipient());
108         const char* recipient2 = httpRequest.getRequestURL();
109         if (!recipient.get() || !*(recipient.get())) {
110             log.error("response missing Recipient attribute");
111             throw BindingException("SAML response did not contain Recipient attribute identifying intended destination.");
112         }
113         else if (!recipient2 || !*recipient2 || strcmp(recipient.get(),recipient2)) {
114             log.error("POST targeted at (%s), but delivered to (%s)", recipient.get(), recipient2 ? recipient2 : "none");
115             throw BindingException("SAML message delivered with POST to incorrect server URL.");
116         }
117         
118         // Check freshness.
119         time_t now = time(NULL);
120         if (response->getIssueInstant()->getEpoch() < now-(2*XMLToolingConfig::getConfig().clock_skew_secs))
121             throw BindingException("Detected expired POST profile response.");
122         
123         // Check replay.
124         ReplayCache* replayCache = XMLToolingConfig::getConfig().getReplayCache();
125         if (replayCache) {
126             auto_ptr_char id(response->getResponseID());
127             if (!replayCache->check("SAML1POST", id.get(), response->getIssueInstant()->getEpoch() + (2*XMLToolingConfig::getConfig().clock_skew_secs))) {
128                 log.error("replay detected of response ID (%s)", id.get());
129                 throw BindingException("Rejecting replayed response ID ($1).", params(1,id.get()));
130             }
131         }
132         else
133             log.warn("replay cache was not provided, this is a serious security risk!");
134         
135         /* For SAML 1, the issuer can only be established from any assertions in the message.
136          * Generally, errors aren't delivered like this, so there should be one.
137          * The Issuer attribute is matched against metadata, and then trust checking can be
138          * applied.
139          */
140         issuer = NULL;
141         issuerTrusted = false;
142         log.debug("attempting to establish issuer and integrity of message...");
143         const vector<Assertion*>& assertions=const_cast<const Response*>(response)->getAssertions();
144         if (!assertions.empty()) {
145             log.debug("searching metadata for assertion issuer...");
146             provider=metadataProvider ? metadataProvider->getEntityDescriptor(assertions.front()->getIssuer()) : NULL;
147             if (provider) {
148                 log.debug("matched assertion issuer against metadata, searching for applicable role...");
149                 pair<bool,int> minor = response->getMinorVersion();
150                 issuer=provider->getRoleDescriptor(
151                     *role,
152                     (minor.first && minor.second==0) ? SAMLConstants::SAML10_PROTOCOL_ENUM : SAMLConstants::SAML11_PROTOCOL_ENUM
153                     );
154                 if (issuer) {
155                     if (trustEngine && response->getSignature()) {
156                         issuerTrusted = trustEngine->validate(
157                             *(response->getSignature()), *issuer, metadataProvider->getKeyResolver()
158                             );
159                         if (!issuerTrusted) {
160                             log.error("unable to verify signature on message with supplied trust engine");
161                             throw BindingException("Message signature failed verification.");
162                         }
163                     }
164                     else {
165                         log.warn("unable to verify integrity of the message, leaving untrusted");
166                     }
167                 }
168                 else {
169                     log.warn(
170                         "unable to find compatible SAML 1.%d role (%s) in metadata",
171                         (minor.first && minor.second==0) ? 0 : 1,
172                         role->toString().c_str()
173                         );
174                 }
175                 if (log.isDebugEnabled()) {
176                     auto_ptr_char iname(assertions.front()->getIssuer());
177                     log.debug("message from (%s), integrity %sverified", iname.get(), issuerTrusted ? "" : "NOT ");
178                 }
179             }
180             else {
181                 auto_ptr_char temp(assertions.front()->getIssuer());
182                 log.warn("no metadata found, can't establish identity of issuer (%s)", temp.get());
183             }
184         }
185         else {
186             log.warn("no assertions found, can't establish identity of issuer");
187         }
188     }
189     catch (XMLToolingException& ex) {
190         // Check for an Issuer.
191         if (!provider) {
192             const vector<Assertion*>& assertions=const_cast<const Response*>(response)->getAssertions();
193             if (!assertions.empty() || !metadataProvider ||
194                     !(provider=metadataProvider->getEntityDescriptor(assertions.front()->getIssuer(), false))) {
195                 // Just record it.
196                 auto_ptr_char iname(assertions.front()->getIssuer());
197                 if (iname.get())
198                     ex.addProperty("entityID", iname.get());
199                 throw;
200             }
201         }
202         if (!issuer) {
203             pair<bool,int> minor = response->getMinorVersion();
204             issuer=provider->getRoleDescriptor(
205                 *role,
206                 (minor.first && minor.second==0) ? SAMLConstants::SAML10_PROTOCOL_ENUM : SAMLConstants::SAML11_PROTOCOL_ENUM
207                 );
208         }
209         if (issuer) annotateException(&ex,issuer); // throws it
210         annotateException(&ex,provider);  // throws it
211     }
212
213     xmlObject.release();
214     return response;
215 }