Add authnskew property for ForceAuthn enforcement.
[shibboleth/sp.git] / shibsp / handler / impl / SAML2Consumer.cpp
1 /*
2  *  Copyright 2001-2007 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  * SAML2Consumer.cpp
19  * 
20  * SAML 2.0 assertion consumer service 
21  */
22
23 #include "internal.h"
24 #include "handler/AssertionConsumerService.h"
25
26 #ifndef SHIBSP_LITE
27 # include "exceptions.h"
28 # include "Application.h"
29 # include "ServiceProvider.h"
30 # include "SessionCache.h"
31 # include "attribute/resolver/ResolutionContext.h"
32 # include <saml/saml2/core/Protocols.h>
33 # include <saml/saml2/profile/BrowserSSOProfileValidator.h>
34 # include <saml/saml2/metadata/Metadata.h>
35 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
36 using namespace opensaml::saml2;
37 using namespace opensaml::saml2p;
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
40 # ifndef min
41 #  define min(a,b)            (((a) < (b)) ? (a) : (b))
42 # endif
43 #endif
44
45 using namespace shibsp;
46 using namespace xmltooling;
47 using namespace std;
48
49 namespace shibsp {
50
51 #if defined (_MSC_VER)
52     #pragma warning( push )
53     #pragma warning( disable : 4250 )
54 #endif
55     
56     class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
57     {
58     public:
59         SAML2Consumer(const DOMElement* e, const char* appId)
60             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
61         }
62         virtual ~SAML2Consumer() {}
63         
64 #ifndef SHIBSP_LITE
65         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
66             AssertionConsumerService::generateMetadata(role, handlerURL);
67             role.addSupport(samlconstants::SAML20P_NS);
68         }
69
70     private:
71         string implementProtocol(
72             const Application& application,
73             const HTTPRequest& httpRequest,
74             SecurityPolicy& policy,
75             const PropertySet* settings,
76             const XMLObject& xmlObject
77             ) const;
78 #endif
79     };
80
81 #if defined (_MSC_VER)
82     #pragma warning( pop )
83 #endif
84
85     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
86     {
87         return new SAML2Consumer(p.first, p.second);
88     }
89     
90 };
91
92 #ifndef SHIBSP_LITE
93
94 string SAML2Consumer::implementProtocol(
95     const Application& application,
96     const HTTPRequest& httpRequest,
97     SecurityPolicy& policy,
98     const PropertySet* settings,
99     const XMLObject& xmlObject
100     ) const
101 {
102     // Implementation of SAML 2.0 SSO profile(s).
103     m_log.debug("processing message against SAML 2.0 SSO profile");
104
105     // Remember whether we already established trust.
106     // None of the SAML 2 bindings require security at the protocol layer.
107     bool alreadySecured = policy.isAuthenticated();
108
109     // Check for errors...this will throw if it's not a successful message.
110     checkError(&xmlObject);
111
112     const Response* response = dynamic_cast<const Response*>(&xmlObject);
113     if (!response)
114         throw FatalProfileException("Incoming message was not a samlp:Response.");
115
116     const vector<saml2::Assertion*>& assertions = response->getAssertions();
117     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
118     if (assertions.empty() && encassertions.empty())
119         throw FatalProfileException("Incoming message contained no SAML assertions.");
120
121     // Maintain list of "legit" tokens to feed to SP subsystems.
122     const Subject* ssoSubject=NULL;
123     const AuthnStatement* ssoStatement=NULL;
124     vector<const opensaml::Assertion*> tokens;
125
126     // Also track "bad" tokens that we'll cache but not use.
127     // This is necessary because there may be valid tokens not aimed at us.
128     vector<const opensaml::Assertion*> badtokens;
129
130     // And also track "owned" tokens that we decrypt here.
131     vector<saml2::Assertion*> ownedtokens;
132
133     // Profile validator.
134     time_t now = time(NULL);
135     string dest = httpRequest.getRequestURL();
136     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
137
138     // With this flag on, we ignore any unsigned assertions.
139     pair<bool,bool> flag = settings->getBool("signedAssertions");
140
141     // authnskew allows rejection of SSO if AuthnInstant is too old.
142     const PropertySet* sessionProps = application.getPropertySet("Sessions");
143     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("authnskew") : pair<bool,unsigned int>(false,0);
144
145     // Saves off error messages potentially helpful for users.
146     string contextualError;
147
148     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
149         // Skip unsigned assertion?
150         if (!(*a)->getSignature() && flag.first && flag.second) {
151             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
152             badtokens.push_back(*a);
153             continue;
154         }
155
156         try {
157             // We clear the security flag, so we can tell whether the token was secured on its own.
158             policy.setAuthenticated(false);
159             policy.reset(true);
160
161             // Extract message bits and re-verify Issuer information.
162             extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
163
164             // Run the policy over the assertion. Handles replay, freshness, and
165             // signature verification, assuming the relevant rules are configured.
166             policy.evaluate(*(*a));
167             
168             // If no security is in place now, we kick it.
169             if (!alreadySecured && !policy.isAuthenticated()) {
170                 m_log.warn("unable to establish security of assertion");
171                 badtokens.push_back(*a);
172                 continue;
173             }
174
175             // Now do profile and core semantic validation to ensure we can use it for SSO.
176             ssoValidator.validateAssertion(*(*a));
177
178             // Address checking.
179             try {
180                 if (ssoValidator.getAddress())
181                     checkAddress(application, httpRequest, ssoValidator.getAddress());
182             }
183             catch (exception& ex) {
184                 // We save off the message if there's no SSO statement yet.
185                 if (!ssoStatement)
186                     contextualError = ex.what();
187                 throw;
188             }
189
190             // Track it as a valid token.
191             tokens.push_back(*a);
192
193             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
194             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
195             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
196                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
197                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
198                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
199                     ssoStatement = *s;
200             }
201
202             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
203             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
204                 ssoSubject = (*a)->getSubject();
205         }
206         catch (exception& ex) {
207             m_log.warn("detected a problem with assertion: %s", ex.what());
208             badtokens.push_back(*a);
209         }
210     }
211
212     // In case we need decryption...
213     CredentialResolver* cr=application.getCredentialResolver();
214     if (!cr && !encassertions.empty())
215         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
216
217     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
218         // Attempt to decrypt it.
219         saml2::Assertion* decrypted=NULL;
220         try {
221             Locker credlocker(cr);
222             auto_ptr<MetadataCredentialCriteria> mcc(
223                 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
224                 );
225             auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
226             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
227             if (decrypted) {
228                 wrapper.release();
229                 ownedtokens.push_back(decrypted);
230             }
231         }
232         catch (exception& ex) {
233             m_log.error(ex.what());
234         }
235         if (!decrypted)
236             continue;
237
238         // Skip unsigned assertion?
239         if (!decrypted->getSignature() && flag.first && flag.second) {
240             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
241             badtokens.push_back(decrypted);
242             continue;
243         }
244
245         try {
246             // We clear the security flag, so we can tell whether the token was secured on its own.
247             policy.setAuthenticated(false);
248             policy.reset(true);
249
250             // Extract message bits and re-verify Issuer information.
251             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
252
253             // Run the policy over the assertion. Handles replay, freshness, and
254             // signature verification, assuming the relevant rules are configured.
255             // We have to marshall the object first to ensure signatures can be checked.
256             if (!decrypted->getDOM())
257                 decrypted->marshall();
258             policy.evaluate(*decrypted);
259             
260             // If no security is in place now, we kick it.
261             if (!alreadySecured && !policy.isAuthenticated()) {
262                 m_log.warn("unable to establish security of assertion");
263                 badtokens.push_back(decrypted);
264                 continue;
265             }
266
267             // Now do profile and core semantic validation to ensure we can use it for SSO.
268             ssoValidator.validateAssertion(*decrypted);
269
270             // Address checking.
271             try {
272                 if (ssoValidator.getAddress())
273                     checkAddress(application, httpRequest, ssoValidator.getAddress());
274             }
275             catch (exception& ex) {
276                 // We save off the message if there's no SSO statement yet.
277                 if (!ssoStatement)
278                     contextualError = ex.what();
279                 throw;
280             }
281
282             // Track it as a valid token.
283             tokens.push_back(decrypted);
284
285             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
286             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
287             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
288                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
289                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
290                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
291                     ssoStatement = *s;
292             }
293
294             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
295             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
296                 ssoSubject = decrypted->getSubject();
297         }
298         catch (exception& ex) {
299             m_log.warn("detected a problem with assertion: %s", ex.what());
300             badtokens.push_back(decrypted);
301         }
302     }
303
304     if (!ssoStatement) {
305         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
306         if (contextualError.empty())
307             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
308         throw FatalProfileException(contextualError.c_str());
309     }
310
311     // May need to decrypt NameID.
312     bool ownedName = false;
313     NameID* ssoName = ssoSubject->getNameID();
314     if (!ssoName) {
315         EncryptedID* encname = ssoSubject->getEncryptedID();
316         if (encname) {
317             if (!cr)
318                 m_log.warn("found encrypted NameID, but no decryption credential was available");
319             else {
320                 Locker credlocker(cr);
321                 auto_ptr<MetadataCredentialCriteria> mcc(
322                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
323                     );
324                 try {
325                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
326                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
327                     if (ssoName) {
328                         ownedName = true;
329                         decryptedID.release();
330                     }
331                 }
332                 catch (exception& ex) {
333                     m_log.error(ex.what());
334                 }
335             }
336         }
337     }
338
339     m_log.debug("SSO profile processing completed successfully");
340
341     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
342     // To complete processing, we need to extract and resolve attributes and then create the session.
343
344     // Now we have to extract the authentication details for session setup.
345
346     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
347     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
348     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
349     if (!lifetime.first || lifetime.second == 0)
350         lifetime.second = 28800;
351     if (sessionExp == 0)
352         sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
353     else
354         sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
355
356     const AuthnContext* authnContext = ssoStatement->getAuthnContext();
357
358     try {
359         // The context will handle deleting attributes and new tokens.
360         auto_ptr<ResolutionContext> ctx(
361             resolveAttributes(
362                 application,
363                 policy.getIssuerMetadata(),
364                 samlconstants::SAML20P_NS,
365                 NULL,
366                 ssoName,
367                 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
368                 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
369                 &tokens
370                 )
371             );
372
373         if (ctx.get()) {
374             // Copy over any new tokens, but leave them in the context for cleanup.
375             tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
376         }
377
378         // Now merge in bad tokens for caching.
379         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
380
381         string key = application.getServiceProvider().getSessionCache()->insert(
382             sessionExp,
383             application,
384             httpRequest.getRemoteAddr().c_str(),
385             policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
386             samlconstants::SAML20P_NS,
387             ssoName,
388             ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
389             ssoStatement->getSessionIndex(),
390             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
391             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
392             &tokens,
393             ctx.get() ? &ctx->getResolvedAttributes() : NULL
394             );
395
396         if (ownedName)
397             delete ssoName;
398         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
399         return key;
400     }
401     catch (exception&) {
402         if (ownedName)
403             delete ssoName;
404         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
405         throw;
406     }
407 }
408
409 #endif