Change license header.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AssertionConsumerService.cpp
index 8f3b008..24751fa 100644 (file)
@@ -1,17 +1,21 @@
-/*
- *  Copyright 2001-2007 Internet2
+/**
+ * Licensed to the University Corporation for Advanced Internet
+ * Development, Inc. (UCAID) under one or more contributor license
+ * agreements. See the NOTICE file distributed with this work for
+ * additional information regarding copyright ownership.
  *
- * 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
+ * UCAID licenses this file to you 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
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ * either express or implied. See the License for the specific
+ * language governing permissions and limitations under the License.
  */
 
 /**
  */
 
 #include "internal.h"
-#include "Application.h"
 #include "exceptions.h"
+#include "Application.h"
 #include "ServiceProvider.h"
+#include "SPRequest.h"
 #include "handler/AssertionConsumerService.h"
 #include "util/SPConstants.h"
 
 # include "attribute/resolver/ResolutionContext.h"
 # include "metadata/MetadataProviderCriteria.h"
 # include "security/SecurityPolicy.h"
+# include "security/SecurityPolicyProvider.h"
+# include <saml/exceptions.h>
 # include <saml/SAMLConfig.h>
 # include <saml/saml1/core/Assertions.h>
+# include <saml/saml2/metadata/Metadata.h>
 # include <saml/util/CommonDomainCookie.h>
 using namespace samlconstants;
 using opensaml::saml2md::MetadataProvider;
@@ -56,10 +64,11 @@ using namespace opensaml;
 using namespace xmltooling;
 using namespace std;
 
-AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
-    : AbstractHandler(e, log)
+AssertionConsumerService::AssertionConsumerService(
+    const DOMElement* e, const char* appId, Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
+    ) : AbstractHandler(e, log, filter, remapper)
 #ifndef SHIBSP_LITE
