Add authnskew property for ForceAuthn enforcement.
[shibboleth/sp.git] / shibsp / handler / impl / SAML1Consumer.cpp
index a4e5303..7ad7355 100644 (file)
 # include "Application.h"
 # include "ServiceProvider.h"
 # include "SessionCache.h"
-# include "attribute/Attribute.h"
-# include "attribute/filtering/AttributeFilter.h"
-# include "attribute/filtering/BasicFilteringContext.h"
-# include "attribute/resolver/AttributeExtractor.h"
 # include "attribute/resolver/ResolutionContext.h"
 # include <saml/saml1/core/Assertions.h>
 # include <saml/saml1/core/Protocols.h>
@@ -43,6 +39,8 @@ using namespace opensaml;
 using saml2::NameID;
 using saml2::NameIDBuilder;
 using saml2md::EntityDescriptor;
+using saml2md::SPSSODescriptor;
+using saml2md::MetadataException;
 #else
 # include "lite/SAMLConstants.h"
 #endif
@@ -69,8 +67,14 @@ namespace shibsp {
         }
         virtual ~SAML1Consumer() {}
         
-    private:
 #ifndef SHIBSP_LITE
+        void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+            AssertionConsumerService::generateMetadata(role, handlerURL);
+            role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
+            role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
+        }
+
+    private:
         string implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
