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