First set of logout base classes and non-building draft of SP-initiated logout.
[shibboleth/sp.git] / shibsp / handler / impl / SAML2Consumer.cpp
index 6d5cda4..414005c 100644 (file)
  */
 
 #include "internal.h"
-#include "Application.h"
-#include "exceptions.h"
-#include "ServiceProvider.h"
-#include "SessionCache.h"
-#include "attribute/resolver/ResolutionContext.h"
 #include "handler/AssertionConsumerService.h"
 
-#include <saml/saml2/core/Protocols.h>
-#include <saml/saml2/profile/BrowserSSOProfileValidator.h>
-#include <saml/saml2/metadata/Metadata.h>
-
-using namespace shibsp;
+#ifndef SHIBSP_LITE
+# include "exceptions.h"
+# 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/saml2/core/Protocols.h>
+# include <saml/saml2/profile/BrowserSSOProfileValidator.h>
+# include <saml/saml2/metadata/Metadata.h>
+# include <saml/saml2/metadata/MetadataCredentialCriteria.h>
 using namespace opensaml::saml2;
 using namespace opensaml::saml2p;
+using namespace opensaml::saml2md;
 using namespace opensaml;
+# ifndef min
+#  define min(a,b)            (((a) < (b)) ? (a) : (b))
+# endif
+#endif
+
+using namespace shibsp;
 using namespace xmltooling;
 using namespace log4cpp;
 using namespace std;
