https://issues.shibboleth.net/jira/browse/SSPCPP-459
[shibboleth/sp.git] / shibsp / impl / XMLServiceProvider.cpp
index 9a6a033..022be8a 100644 (file)
@@ -50,7 +50,7 @@
 #endif
 #include <algorithm>
 #include <boost/bind.hpp>
-#include <boost/scoped_ptr.hpp>
+#include <boost/lexical_cast.hpp>
 #include <boost/shared_ptr.hpp>
 #include <boost/algorithm/string.hpp>
 #include <boost/tuple/tuple.hpp>
 # include "attribute/resolver/AttributeResolver.h"
 # include "security/PKIXTrustEngine.h"
 # include "security/SecurityPolicyProvider.h"
-# include <saml/SAMLConfig.h>
+# include <saml/exceptions.h>
 # include <saml/version.h>
+# include <saml/SAMLConfig.h>
 # include <saml/binding/ArtifactMap.h>
 # include <saml/binding/SAMLArtifact.h>
 # include <saml/saml1/core/Assertions.h>
 # include <saml/saml2/core/Assertions.h>
 # include <saml/saml2/binding/SAML2ArtifactType0004.h>
+# include <saml/saml2/metadata/EntityMatcher.h>
 # include <saml/saml2/metadata/Metadata.h>
 # include <saml/saml2/metadata/MetadataProvider.h>
 # include <saml/util/SAMLConstants.h>
@@ -162,6 +164,7 @@ namespace {
         }
         const PropertySet* getRelyingParty(const EntityDescriptor* provider) const;
         const PropertySet* getRelyingParty(const XMLCh* entityID) const;
+
         const vector<const XMLCh*>* getAudiences() const {
             return (m_audiences.empty() && m_base) ? m_base->getAudiences() : &m_audiences;
         }
