https://bugs.internet2.edu/jira/browse/SSPCPP-293
[shibboleth/sp.git] / shibsp / handler / impl / SAML1Consumer.cpp
index 1e06560..78cd49a 100644 (file)
@@ -1,6 +1,6 @@
 /*
- *  Copyright 2001-2007 Internet2
- * 
+ *  Copyright 2001-2010 Internet2
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
 
 /**
  * SAML1Consumer.cpp
- * 
- * SAML 1.x assertion consumer service 
+ *
+ * SAML 1.x assertion consumer service.
  */
 
 #include "internal.h"
 #include "handler/AssertionConsumerService.h"
 
 #ifndef SHIBSP_LITE
-# include "exceptions.h"
 # include "Application.h"
 # include "ServiceProvider.h"
 # include "SessionCache.h"
 # include "attribute/resolver/ResolutionContext.h"
+# include <saml/exceptions.h>
+# include <saml/SAMLConfig.h>
+# include <saml/binding/SecurityPolicy.h>
+# include <saml/binding/SecurityPolicyRule.h>
 # include <saml/saml1/core/Assertions.h>
 # include <saml/saml1/core/Protocols.h>
-# include <saml/saml1/profile/BrowserSSOProfileValidator.h>
 # include <saml/saml2/metadata/Metadata.h>
+# include <xmltooling/io/HTTPRequest.h>
+# include <xmltooling/util/DateTime.h>
 using namespace opensaml::saml1;
 using namespace opensaml::saml1p;
 using namespace opensaml;
 using saml2::NameID;
 using saml2::NameIDBuilder;
 using saml2md::EntityDescriptor;
+using saml2md::SPSSODescriptor;
 using saml2md::MetadataException;
 #else
 # include "lite/SAMLConstants.h"
@@ -54,28 +59,44 @@ namespace shibsp {
     #pragma warning( push )
     #pragma warning( disable : 4250 )
 #endif
-    
+
     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
     {
     public:
         SAML1Consumer(const DOMElement* e, const char* appId)
-                : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
+            : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
 #ifndef SHIBSP_LITE
+            m_ssoRule = nullptr;
             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
+            if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
+                m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
 #endif
         }
-        virtual ~SAML1Consumer() {}
-        
-    private:
+        virtual ~SAML1Consumer() {
 #ifndef SHIBSP_LITE
-        string implementProtocol(
+            delete m_ssoRule;
+#endif
+        }
+
+#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:
+        void implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
+            HTTPResponse& httpResponse,
             SecurityPolicy& policy,
-            const PropertySet* settings,
+            const PropertySet*,
             const XMLObject& xmlObject
             ) const;
+
         bool m_post;
+        SecurityPolicyRule* m_ssoRule;
 #endif
     };
 
@@ -87,16 +108,29 @@ namespace shibsp {
     {
         return new SAML1Consumer(p.first, p.second);
     }
-    
+
+#ifndef SHIBSP_LITE
+    class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
+    {
+    public:
+        _rulenamed(const char* name) : m_name(name) {}
+        bool operator()(const SecurityPolicyRule* rule) const {
+            return rule ? !strcmp(m_name, rule->getType()) : false;
+        }
+    private:
+        const char* m_name;
+    };
+#endif
 };
 
 #ifndef SHIBSP_LITE
 
-string SAML1Consumer::implementProtocol(
+void SAML1Consumer::implementProtocol(
     const Application& application,
     const HTTPRequest& httpRequest,
+    HTTPResponse& httpResponse,
     SecurityPolicy& policy,
-    const PropertySet* settings,
+    const PropertySet*,
     const XMLObject& xmlObject
     ) const
 {
@@ -110,15 +144,15 @@ string SAML1Consumer::implementProtocol(
     // 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();
+    bool alreadySecured = policy.isAuthenticated();
 
     const Response* response = dynamic_cast<const Response*>(&xmlObject);
     if (!response)
@@ -128,62 +162,87 @@ 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;
+    const AuthenticationStatement* ssoStatement=nullptr;
     vector<const opensaml::Assertion*> tokens;
 
     // Also track "bad" tokens that we'll cache but not use.
     // This is necessary because there may be valid tokens not aimed at us.
     vector<const opensaml::Assertion*> badtokens;
 
-    // Profile validator.
-    time_t now = time(NULL);
-    BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
-
     // With this flag on, we ignore any unsigned assertions.
-    pair<bool,bool> flag = settings->getBool("signedAssertions");
+    const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
+    pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
 
-    for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
-        // Skip unsigned assertion?
-        if (!(*a)->getSignature() && flag.first && flag.second) {
-            m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
-            badtokens.push_back(*a);
-            continue;
-        }
+    // authnskew allows rejection of SSO if AuthnInstant is too old.
+    const PropertySet* sessionProps = application.getPropertySet("Sessions");
+    pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
 
+    // Saves off error messages potentially helpful for users.
+    string contextualError;
+
+    // Ensure the BrowserSSO rule is in the policy set.
+    if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
+        policy.getRules().push_back(m_ssoRule);
+
+    // Populate recipient as audience.
+    policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
+
+    time_t now = time(nullptr);
+    for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
         try {
+            // Skip unsigned assertion?
+            if (!(*a)->getSignature() && flag.first && flag.second)
+                throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
+
             // 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.evaluate(*(*a));
-            
-            // If no security is in place now, we kick it.
-            if (!alreadySecured && !policy.isSecure()) {
-                m_log.warn("unable to establish security of assertion");
-                badtokens.push_back(*a);
-                continue;
-            }
+            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
+                );
 
-            // Now do profile and core semantic validation to ensure we can use it for SSO.
-            ssoValidator.validateAssertion(*(*a));
+            // Run the policy over the assertion. Handles replay, freshness, and
+            // signature verification, assuming the relevant rules are configured,
+            // along with condition and profile enforcement.
+            policy.evaluate(*(*a), &httpRequest);
+
+            // If no security is in place now, we kick it.
+            if (!alreadySecured && !policy.isAuthenticated())
+                throw SecurityPolicyException("Unable to establish security of incoming assertion.");
 
             // Track it as a valid token.
             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());
+            if (!ssoStatement)
+                contextualError = ex.what();
             badtokens.push_back(*a);
         }
     }
 
-    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,7 +258,6 @@ 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;
@@ -208,7 +266,7 @@ string SAML1Consumer::implementProtocol(
     // To complete processing, we need to extract and resolve attributes and then create the session.
 
     // Normalize the SAML 1.x NameIdentifier...
-    auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
+    auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
     if (n) {
         nameid->setName(n->getName());
         nameid->setFormat(n->getFormat());
@@ -225,7 +283,7 @@ string SAML1Consumer::implementProtocol(
             n,
             nameid.get(),
             ssoStatement->getAuthenticationMethod(),
-            NULL,
+            nullptr,
             &tokens
             )
         );
@@ -238,20 +296,21 @@ string SAML1Consumer::implementProtocol(
     // Now merge in bad tokens for caching.
     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
 
-    return application.getServiceProvider().getSessionCache()->insert(
-        now + lifetime.second,
+    application.getServiceProvider().getSessionCache()->insert(
         application,
-        httpRequest.getRemoteAddr().c_str(),
-        policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
+        httpRequest,
+        httpResponse,
+        now + lifetime.second,
+        entity,
         (!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->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
+        nullptr,
         ssoStatement->getAuthenticationMethod(),
-        NULL,
+        nullptr,
         &tokens,
-        ctx.get() ? &ctx->getResolvedAttributes() : NULL
+        ctx.get() ? &ctx->getResolvedAttributes() : nullptr
         );
 }