@@ -106,19 +110,22 @@ string SAML1Consumer::implementProtocol(
     // Implementation of SAML 1.x SSO profile(s).
     m_log.debug("processing message against SAML 1.x SSO profile");
 
+    // Check for errors...this will throw if it's not a successful message.
+    checkError(&xmlObject);
+
     // With the binding aspects now moved out to the MessageDecoder,
     // the focus here is on the assertion content. For SAML 1.x POST,
     // all the security comes from the protocol layer, and signing
     // the assertion isn't sufficient. So we can check the policy
-    // object now and bail if it's not a secure message.
-    if (m_post && !policy.isSecure())
+    // object now and bail if it's not a secured message.
+    if (m_post && !policy.isAuthenticated()) {
+        if (policy.getIssuer() && !policy.getIssuerMetadata())
+            throw MetadataException("Security of SAML 1.x SSO POST response not established.");
         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
+    }
         
     // Remember whether we already established trust.
-    bool alreadySecured = policy.isSecure();
-
-    // Check for errors...this will throw if it's not a successful message.
-    checkError(&xmlObject);
+    bool alreadySecured = policy.isAuthenticated();
 
     const Response* response = dynamic_cast<const Response*>(&xmlObject);
     if (!response)
@@ -128,6 +135,8 @@ string SAML1Consumer::implementProtocol(
     if (assertions.empty())
         throw FatalProfileException("Incoming message contained no SAML assertions.");
 
+    pair<bool,int> minor = response->getMinorVersion();
+
     // Maintain list of "legit" tokens to feed to SP subsystems.
     const AuthenticationStatement* ssoStatement=NULL;
     vector<const opensaml::Assertion*> tokens;
@@ -143,6 +152,13 @@ string SAML1Consumer::implementProtocol(
     // With this flag on, we ignore any unsigned assertions.
     pair<bool,bool> flag = settings->getBool("signedAssertions");
 
+    // authnskew allows rejection of SSO if AuthnInstant is too old.
+    const PropertySet* sessionProps = application.getPropertySet("Sessions");
+    pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("authnskew") : pair<bool,unsigned int>(false,0);
+
+    // Saves off error messages potentially helpful for users.
+    string contextualError;
+
     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
         // Skip unsigned assertion?
         if (!(*a)->getSignature() && flag.first && flag.second) {
@@ -153,14 +169,20 @@ string SAML1Consumer::implementProtocol(
 
         try {
             // We clear the security flag, so we can tell whether the token was secured on its own.
-            policy.setSecure(false);
-            
-            // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
-            // and signature verification, assuming the relevant rules are configured.
+            policy.setAuthenticated(false);
+            policy.reset(true);
+
+            // Extract message bits and re-verify Issuer information.
+            extractMessageDetails(
+                *(*a), (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
+                );
+
+            // Run the policy over the assertion. Handles replay, freshness, and
+            // signature verification, assuming the relevant rules are configured.
             policy.evaluate(*(*a));
             
             // If no security is in place now, we kick it.
-            if (!alreadySecured && !policy.isSecure()) {
+            if (!alreadySecured && !policy.isAuthenticated()) {
                 m_log.warn("unable to establish security of assertion");
                 badtokens.push_back(*a);
                 continue;
@@ -173,8 +195,16 @@ string SAML1Consumer::implementProtocol(
             tokens.push_back(*a);
 
             // Save off the first valid SSO statement.
-            if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
-                ssoStatement = (*a)->getAuthenticationStatements().front();
+            const vector<AuthenticationStatement*>& statements = const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
+            for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
+                if (authnskew.first && authnskew.second &&
+                    (*s)->getAuthenticationInstant() && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second))
+                    contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
+                else if (!ssoStatement) {
+                    ssoStatement = *s;
+                    break;
+                }
+            }
         }
         catch (exception& ex) {
             m_log.warn("detected a problem with assertion: %s", ex.what());
@@ -182,8 +212,11 @@ string SAML1Consumer::implementProtocol(
         }
     }
 
-    if (!ssoStatement)
-        throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
+    if (!ssoStatement) {
+        if (contextualError.empty())
+            throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
+        throw FatalProfileException(contextualError.c_str());
+    }
 
     // Address checking.
     SubjectLocality* locality = ssoStatement->getSubjectLocality();
@@ -199,50 +232,12 @@ string SAML1Consumer::implementProtocol(
     // Now we have to extract the authentication details for attribute and session setup.
 
     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
-    const PropertySet* sessionProps = application.getPropertySet("Sessions");
     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
     if (!lifetime.first || lifetime.second == 0)
         lifetime.second = 28800;
 
     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
     // To complete processing, we need to extract and resolve attributes and then create the session.
-    vector<Attribute*> resolvedAttributes;
-    AttributeExtractor* extractor = application.getAttributeExtractor();
-    if (extractor) {
-        m_log.debug("extracting pushed attributes...");
-        Locker extlocker(extractor);
-        if (n) {
-            try {
-                extractor->extractAttributes(application, policy.getIssuerMetadata(), *n, resolvedAttributes);
-            }
-            catch (exception& ex) {
-                m_log.error("caught exception extracting attributes: %s", ex.what());
-            }
-        }
-        for (vector<const opensaml::Assertion*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
-            try {
-                extractor->extractAttributes(application, policy.getIssuerMetadata(), *(*t), resolvedAttributes);
-            }
-            catch (exception& ex) {
-                m_log.error("caught exception extracting attributes: %s", ex.what());
-            }
-        }
-
-        AttributeFilter* filter = application.getAttributeFilter();
-        if (filter && !resolvedAttributes.empty()) {
-            BasicFilteringContext fc(application, resolvedAttributes, policy.getIssuerMetadata(), ssoStatement->getAuthenticationMethod());
-            Locker filtlocker(filter);
-            try {
-                filter->filterAttributes(fc, resolvedAttributes);
-            }
-            catch (exception& ex) {
-                m_log.error("caught exception filtering attributes: %s", ex.what());
-                m_log.error("dumping extracted attributes due to filtering exception");
-                for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
-                resolvedAttributes.clear();
-            }
-        }
-    }
 
     // Normalize the SAML 1.x NameIdentifier...
     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
@@ -252,57 +247,44 @@ string SAML1Consumer::implementProtocol(
         nameid->setNameQualifier(n->getNameQualifier());
     }
 
-    const EntityDescriptor* issuerMetadata =
-        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
+    // The context will handle deleting attributes and new tokens.
     auto_ptr<ResolutionContext> ctx(
         resolveAttributes(
             application,
-            issuerMetadata,
+            policy.getIssuerMetadata(),
             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
+            n,
             nameid.get(),
             ssoStatement->getAuthenticationMethod(),
             NULL,
-            &tokens,
-            &resolvedAttributes
+            &tokens
             )
         );
 
     if (ctx.get()) {
         // Copy over any new tokens, but leave them in the context for cleanup.
         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
-
-        // Copy over new attributes, and transfer ownership.
-        resolvedAttributes.insert(resolvedAttributes.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
-        ctx->getResolvedAttributes().clear();
     }
 
     // Now merge in bad tokens for caching.
     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
 
-    try {
-        string key = application.getServiceProvider().getSessionCache()->insert(
-            now + lifetime.second,
-            application,
-            httpRequest.getRemoteAddr().c_str(),
-            issuerMetadata,
-            (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
-                samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
-            nameid.get(),
-            ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
-            NULL,
-            ssoStatement->getAuthenticationMethod(),
-            NULL,
-            &tokens,
-            &resolvedAttributes
-            );
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
-        return key;
-    }
-    catch (exception&) {
-        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
-        throw;
-    }
+    return application.getServiceProvider().getSessionCache()->insert(
+        now + lifetime.second,
+        application,
+        httpRequest.getRemoteAddr().c_str(),
+        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
+        (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
+            samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
+        nameid.get(),
+        ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
+        NULL,
+        ssoStatement->getAuthenticationMethod(),
+        NULL,
+        &tokens,
+        ctx.get() ? &ctx->getResolvedAttributes() : NULL
+        );
 }
 
 #endif