@@ -184,6 +187,7 @@ namespace {
         const vector<const Handler*>& getAssertionConsumerServicesByBinding(const XMLCh* binding) const;
         const Handler* getHandler(const char* path) const;
         void getHandlers(vector<const Handler*>& handlers) const;
+        void limitRedirect(const GenericRequest& request, const char* url) const;
 
         void receive(DDF& in, ostream& out) {
             // Only current function is to return the headers to clear.
@@ -235,7 +239,8 @@ namespace {
         vector<const XMLCh*> m_audiences;
 
         // RelyingParty properties
-        map< xstring,boost::shared_ptr<PropertySet> > m_partyMap;
+        map< xstring,boost::shared_ptr<PropertySet> > m_partyMap;   // name-based matching
+        vector< pair< boost::shared_ptr<EntityMatcher>,boost::shared_ptr<PropertySet> > > m_partyVec;  // plugin-based matching
 #endif
         vector<string> m_remoteUsers,m_frontLogout,m_backLogout;
 
@@ -272,6 +277,17 @@ namespace {
             if (m_artifactResolutionDefault) return m_artifactResolutionDefault->getInt("index");
             return m_base ? m_base->getArtifactEndpointIndex() : make_pair(false,0);
         }
+
+        enum {
+            REDIRECT_LIMIT_INHERIT,
+            REDIRECT_LIMIT_NONE,
+            REDIRECT_LIMIT_EXACT,
+            REDIRECT_LIMIT_HOST,
+            REDIRECT_LIMIT_WHITELIST,
+            REDIRECT_LIMIT_EXACT_WHITELIST,
+            REDIRECT_LIMIT_HOST_WHITELIST
+        } m_redirectLimit;
+        vector<string> m_redirectWhitelist;
     };
 
     // Top-level configuration implementation
@@ -527,10 +543,51 @@ XMLApplication::XMLApplication(
 #ifdef _DEBUG
     xmltooling::NDC ndc("XMLApplication");
 #endif
-    Category& log=Category::getInstance(SHIBSP_LOGCAT".Application");
+    Category& log = Category::getInstance(SHIBSP_LOGCAT".Application");
 
     // First load any property sets.
-    load(e, nullptr, this);
+    map<string,string> remapper;
+    remapper["relayStateLimit"] = "redirectLimit";
+    remapper["relayStateWhitelist"] = "redirectWhitelist";
+    load(e, nullptr, this, &remapper);
+
+    // Process redirect limit policy. Do this before assigning the parent pointer
+    // to ensure we get only our Sessions element.
+    const PropertySet* sessionProps = getPropertySet("Sessions");
+    if (sessionProps) {
+        pair<bool,const char*> redirectLimit = sessionProps->getString("redirectLimit");
+        if (redirectLimit.first) {
+            if (!strcmp(redirectLimit.second, "none"))
+                m_redirectLimit = REDIRECT_LIMIT_NONE;
+            else if (!strcmp(redirectLimit.second, "exact"))
+                m_redirectLimit = REDIRECT_LIMIT_EXACT;
+            else if (!strcmp(redirectLimit.second, "host"))
+                m_redirectLimit = REDIRECT_LIMIT_HOST;
+            else {
+                if (!strcmp(redirectLimit.second, "exact+whitelist"))
+                    m_redirectLimit = REDIRECT_LIMIT_EXACT_WHITELIST;
+                else if (!strcmp(redirectLimit.second, "host+whitelist"))
+                    m_redirectLimit = REDIRECT_LIMIT_HOST_WHITELIST;
+                else if (!strcmp(redirectLimit.second, "whitelist"))
+                    m_redirectLimit = REDIRECT_LIMIT_WHITELIST;
+                else
+                    throw ConfigurationException("Unrecognized redirectLimit setting ($1)", params(1, redirectLimit.second));
+                redirectLimit = sessionProps->getString("redirectWhitelist");
+                if (redirectLimit.first) {
+                    string dup(redirectLimit.second);
+                    split(m_redirectWhitelist, dup, is_space(), algorithm::token_compress_on);
+                }
+            }
+        }
+        else {
+            m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
+        }
+    }
+    else {
+        m_redirectLimit = base ? REDIRECT_LIMIT_INHERIT : REDIRECT_LIMIT_NONE;
+    }
+
+    // Assign parent.
     if (base)
         setParent(base);
 
@@ -629,9 +686,17 @@ XMLApplication::XMLApplication(
             rp->setParent(this);
             m_partyMap[child->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
         }
+        else if (child->hasAttributeNS(nullptr, _type)) {
+            string emtype(XMLHelper::getAttrString(child, nullptr, _type));
+            boost::shared_ptr<EntityMatcher> em(SAMLConfig::getConfig().EntityMatcherManager.newPlugin(emtype, child));
+            boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
+            rp->load(child, nullptr, this);
+            rp->setParent(this);
+            m_partyVec.push_back(make_pair(em, rp));
+        }
         child = XMLHelper::getNextSiblingElement(child, RelyingParty);
     }
-    if (base && m_partyMap.empty() && !base->m_partyMap.empty()) {
+    if (base && m_partyMap.empty() && m_partyVec.empty() && (!base->m_partyMap.empty() || !base->m_partyVec.empty())) {
         // For inheritance of RPs to work, we have to pull them in to the override by cloning the DOM.
         child = XMLHelper::getFirstChildElement(base->getElement(), RelyingParty);
         while (child) {
@@ -642,6 +707,15 @@ XMLApplication::XMLApplication(
                 rp->setParent(this);
                 m_partyMap[rpclone->getAttributeNS(nullptr, saml2::Attribute::NAME_ATTRIB_NAME)] = rp;
             }
+            else if (child->hasAttributeNS(nullptr, _type)) {
+                DOMElement* rpclone = static_cast<DOMElement*>(child->cloneNode(true));
+                string emtype(XMLHelper::getAttrString(rpclone, nullptr, _type));
+                boost::shared_ptr<EntityMatcher> em(SAMLConfig::getConfig().EntityMatcherManager.newPlugin(emtype, rpclone));
+                boost::shared_ptr<DOMPropertySet> rp(new DOMPropertySet());
+                rp->load(rpclone, nullptr, this);
+                rp->setParent(this);
+                m_partyVec.push_back(make_pair(em, rp));
+            }
             child = XMLHelper::getNextSiblingElement(child, RelyingParty);
         }
     }
@@ -989,6 +1063,8 @@ void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, D
 
     SPConfig& conf = SPConfig::getConfig();
 
+    int index = 0; // track ACS indexes globally across all protocols
+
     // Tokenize the protocol list inside the element.
     XMLStringTokenizer prottokens(e->getTextContent());
     while (prottokens.hasMoreTokens()) {
@@ -1018,7 +1094,6 @@ void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, D
         const vector<const PropertySet*>& bindings = pp.getBindings(prot.get(), "SSO");
         if (!bindings.empty()) {
             log.info("auto-configuring SSO endpoints for protocol (%s)", prot.get());
-            int index = 0;
             pair<bool,const XMLCh*> idprop,pathprop;
             for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
                 idprop = (*b)->getXMLString("id");
@@ -1027,7 +1102,7 @@ void XMLApplication::doSSO(const ProtocolProvider& pp, set<string>& protocols, D
                     DOMElement* acsdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _AssertionConsumerService);
                     acsdom->setAttributeNS(nullptr, Binding, idprop.second);
                     acsdom->setAttributeNS(nullptr, Location, pathprop.second);
-                    xstring indexbuf(chDigit_1 + (index % 10), 1);
+                    xstring indexbuf(1, chDigit_1 + (index % 10));
                     if (index / 10)
                         indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
                     acsdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
@@ -1249,20 +1324,21 @@ void XMLApplication::doArtifactResolution(const ProtocolProvider& pp, const char
 {
     SPConfig& conf = SPConfig::getConfig();
 
+    int index = 0; // track indexes globally across all protocols
+
     // Look for incoming bindings.
     const vector<const PropertySet*>& bindings = pp.getBindings(protocol, "ArtifactResolution");
     if (!bindings.empty()) {
         log.info("auto-configuring ArtifactResolution endpoints for protocol (%s)", protocol);
-        int index = 0;
         pair<bool,const XMLCh*> idprop,pathprop;
-        for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b) {
+        for (vector<const PropertySet*>::const_iterator b = bindings.begin(); b != bindings.end(); ++b, ++index) {
             idprop = (*b)->getXMLString("id");
             pathprop = (*b)->getXMLString("path");
             if (idprop.first && pathprop.first) {
                 DOMElement* artdom = e->getOwnerDocument()->createElementNS(samlconstants::SAML20MD_NS, _ArtifactResolutionService);
                 artdom->setAttributeNS(nullptr, Binding, idprop.second);
                 artdom->setAttributeNS(nullptr, Location, pathprop.second);
-                xstring indexbuf(chDigit_1 + (index % 10), 1);
+                xstring indexbuf(1, chDigit_1 + (index % 10));
                 if (index / 10)
                     indexbuf = (XMLCh)(chDigit_1 + (index / 10)) + indexbuf;
                 artdom->setAttributeNS(nullptr, _index, indexbuf.c_str());
@@ -1393,9 +1469,19 @@ const PropertySet* XMLApplication::getRelyingParty(const EntityDescriptor* provi
     if (!provider)
         return this;
 
+    // Check for exact match on name.
     map< xstring,boost::shared_ptr<PropertySet> >::const_iterator i = m_partyMap.find(provider->getEntityID());
     if (i != m_partyMap.end())
         return i->second.get();
+
+    // Check for extensible matching.
+    vector < pair< boost::shared_ptr<EntityMatcher>,boost::shared_ptr<PropertySet> > >::const_iterator j;
+    for (j = m_partyVec.begin(); j != m_partyVec.end(); ++j) {
+        if (j->first->matches(*provider))
+            return j->second.get();
+    }
+
+    // Check for group match.
     const EntitiesDescriptor* group = dynamic_cast<const EntitiesDescriptor*>(provider->getParent());
     while (group) {
         if (group->getName()) {
@@ -1603,6 +1689,43 @@ void XMLApplication::getHandlers(vector<const Handler*>& handlers) const
     }
 }
 
+void XMLApplication::limitRedirect(const GenericRequest& request, const char* url) const
+{
+    if (!url || *url == '/')
+        return;
+    if (m_redirectLimit == REDIRECT_LIMIT_INHERIT)
+        return m_base->limitRedirect(request, url);
+    if (m_redirectLimit != REDIRECT_LIMIT_NONE) {
+        vector<string> whitelist;
+        if (m_redirectLimit == REDIRECT_LIMIT_EXACT || m_redirectLimit == REDIRECT_LIMIT_EXACT_WHITELIST) {
+            // Scheme and hostname have to match.
+            if (request.isDefaultPort()) {
+                whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + '/');
+            }
+            whitelist.push_back(string(request.getScheme()) + "://" + request.getHostname() + ':' + lexical_cast<string>(request.getPort()) + '/');
+        }
+        else if (m_redirectLimit == REDIRECT_LIMIT_HOST || m_redirectLimit == REDIRECT_LIMIT_HOST_WHITELIST) {
+            // Allow any scheme or port.
+            whitelist.push_back(string("https://") + request.getHostname() + '/');
+            whitelist.push_back(string("http://") + request.getHostname() + '/');
+            whitelist.push_back(string("https://") + request.getHostname() + ':');
+            whitelist.push_back(string("http://") + request.getHostname() + ':');
+        }
+
+        static bool (*startsWithI)(const char*,const char*) = XMLString::startsWithI;
+        if (!whitelist.empty() && find_if(whitelist.begin(), whitelist.end(),
+                boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != whitelist.end()) {
+            return;
+        }
+        else if (!m_redirectWhitelist.empty() && find_if(m_redirectWhitelist.begin(), m_redirectWhitelist.end(),
+                boost::bind(startsWithI, url, boost::bind(&string::c_str, _1))) != m_redirectWhitelist.end()) {
+            return;
+        }
+        Category::getInstance(SHIBSP_LOGCAT".Application").warn("redirectLimit policy enforced, blocked redirect to (%s)", url);
+        throw opensaml::SecurityPolicyException("Blocked unacceptable redirect location.");
+    }
+}
+
 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
 short
 #else
@@ -1799,6 +1922,8 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer,
     const DOMElement* SHIRE=XMLHelper::getFirstChildElement(e, InProcess);
 
     // Initialize logging manually in order to redirect log messages as soon as possible.
+    // If no explicit config is supplied, we now assume the caller has done this, so that
+    // setuid processes can potentially do this as root.
     if (conf.isEnabled(SPConfig::Logging)) {
         string logconf;
         if (conf.isEnabled(SPConfig::OutOfProcess))
@@ -1807,15 +1932,6 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer,
             logconf = XMLHelper::getAttrString(SHIRE, nullptr, logger);
         if (logconf.empty())
             logconf = XMLHelper::getAttrString(e, nullptr, logger);
-        if (logconf.empty() && !getenv("SHIBSP_LOGGING")) {
-            // No properties found, so default them.
-            if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess))
-                logconf = "shibd.logger";
-            else if (!conf.isEnabled(SPConfig::OutOfProcess) && conf.isEnabled(SPConfig::InProcess))
-                logconf = "native.logger";
-            else
-                logconf = "shibboleth.logger";
-        }
         if (!logconf.empty()) {
             log.debug("loading new logging configuration from (%s), check log destination for status of configuration", logconf.c_str());
             if (!XMLToolingConfig::getConfig().log_config(logconf.c_str()))
@@ -1883,6 +1999,17 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer,
             split(HTTPResponse::getAllowedSchemes(), schemes, is_space(), algorithm::token_compress_on);
         }
 
+        // Default language handling.
+        pair<bool,bool> langFromClient = getBool("langFromClient");
+        pair<bool,const XMLCh*> langPriority = getXMLString("langPriority");
+        GenericRequest::setLangDefaults(!langFromClient.first || langFromClient.second, langPriority.second);
+
+#ifndef SHIBSP_LITE
+        langPriority = getXMLString("contactPriority");
+        if (langPriority.first)
+            SAMLConfig::getConfig().setContactPriority(langPriority.second);
+#endif
+
         // Extensions
         doExtensions(e, "global", log);
         if (conf.isEnabled(SPConfig::OutOfProcess))
@@ -2029,6 +2156,7 @@ XMLConfigImpl::XMLConfigImpl(const DOMElement* e, bool first, XMLConfig* outer,
             if (extraAuthTypes.first) {
                 string types(extraAuthTypes.second);
                 split(outer->m_authTypes, types, is_space(), algorithm::token_compress_on);
+                outer->m_authTypes.insert("shibboleth");
             }
         }
     }