VS10 solution files, convert from NULL macro to nullptr.
[shibboleth/sp.git] / shibsp / handler / impl / SAML2Consumer.cpp
index 534544d..c22f4a2 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
 
 /**
  * SAML2Consumer.cpp
- * 
- * SAML 2.0 assertion consumer service 
+ *
+ * SAML 2.0 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/SecurityPolicyRule.h>
 # include <saml/saml2/core/Protocols.h>
-# include <saml/saml2/profile/BrowserSSOProfileValidator.h>
 # include <saml/saml2/metadata/Metadata.h>
 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
+# include <saml/saml2/profile/SAML2AssertionPolicy.h>
+# include <xmltooling/XMLToolingConfig.h>
+# include <xmltooling/io/HTTPRequest.h>
+# include <xmltooling/util/DateTime.h>
 using namespace opensaml::saml2;
 using namespace opensaml::saml2p;
 using namespace opensaml::saml2md;
@@ -52,24 +57,41 @@ namespace shibsp {
     #pragma warning( push )
     #pragma warning( disable : 4250 )
 #endif
-    
+
     class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
     {
     public:
         SAML2Consumer(const DOMElement* e, const char* appId)
             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML2")) {
+#ifndef SHIBSP_LITE
+            m_ssoRule = nullptr;
+            if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
+                m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(BEARER_POLICY_RULE, e);
+#endif
         }
-        virtual ~SAML2Consumer() {}
-        
-    private:
+        virtual ~SAML2Consumer() {
 #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::SAML20P_NS);
+        }
+
+    private:
+        void implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
+            HTTPResponse& httpResponse,
             SecurityPolicy& policy,
             const PropertySet* settings,
             const XMLObject& xmlObject
             ) const;
+
+        SecurityPolicyRule* m_ssoRule;
 #endif
     };
 
@@ -81,14 +103,27 @@ namespace shibsp {
     {
         return new SAML2Consumer(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 SAML2Consumer::implementProtocol(
+void SAML2Consumer::implementProtocol(
     const Application& application,
     const HTTPRequest& httpRequest,
+    HTTPResponse& httpResponse,
     SecurityPolicy& policy,
     const PropertySet* settings,
     const XMLObject& xmlObject
@@ -99,10 +134,10 @@ string SAML2Consumer::implementProtocol(
 
     // Remember whether we already established trust.
     // None of the SAML 2 bindings require security at the protocol layer.
-    bool alreadySecured = policy.isSecure();
+    bool alreadySecured = policy.isAuthenticated();
 
     // Check for errors...this will throw if it's not a successful message.
-    checkError(&xmlObject);
+    checkError(&xmlObject, policy.getIssuerMetadata());
 
     const Response* response = dynamic_cast<const Response*>(&xmlObject);
     if (!response)
@@ -114,8 +149,8 @@ string SAML2Consumer::implementProtocol(
         throw FatalProfileException("Incoming message contained no SAML assertions.");
 
     // Maintain list of "legit" tokens to feed to SP subsystems.
-    const Subject* ssoSubject=NULL;
-    const AuthnStatement* ssoStatement=NULL;
+    const Subject* ssoSubject=nullptr;
+    const AuthnStatement* ssoStatement=nullptr;
     vector<const opensaml::Assertion*> tokens;
 
     // Also track "bad" tokens that we'll cache but not use.
@@ -125,53 +160,66 @@ string SAML2Consumer::implementProtocol(
     // And also track "owned" tokens that we decrypt here.
     vector<saml2::Assertion*> ownedtokens;
 
-    // Profile validator.
-    time_t now = time(NULL);
-    string dest = httpRequest.getRequestURL();
-    BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
-
     // With this flag on, we ignore any unsigned assertions.
-    pair<bool,bool> flag = settings->getBool("signedAssertions");
+    const EntityDescriptor* entity = nullptr;
+    pair<bool,bool> flag = make_pair(false,false);
+    if (alreadySecured && policy.getIssuerMetadata()) {
+        entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
+        flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
+    }
 
-    // Saves off IP-mismatch error message because it's potentially helpful for users.
-    string addressMismatch;
+    // 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);
 
-    for (vector<saml2::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;
-        }
+    // Saves off error messages potentially helpful for users.
+    string contextualError;
+
+    // Ensure the Bearer rule is in the policy set.
+    if (find_if(policy.getRules(), _rulenamed(BEARER_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<saml2::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));
-            
+            policy.setAuthenticated(false);
+            policy.reset(true);
+
+            // Extract message bits and re-verify Issuer information.
+            extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
+
+            // 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.isSecure()) {
-                m_log.warn("unable to establish security of assertion");
-                badtokens.push_back(*a);
-                continue;
+            if (!alreadySecured && !policy.isAuthenticated())
+                throw SecurityPolicyException("Unable to establish security of incoming assertion.");
+
+            // If we hadn't established Issuer yet, redo the signedAssertions check.
+            if (!entity && policy.getIssuerMetadata()) {
+                entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
+                flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
+                if (!(*a)->getSignature() && flag.first && flag.second)
+                    throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
             }
 
-            // Now do profile and core semantic validation to ensure we can use it for SSO.
-            ssoValidator.validateAssertion(*(*a));
-
             // Address checking.
-            try {
-                if (ssoValidator.getAddress())
-                    checkAddress(application, httpRequest, ssoValidator.getAddress());
-            }
-            catch (exception& ex) {
-                // We save off the message if there's no SSO statement yet.
-                if (!ssoStatement)
-                    addressMismatch = ex.what();
-                throw;
+            SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
+                dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
+                );
+            if (subcondata && subcondata->getAddress()) {
+                auto_ptr_char boundip(subcondata->getAddress());
+                checkAddress(application, httpRequest, boundip.get());
             }
 
             // Track it as a valid token.
@@ -180,7 +228,9 @@ string SAML2Consumer::implementProtocol(
             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
-                if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
+                if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
+                    contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
+                else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
                     ssoStatement = *s;
             }
 
@@ -190,6 +240,8 @@ string SAML2Consumer::implementProtocol(
         }
         catch (exception& ex) {
             m_log.warn("detected a problem with assertion: %s", ex.what());
+            if (!ssoStatement)
+                contextualError = ex.what();
             badtokens.push_back(*a);
         }
     }
@@ -201,17 +253,19 @@ string SAML2Consumer::implementProtocol(
 
     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
         // Attempt to decrypt it.
-        saml2::Assertion* decrypted=NULL;
+        saml2::Assertion* decrypted=nullptr;
         try {
             Locker credlocker(cr);
             auto_ptr<MetadataCredentialCriteria> mcc(
-                policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
+                policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
                 );
-            auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
+            auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
             if (decrypted) {
                 wrapper.release();
                 ownedtokens.push_back(decrypted);
+                if (m_log.isDebugEnabled())
+                    m_log.debugStream() << "decrypted Assertion: " << *decrypted << logging::eol;
             }
         }
         catch (exception& ex) {
@@ -220,42 +274,41 @@ string SAML2Consumer::implementProtocol(
         if (!decrypted)
             continue;
 
-        // Skip unsigned assertion?
-        if (!decrypted->getSignature() && flag.first && flag.second) {
-            m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
-            badtokens.push_back(decrypted);
-            continue;
-        }
-
         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(*decrypted, samlconstants::SAML20P_NS, policy);
+
+            // Run the policy over the assertion. Handles replay, freshness, and
+            // signature verification, assuming the relevant rules are configured,
+            // along with condition and profile enforcement.
             // We have to marshall the object first to ensure signatures can be checked.
-            policy.evaluate(*decrypted);
-            
+            if (!decrypted->getDOM())
+                decrypted->marshall();
+            policy.evaluate(*decrypted, &httpRequest);
+
             // 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(decrypted);
-                continue;
+            if (!alreadySecured && !policy.isAuthenticated())
+                throw SecurityPolicyException("Unable to establish security of incoming assertion.");
+
+            // If we hadn't established Issuer yet, redo the signedAssertions check.
+            if (!entity && policy.getIssuerMetadata()) {
+                entity = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
+                flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
+                if (!decrypted->getSignature() && flag.first && flag.second)
+                    throw SecurityPolicyException("The decrypted assertion was unsigned, violating local security policy.");
             }
 
-            // Now do profile and core semantic validation to ensure we can use it for SSO.
-            ssoValidator.validateAssertion(*decrypted);
-
             // Address checking.
-            try {
-                if (ssoValidator.getAddress())
-                    checkAddress(application, httpRequest, ssoValidator.getAddress());
-            }
-            catch (exception& ex) {
-                // We save off the message if there's no SSO statement yet.
-                if (!ssoStatement)
-                    addressMismatch = ex.what();
-                throw;
+            SubjectConfirmationData* subcondata = dynamic_cast<SubjectConfirmationData*>(
+                dynamic_cast<SAML2AssertionPolicy&>(policy).getSubjectConfirmation()->getSubjectConfirmationData()
+                );
+            if (subcondata && subcondata->getAddress()) {
+                auto_ptr_char boundip(subcondata->getAddress());
+                checkAddress(application, httpRequest, boundip.get());
             }
 
             // Track it as a valid token.
@@ -264,7 +317,9 @@ string SAML2Consumer::implementProtocol(
             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
-                if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
+                if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
+                    contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
+                else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
                     ssoStatement = *s;
             }
 
@@ -274,15 +329,17 @@ string SAML2Consumer::implementProtocol(
         }
         catch (exception& ex) {
             m_log.warn("detected a problem with assertion: %s", ex.what());
+            if (!ssoStatement)
+                contextualError = ex.what();
             badtokens.push_back(decrypted);
         }
     }
 
     if (!ssoStatement) {
         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
-        if (addressMismatch.empty())
+        if (contextualError.empty())
             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
-        throw FatalProfileException(addressMismatch.c_str());
+        throw FatalProfileException(contextualError.c_str());
     }
 
     // May need to decrypt NameID.
@@ -296,14 +353,16 @@ string SAML2Consumer::implementProtocol(
             else {
                 Locker credlocker(cr);
                 auto_ptr<MetadataCredentialCriteria> mcc(
-                    policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
+                    policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : nullptr
                     );
                 try {
-                    auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
+                    auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get()));
                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
                     if (ssoName) {
                         ownedName = true;
                         decryptedID.release();
+                        if (m_log.isDebugEnabled())
+                            m_log.debugStream() << "decrypted NameID: " << *ssoName << logging::eol;
                     }
                 }
                 catch (exception& ex) {
@@ -321,8 +380,8 @@ string SAML2Consumer::implementProtocol(
     // Now we have to extract the authentication details for session setup.
 
     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
-    time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
-    const PropertySet* sessionProps = application.getPropertySet("Sessions");
+    time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ?
+        (ssoStatement->getSessionNotOnOrAfterEpoch() + XMLToolingConfig::getConfig().clock_skew_secs) : 0;
     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
     if (!lifetime.first || lifetime.second == 0)
         lifetime.second = 28800;
@@ -340,10 +399,10 @@ string SAML2Consumer::implementProtocol(
                 application,
                 policy.getIssuerMetadata(),
                 samlconstants::SAML20P_NS,
-                NULL,
+                nullptr,
                 ssoName,
-                (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
-                (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
+                (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
+                (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
                 &tokens
                 )
             );
@@ -356,25 +415,25 @@ string SAML2Consumer::implementProtocol(
         // Now merge in bad tokens for caching.
         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
 
-        string key = application.getServiceProvider().getSessionCache()->insert(
-            sessionExp,
+        application.getServiceProvider().getSessionCache()->insert(
             application,
-            httpRequest.getRemoteAddr().c_str(),
-            policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
+            httpRequest,
+            httpResponse,
+            sessionExp,
+            entity,
             samlconstants::SAML20P_NS,
             ssoName,
-            ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
+            ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : nullptr,
             ssoStatement->getSessionIndex(),
-            (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
-            (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
+            (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : nullptr,
+            (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : nullptr,
             &tokens,
-            ctx.get() ? &ctx->getResolvedAttributes() : NULL
+            ctx.get() ? &ctx->getResolvedAttributes() : nullptr
             );
 
         if (ownedName)
             delete ssoName;
         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
-        return key;
     }
     catch (exception&) {
         if (ownedName)