-        ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
+        ,m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
 #endif
 {
     if (!e)
@@ -107,7 +116,7 @@ void AssertionConsumerService::receive(DDF& in, ostream& out)
 {
     // Find application.
     const char* aid=in["application_id"].string();
-    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
+    const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
     if (!app) {
         // Something's horribly wrong.
         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
@@ -118,7 +127,7 @@ void AssertionConsumerService::receive(DDF& in, ostream& out)
     auto_ptr<HTTPRequest> req(getRequest(in));
 
     // Wrap a response shim.
-    DDF ret(NULL);
+    DDF ret(nullptr);
     DDFJanitor jout(ret);
     auto_ptr<HTTPResponse> resp(getResponse(ret));
 
@@ -139,36 +148,56 @@ pair<bool,long> AssertionConsumerService::processMessage(
     if (!policyId.first)
         policyId = application.getString("policyId");   // unqualified in Application(s) element
 
-    // Access policy properties.
-    const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
-    pair<bool,bool> validate = settings->getBool("validate");
-
     // Lock metadata for use by policy.
     Locker metadataLocker(application.getMetadataProvider());
 
     // Create the policy.
-    shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
+    auto_ptr<opensaml::SecurityPolicy> policy(
+        application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
+        );
 
     string relayState;
-
+    bool relayStateOK = true;
     try {
         // Decode the message and process it in a protocol-specific way.
-        auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
+        auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *(policy.get())));
         if (!msg.get())
             throw BindingException("Failed to decode an SSO protocol response.");
+        DDF postData = recoverPostData(application, httpRequest, httpResponse, relayState.c_str());
+        DDFJanitor postjan(postData);
         recoverRelayState(application, httpRequest, httpResponse, relayState);
-        implementProtocol(application, httpRequest, httpResponse, policy, settings, *msg.get());
+        limitRelayState(m_log, application, httpRequest, relayState.c_str());
+        implementProtocol(application, httpRequest, httpResponse, *(policy.get()), NULL, *msg.get());
 
-        auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
+        auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
 
         // History cookie.
         if (issuer.get() && *issuer.get())
             maintainHistory(application, httpRequest, httpResponse, issuer.get());
 
         // Now redirect to the state value. By now, it should be set to *something* usable.
-        return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
+        // First check for POST data.
+        if (!postData.islist()) {
+            m_log.debug("ACS returning via redirect to: %s", relayState.c_str());
+            return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
+        }
+        else {
+            m_log.debug("ACS returning via POST to: %s", relayState.c_str());
+            return make_pair(true, sendPostResponse(application, httpResponse, relayState.c_str(), postData));
+        }
     }
     catch (XMLToolingException& ex) {
+        if (relayStateOK) {
+            // Check for isPassive error condition.
+            const char* sc2 = ex.getProperty("statusCode2");
+            if (sc2 && !strcmp(sc2, "urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
+                pair<bool,bool> ignore = getBool("ignoreNoPassive", m_configNS.get());  // namespace-qualified if inside handler element
+                if (ignore.first && ignore.second && !relayState.empty()) {
+                    m_log.debug("ignoring SAML status of NoPassive and redirecting to resource...");
+                    return make_pair(true, httpResponse.sendRedirect(relayState.c_str()));
+                }
+            }
+        }
         if (!relayState.empty())
             ex.addProperty("RelayState", relayState.c_str());
         throw;
@@ -203,29 +232,53 @@ void AssertionConsumerService::checkAddress(const Application& application, cons
 
 #ifndef SHIBSP_LITE
 
-void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
+const XMLCh* AssertionConsumerService::getProtocolFamily() const
+{
+    return m_decoder ? m_decoder->getProtocolFamily() : nullptr;
+}
+
+const char* AssertionConsumerService::getType() const
+{
+    return "AssertionConsumerService";
+}
+
+void AssertionConsumerService::generateMetadata(SPSSODescriptor& role, const char* handlerURL) const
+{
+    // Initial guess at index to use.
+    pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
+    if (!strncmp(handlerURL, "https", 5))
+        ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
+    if (!ix.first)
+        ix = getUnsignedInt("index");
+    if (!ix.first)
+        ix.second = 1;
+
+    // Find maximum index in use and go one higher.
+    const vector<saml2md::AssertionConsumerService*>& services = const_cast<const SPSSODescriptor&>(role).getAssertionConsumerServices();
+    if (!services.empty() && ix.second <= services.back()->getIndex().second)
+        ix.second = services.back()->getIndex().second + 1;
+
     const char* loc = getString("Location").second;
     string hurl(handlerURL);
     if (*loc != '/')
         hurl += '/';
     hurl += loc;
     auto_ptr_XMLCh widen(hurl.c_str());
+
     saml2md::AssertionConsumerService* ep = saml2md::AssertionConsumerServiceBuilder::buildAssertionConsumerService();
     ep->setLocation(widen.get());
     ep->setBinding(getXMLString("Binding").second);
-    if (!strncmp(handlerURL, "https", 5)) {
-       pair<bool,const XMLCh*> index = getXMLString("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
-       if (index.first)
-               ep->setIndex(index.second);
-       else
-               ep->setIndex(getXMLString("index").second);
-    }
-    else {
-       ep->setIndex(getXMLString("index").second);
-    }
+    ep->setIndex(ix.second);
     role.getAssertionConsumerServices().push_back(ep);
 }
 
+opensaml::SecurityPolicy* AssertionConsumerService::createSecurityPolicy(
+    const Application& application, const xmltooling::QName* role, bool validate, const char* policyId
+    ) const
+{
+    return new SecurityPolicy(application, role, validate, policyId);
+}
+
 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
 {
 public:
@@ -261,19 +314,18 @@ ResolutionContext* AssertionConsumerService::resolveAttributes(
     const vector<const Assertion*>* tokens
     ) const
 {
-    const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
-
     // First we do the extraction of any pushed information, including from metadata.
     vector<Attribute*> resolvedAttributes;
     AttributeExtractor* extractor = application.getAttributeExtractor();
     if (extractor) {
         Locker extlocker(extractor);
-        if (entity) {
+        if (issuer) {
             pair<bool,const char*> mprefix = application.getString("metadataAttributePrefix");
             if (mprefix.first) {
                 m_log.debug("extracting metadata-derived attributes...");
                 try {
-                    extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
+                    // We pass nullptr for "issuer" because the IdP isn't the one asserting metadata-based attributes.
+                    extractor->extractAttributes(application, nullptr, *issuer, resolvedAttributes);
                     for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
                         vector<string>& ids = (*a)->getAliases();
                         for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
@@ -328,6 +380,9 @@ ResolutionContext* AssertionConsumerService::resolveAttributes(
             }
         }
     }
+    else {
+        m_log.warn("no AttributeExtractor plugin installed, check log during startup");
+    }
 
     try {
         AttributeResolver* resolver = application.getAttributeResolver();
@@ -338,7 +393,7 @@ ResolutionContext* AssertionConsumerService::resolveAttributes(
             auto_ptr<ResolutionContext> ctx(
                 resolver->createResolutionContext(
                     application,
-                    entity,
+                    issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : nullptr,
                     protocol,
                     nameid,
                     authncontext_class,
@@ -351,17 +406,6 @@ ResolutionContext* AssertionConsumerService::resolveAttributes(
             // Copy over any pushed attributes.
             if (!resolvedAttributes.empty())
                 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
-
-            // Attach global prefix if needed.
-            pair<bool,const char*> prefix = application.getString("attributePrefix");
-            if (prefix.first) {
-                for (vector<Attribute*>::iterator a = ctx->getResolvedAttributes().begin(); a != ctx->getResolvedAttributes().end(); ++a) {
-                    vector<string>& ids = (*a)->getAliases();
-                    for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
-                        *id = prefix.second + *id;
-                }
-            }
-
             return ctx.release();
         }
     }
@@ -369,20 +413,9 @@ ResolutionContext* AssertionConsumerService::resolveAttributes(
         m_log.error("attribute resolution failed: %s", ex.what());
     }
 
-    if (!resolvedAttributes.empty()) {
-        // Attach global prefix if needed.
-        pair<bool,const char*> prefix = application.getString("attributePrefix");
-        if (prefix.first) {
-            for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
-                vector<string>& ids = (*a)->getAliases();
-                for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
-                    *id = prefix.second + *id;
-            }
-        }
-
+    if (!resolvedAttributes.empty())
         return new DummyContext(resolvedAttributes);
-    }
-    return NULL;
+    return nullptr;
 }
 
 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
@@ -412,15 +445,11 @@ void AssertionConsumerService::extractMessageDetails(const Assertion& assertion,
         }
         m_log.debug("searching metadata for assertion issuer...");
         pair<const EntityDescriptor*,const RoleDescriptor*> entity;
-        shibsp::SecurityPolicy* sppol = dynamic_cast<shibsp::SecurityPolicy*>(&policy);
-        if (sppol) {
-            MetadataProviderCriteria mc(sppol->getApplication(), policy.getIssuer()->getName(), &IDPSSODescriptor::ELEMENT_QNAME, protocol);
-            entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
-        }
-        else {
-            MetadataProvider::Criteria mc(policy.getIssuer()->getName(), &IDPSSODescriptor::ELEMENT_QNAME, protocol);
-            entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
-        }
+        MetadataProvider::Criteria& mc = policy.getMetadataProviderCriteria();
+        mc.entityID_unicode = policy.getIssuer()->getName();
+        mc.role = &IDPSSODescriptor::ELEMENT_QNAME;
+        mc.protocol = protocol;
+        entity = policy.getMetadataProvider()->getEntityDescriptor(mc);
         if (!entity.first) {
             auto_ptr_char iname(policy.getIssuer()->getName());
             m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
@@ -460,7 +489,7 @@ void AssertionConsumerService::maintainHistory(
             response.setCookie(CommonDomainCookie::CDCName, c.c_str());
         }
         else {
-            time_t now=time(NULL) + (days.second * 24 * 60 * 60);
+            time_t now=time(nullptr) + (days.second * 24 * 60 * 60);
 #ifdef HAVE_GMTIME_R
             struct tm res;
             struct tm* ptime=gmtime_r(&now,&res);