-using saml2md::EntityDescriptor;
 
 namespace shibsp {
 
@@ -52,11 +62,12 @@ namespace shibsp {
     {
     public:
         SAML2Consumer(const DOMElement* e, const char* appId)
-                : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2")) {
+            : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2SSO")) {
         }
         virtual ~SAML2Consumer() {}
         
     private:
+#ifndef SHIBSP_LITE
         string implementProtocol(
             const Application& application,
             const HTTPRequest& httpRequest,
@@ -64,6 +75,7 @@ namespace shibsp {
             const PropertySet* settings,
             const XMLObject& xmlObject
             ) const;
+#endif
     };
 
 #if defined (_MSC_VER)
@@ -77,6 +89,8 @@ namespace shibsp {
     
 };
 
+#ifndef SHIBSP_LITE
+
 string SAML2Consumer::implementProtocol(
     const Application& application,
     const HTTPRequest& httpRequest,
@@ -185,14 +199,8 @@ string SAML2Consumer::implementProtocol(
         }
     }
 
-    // We look up decryption credentials based on the peer who did the encrypting.
-    CredentialCriteria cc;
-    if (policy.getIssuerMetadata()) {
-        auto_ptr_char assertingParty(dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent())->getEntityID());
-        cc.setPeerName(assertingParty.get());
-    }
+    // In case we need decryption...
     CredentialResolver* cr=application.getCredentialResolver();
-
     if (!cr && !encassertions.empty())
         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
 
@@ -201,7 +209,10 @@ string SAML2Consumer::implementProtocol(
         saml2::Assertion* decrypted=NULL;
         try {
             Locker credlocker(cr);
-            auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, &cc));
+            auto_ptr<MetadataCredentialCriteria> mcc(
+                policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
+                );
+            auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, mcc.get()));
             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
             if (decrypted) {
                 wrapper.release();
@@ -228,7 +239,6 @@ string SAML2Consumer::implementProtocol(
             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
             // and signature verification, assuming the relevant rules are configured.
             // We have to marshall the object first to ensure signatures can be checked.
-            decrypted->marshall();
             policy.evaluate(*decrypted);
             
             // If no security is in place now, we kick it.
@@ -290,8 +300,11 @@ string SAML2Consumer::implementProtocol(
                 m_log.warn("found encrypted NameID, but no decryption credential was available");
             else {
                 Locker credlocker(cr);
+                auto_ptr<MetadataCredentialCriteria> mcc(
+                    policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
+                    );
                 try {
-                    auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,&cc));
+                    auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
                     if (ssoName) {
                         ownedName = true;
@@ -308,68 +321,122 @@ string SAML2Consumer::implementProtocol(
     m_log.debug("SSO profile processing completed successfully");
 
     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
-    // To complete processing, we need to resolve attributes and then create the session.
+    // To complete processing, we need to extract and resolve attributes and then create the session.
+
+    // 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");
+    pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
+    if (!lifetime.first || lifetime.second == 0)
+        lifetime.second = 28800;
+    if (sessionExp == 0)
+        sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
+    else
+        sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
+
+    multimap<string,Attribute*> resolvedAttributes;
+    AttributeExtractor* extractor = application.getAttributeExtractor();
+    if (extractor) {
+        m_log.debug("extracting pushed attributes...");
+        Locker extlocker(extractor);
+        try {
+            extractor->extractAttributes(application, policy.getIssuerMetadata(), *ssoName, 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());
+            }
+        }
+    }
+
+    const AuthnContext* authnContext = ssoStatement->getAuthnContext();
+
+    AttributeFilter* filter = application.getAttributeFilter();
+    if (filter && !resolvedAttributes.empty()) {
+        BasicFilteringContext fc(
+            application,
+            resolvedAttributes,
+            policy.getIssuerMetadata(),
+            (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
+            (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL
+            );
+        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(), cleanup_pair<string,shibsp::Attribute>());
+            resolvedAttributes.clear();
+        }
+    }
 
     try {
-        const EntityDescriptor* issuerMetadata = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
+        const EntityDescriptor* issuerMetadata =
+            policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
         auto_ptr<ResolutionContext> ctx(
-            resolveAttributes(application, httpRequest, issuerMetadata, ssoName, &tokens)
+            resolveAttributes(
+                application,
+                issuerMetadata,
+                samlconstants::SAML20P_NS,
+                ssoName,
+                (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
+                (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
+                &tokens,
+                &resolvedAttributes
+                )
             );
 
-        // Copy over any new tokens, but leave them in the context for cleanup.
-        tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
+        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());
 
-        // Now merge in bad tokens for caching.
-        tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
-
-        // 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");
-        pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
-        if (!lifetime.first)
-            lifetime.second = 28800;
-        if (lifetime.second != 0) {
-            if (sessionExp == 0)
-                sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
-            else
-                sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
+            // Copy over new attributes, and transfer ownership.
+            resolvedAttributes.insert(ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
+            ctx->getResolvedAttributes().clear();
         }
 
-        // Other details...
-        const AuthnContext* authnContext = ssoStatement->getAuthnContext();
-        auto_ptr_char authnClass((authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL);
-        auto_ptr_char authnDecl((authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL);
-        auto_ptr_char index(ssoStatement->getSessionIndex());
-        auto_ptr_char authnInstant(ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL);
+        // Now merge in bad tokens for caching.
+        tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
 
-        vector<shibsp::Attribute*>& attrs = ctx->getResolvedAttributes();
         string key = application.getServiceProvider().getSessionCache()->insert(
             sessionExp,
             application,
             httpRequest.getRemoteAddr().c_str(),
             issuerMetadata,
+            samlconstants::SAML20P_NS,
             ssoName,
-            authnInstant.get(),
-            index.get(),
-            authnClass.get(),
-            authnDecl.get(),
+            ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
+            ssoStatement->getSessionIndex(),
+            (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
+            (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
             &tokens,
-            &attrs
+            &resolvedAttributes
             );
-        attrs.clear();  // Attributes are owned by cache now.
+        resolvedAttributes.clear();  // Attributes are owned by cache now.
 
         if (ownedName)
             delete ssoName;
         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
-
+        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
         return key;
     }
     catch (exception&) {
         if (ownedName)
             delete ssoName;
         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
+        for_each(resolvedAttributes.begin(), resolvedAttributes.end(), cleanup_pair<string,Attribute>());
         throw;
     }
 }
+
+#endif