Revert "Revert "try to guard against multiple shibboleth library initializations""
[moonshot.git] / mech_eap / util_shib.cpp
index f29e521..b1464f7 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, JANET(UK)
+ * Copyright (c) 2011, JANET(UK)
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -31,7 +31,7 @@
  */
 /*
  * Copyright 2001-2009 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
  * limitations under the License.
  */
 
-#include "gssapiP_eap.h"
+/*
+ * Local attribute provider implementation.
+ */
+
+#include <xmltooling/XMLObject.h>
+
+#include <saml/saml2/core/Assertions.h>
 
-#include <shibsp/Application.h>
 #include <shibsp/exceptions.h>
-#include <shibsp/SPConfig.h>
-#include <shibsp/ServiceProvider.h>
-#include <shibsp/attribute/Attribute.h>
 #include <shibsp/attribute/SimpleAttribute.h>
-#include <shibsp/attribute/resolver/ResolutionContext.h>
-#include <shibsp/handler/AssertionConsumerService.h>
-#include <shibsp/metadata/MetadataProviderCriteria.h>
-#include <shibsp/util/SPConstants.h>
+#include <shibresolver/resolver.h>
 
-#include <saml/saml1/core/Assertions.h>
-#include <saml/saml2/core/Assertions.h>
-#include <saml/saml2/metadata/Metadata.h>
-#include <xercesc/util/XMLUniDefs.hpp>
-#include <xmltooling/XMLToolingConfig.h>
-#include <xmltooling/util/XMLHelper.h>
+#include <sstream>
 
-#include "resolver.h"
+#include "gssapiP_eap.h"
 
 using namespace shibsp;
 using namespace shibresolver;
 using namespace opensaml::saml2md;
 using namespace opensaml;
-using namespace xmltooling::logging;
 using namespace xmltooling;
-using namespace xercesc;
 using namespace std;
 
-bool
-gss_eap_shib_attr_source::initFromExistingContext(const gss_eap_attr_ctx *manager,
-                                                  const gss_eap_attr_source *ctx)
+gss_eap_shib_attr_provider::gss_eap_shib_attr_provider(void)
 {
-    const gss_eap_shib_attr_source *shib;
-
-    if (!gss_eap_attr_source::initFromExistingContext(manager, ctx))
-        return false;
-
-    shib = dynamic_cast<const gss_eap_shib_attr_source *>(ctx);
-    if (shib != NULL)
-        m_attributes = duplicateAttributes(shib->getAttributes());
+    m_initialized = false;
+    m_authenticated = false;
+}
 
-    return true;
+gss_eap_shib_attr_provider::~gss_eap_shib_attr_provider(void)
+{
+    for_each(m_attributes.begin(),
+             m_attributes.end(),
+             xmltooling::cleanup<Attribute>())
+        ;
 }
 
 bool
-addRadiusAttribute(const gss_eap_attr_source *provider,
-                   const gss_buffer_t attribute,
-                   void *data)
+gss_eap_shib_attr_provider::initWithExistingContext(const gss_eap_attr_ctx *manager,
+                                                    const gss_eap_attr_provider *ctx)
 {
-    const gss_eap_shib_attr_source *shib;
-    const gss_eap_radius_attr_source *radius;
-    int authenticated, complete, more = -1;
-    vector <string> attributeIds(1);
-    SimpleAttribute *a;
-
-    radius = dynamic_cast<const gss_eap_radius_attr_source *>(provider);
-    shib = static_cast<const gss_eap_shib_attr_source *>(data);
+    const gss_eap_shib_attr_provider *shib;
 
-    assert(radius != NULL && shib != NULL);
-
-    string attributeName =
-        gss_eap_attr_ctx::composeAttributeName(ATTR_TYPE_RADIUS, attribute);
-
-    attributeIds.push_back(attributeName);
-    a = new SimpleAttribute(attributeIds);
-    if (a == NULL)
+    if (!gss_eap_attr_provider::initWithExistingContext(manager, ctx)) {
         return false;
+    }
 
-    while (more != 0) {
-        gss_buffer_desc value = GSS_C_EMPTY_BUFFER;
-        OM_uint32 minor;
+    m_authenticated = false;
 
-        if (!radius->getAttribute(attribute,
-                                  &authenticated,
-                                  &complete,
-                                  &value,
-                                  NULL,
-                                  &more))
-            return false;
+    shib = static_cast<const gss_eap_shib_attr_provider *>(ctx);
+    if (shib != NULL) {
+        m_attributes = duplicateAttributes(shib->getAttributes());
+        m_authenticated = shib->authenticated();
+    }
+
+    m_initialized = true;
 
-        string attributeValue((char *)value.value, value.length);
-        a->getValues().push_back(attributeValue);
+    return true;
+}
 
-        gss_release_buffer(&minor, &value);
+static OM_uint32
+exportMechSecContext(OM_uint32 *minor,
+                     gss_ctx_id_t gssCtx,
+                     gss_buffer_t mechContext)
+{
+    OM_uint32 major;
+    gss_buffer_desc exportedCtx;
+    unsigned char *p;
+
+    assert(gssCtx->mechanismUsed != GSS_C_NO_OID);
+
+    major = gssEapExportSecContext(minor, gssCtx, &exportedCtx);
+    if (GSS_ERROR(major))
+        return major;
+
+    /*
+     * gss_import_sec_context expects the exported security context token
+     * to be tagged with the mechanism OID; in Heimdal and MIT, this is
+     * done by the mechglue, so if we are subverting the mechglue we need
+     * to add it ourselves.
+     */
+    mechContext->length = 4 + gssCtx->mechanismUsed->length + exportedCtx.length;
+    mechContext->value = p = (unsigned char *)GSSEAP_MALLOC(mechContext->length);
+    if (mechContext->value == NULL) {
+        gss_release_buffer(minor, &exportedCtx);
+        throw std::bad_alloc();
     }
 
-    shib->getAttributes().push_back(a);
+    p = store_oid(gssCtx->mechanismUsed, p);
+    memcpy(p, exportedCtx.value, exportedCtx.length);
 
-    return true;
+    gss_release_buffer(minor, &exportedCtx);
+
+    return GSS_S_COMPLETE;
 }
 
 bool
-gss_eap_shib_attr_source::initFromGssContext(const gss_eap_attr_ctx *manager,
-                                             const gss_cred_id_t gssCred,
-                                             const gss_ctx_id_t gssCtx)
+gss_eap_shib_attr_provider::initWithGssContext(const gss_eap_attr_ctx *manager,
+                                               const gss_cred_id_t gssCred,
+                                               const gss_ctx_id_t gssCtx)
 {
-    const gss_eap_saml_assertion_source *saml;
-    const gss_eap_radius_attr_source *radius;
-    gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
-    ShibbolethResolver *resolver = NULL;
-    OM_uint32 minor;
-
-    if (!gss_eap_attr_source::initFromGssContext(manager, gssCred, gssCtx))
+    if (!gss_eap_attr_provider::initWithGssContext(manager, gssCred, gssCtx))
         return false;
 
-    saml = dynamic_cast<const gss_eap_saml_assertion_source *>
-        (manager->getProvider(ATTR_TYPE_SAML_ASSERTION));
-    radius = dynamic_cast<const gss_eap_radius_attr_source *>
-        (manager->getProvider(ATTR_TYPE_RADIUS));
+    auto_ptr<ShibbolethResolver> resolver(ShibbolethResolver::create());
 
+    /*
+     * For now, leave ApplicationID defaulted.
+     * Later on, we could allow this via config option to the mechanism
+     * or rely on an SPRequest interface to pass in a URI identifying the
+     * acceptor.
+     */
+#if 0
+    gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
     if (gssCred != GSS_C_NO_CREDENTIAL &&
-        gss_display_name(&minor, gssCred->name, &nameBuf, NULL) == GSS_S_COMPLETE)
+        gssEapDisplayName(&minor, gssCred->name, &nameBuf, NULL) == GSS_S_COMPLETE) {
         resolver->setApplicationID((const char *)nameBuf.value);
+        gss_release_buffer(&minor, &nameBuf);
+    }
+#endif
+
+    gss_buffer_desc mechContext = GSS_C_EMPTY_BUFFER;
+    OM_uint32 major, minor;
+    major = exportMechSecContext(&minor, gssCtx, &mechContext);
+    if (major == GSS_S_COMPLETE) {
+        resolver->addToken(&mechContext);
+        gss_release_buffer(&minor, &mechContext);
+    }
 
-    if (saml != NULL && saml->getAssertion() != NULL)
+    const gss_eap_saml_assertion_provider *saml;
+    saml = static_cast<const gss_eap_saml_assertion_provider *>
+        (m_manager->getProvider(ATTR_TYPE_SAML_ASSERTION));
+    if (saml != NULL && saml->getAssertion() != NULL) {
         resolver->addToken(saml->getAssertion());
+    }
 
-    if (radius != NULL)
-        radius->getAttributeTypes(addRadiusAttribute, (void *)this);
-
-    resolver->resolveAttributes(m_attributes);
-
-    gss_release_buffer(&minor, &nameBuf);
+    try {
+        resolver->resolve();
+        m_attributes = resolver->getResolvedAttributes();
+        resolver->getResolvedAttributes().clear();
+    } catch (exception &e) {
+        return false;
+    }
 
-    delete resolver;
+    m_authenticated = true;
+    m_initialized = true;
 
     return true;
 }
 
-gss_eap_shib_attr_source::~gss_eap_shib_attr_source(void)
-{
-    for_each(m_attributes.begin(),
-             m_attributes.end(),
-             xmltooling::cleanup<Attribute>())
-        ;
-}
-
-int
-gss_eap_shib_attr_source::getAttributeIndex(const gss_buffer_t attr) const
+ssize_t
+gss_eap_shib_attr_provider::getAttributeIndex(const gss_buffer_t attr) const
 {
     int i = 0;
 
+    assert(m_initialized);
+
     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
          a != m_attributes.end();
          ++a)
@@ -207,41 +219,51 @@ gss_eap_shib_attr_source::getAttributeIndex(const gss_buffer_t attr) const
     return -1;
 }
 
-void
-gss_eap_shib_attr_source::setAttribute(int complete,
-                                       const gss_buffer_t attr,
-                                       const gss_buffer_t value)
+bool
+gss_eap_shib_attr_provider::setAttribute(int complete GSSEAP_UNUSED,
+                                         const gss_buffer_t attr,
+                                         const gss_buffer_t value)
 {
     string attrStr((char *)attr->value, attr->length);
-    vector <string> ids(1);
-
-    ids.push_back(attrStr);
-
+    vector <string> ids(1, attrStr);
     SimpleAttribute *a = new SimpleAttribute(ids);
 
+    assert(m_initialized);
+
     if (value->length != 0) {
         string valueStr((char *)value->value, value->length);
 
-        a->getValues().push_back(valueStr);        
+        a->getValues().push_back(valueStr);
     }
 
     m_attributes.push_back(a);
+    m_authenticated = false;
+
+    return true;
 }
 
-void
-gss_eap_shib_attr_source::deleteAttribute(const gss_buffer_t attr)
+bool
+gss_eap_shib_attr_provider::deleteAttribute(const gss_buffer_t attr)
 {
     int i;
 
+    assert(m_initialized);
+
     i = getAttributeIndex(attr);
     if (i >= 0)
         m_attributes.erase(m_attributes.begin() + i);
+
+    m_authenticated = false;
+
+    return true;
 }
 
 bool
-gss_eap_shib_attr_source::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
-                                            void *data) const
+gss_eap_shib_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
+                                              void *data) const
 {
+    assert(m_initialized);
+
     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
         a != m_attributes.end();
         ++a)
@@ -251,7 +273,7 @@ gss_eap_shib_attr_source::getAttributeTypes(gss_eap_attr_enumeration_cb addAttri
         attribute.value = (void *)((*a)->getId());
         attribute.length = strlen((char *)attribute.value);
 
-        if (!addAttribute(this, &attribute, data))
+        if (!addAttribute(m_manager, this, &attribute, data))
             return false;
     }
 
@@ -259,10 +281,12 @@ gss_eap_shib_attr_source::getAttributeTypes(gss_eap_attr_enumeration_cb addAttri
 }
 
 const Attribute *
-gss_eap_shib_attr_source::getAttribute(const gss_buffer_t attr) const
+gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr) const
 {
     const Attribute *ret = NULL;
 
+    assert(m_initialized);
+
     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
          a != m_attributes.end();
          ++a)
@@ -284,44 +308,65 @@ gss_eap_shib_attr_source::getAttribute(const gss_buffer_t attr) const
 }
 
 bool
-gss_eap_shib_attr_source::getAttribute(const gss_buffer_t attr,
-                                       int *authenticated,
-                                       int *complete,
-                                       gss_buffer_t value,
-                                       gss_buffer_t display_value,
-                                       int *more) const
+gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr,
+                                         int *authenticated,
+                                         int *complete,
+                                         gss_buffer_t value,
+                                         gss_buffer_t display_value,
+                                         int *more) const
 {
     const Attribute *shibAttr = NULL;
     gss_buffer_desc buf;
+    int nvalues, i = *more;
+
+    assert(m_initialized);
+
+    *more = 0;
 
     shibAttr = getAttribute(attr);
     if (shibAttr == NULL)
         return false;
 
-    if (*more == -1) {
-        *more = 0;
-    } else if (*more >= (int)shibAttr->valueCount()) {
-        *more = 0;
-        return true;
-    }
+    nvalues = shibAttr->valueCount();
 
-    buf.value = (void *)shibAttr->getString(*more);
+    if (i == -1)
+        i = 0;
+    if (i >= nvalues)
+        return false;
+
+    buf.value = (void *)shibAttr->getSerializedValues()[*more].c_str();
     buf.length = strlen((char *)buf.value);
 
-    duplicateBuffer(buf, value);
-    *authenticated = TRUE;
-    *complete = FALSE;
+    if (buf.length != 0) {
+        if (value != NULL)
+            duplicateBuffer(buf, value);
+
+        if (display_value != NULL)
+            duplicateBuffer(buf, display_value);
+    }
+
+    if (authenticated != NULL)
+        *authenticated = m_authenticated;
+    if (complete != NULL)
+        *complete = false;
+
+    if (nvalues > ++i)
+        *more = i;
 
     return true;
 }
 
 gss_any_t
-gss_eap_shib_attr_source::mapToAny(int authenticated,
-                                   gss_buffer_t type_id) const
+gss_eap_shib_attr_provider::mapToAny(int authenticated,
+                                     gss_buffer_t type_id GSSEAP_UNUSED) const
 {
     gss_any_t output;
 
+    assert(m_initialized);
+
+    if (authenticated && !m_authenticated)
+        return (gss_any_t)NULL;
+
     vector <Attribute *>v = duplicateAttributes(m_attributes);
 
     output = (gss_any_t)new vector <Attribute *>(v);
@@ -330,62 +375,139 @@ gss_eap_shib_attr_source::mapToAny(int authenticated,
 }
 
 void
-gss_eap_shib_attr_source::releaseAnyNameMapping(gss_buffer_t type_id,
-                                                gss_any_t input) const
+gss_eap_shib_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id GSSEAP_UNUSED,
+                                                  gss_any_t input) const
 {
+    assert(m_initialized);
+
     vector <Attribute *> *v = ((vector <Attribute *> *)input);
     delete v;
 }
 
-void
-gss_eap_shib_attr_source::exportToBuffer(gss_buffer_t buffer) const
+const char *
+gss_eap_shib_attr_provider::prefix(void) const
 {
-    buffer->length = 0;
-    buffer->value = NULL;
+    return NULL;
+}
+
+const char *
+gss_eap_shib_attr_provider::name(void) const
+{
+    return "local";
+}
+
+JSONObject
+gss_eap_shib_attr_provider::jsonRepresentation(void) const
+{
+    JSONObject obj;
+
+    if (m_initialized == false)
+        return obj; /* don't export incomplete context */
+
+    JSONObject jattrs = JSONObject::array();
+
+    for (vector<Attribute*>::const_iterator a = m_attributes.begin();
+         a != m_attributes.end(); ++a) {
+        DDF attr = (*a)->marshall();
+        JSONObject jattr = JSONObject::ddf(attr);
+        jattrs.append(jattr);
+    }
+
+    obj.set("attributes", jattrs);
+
+    obj.set("authenticated", m_authenticated);
+
+    return obj;
 }
 
 bool
-gss_eap_shib_attr_source::initFromBuffer(const gss_eap_attr_ctx *ctx,
-                                         const gss_buffer_t buffer)
+gss_eap_shib_attr_provider::initWithJsonObject(const gss_eap_attr_ctx *ctx,
+                                               JSONObject &obj)
 {
-    if (!gss_eap_attr_source::initFromBuffer(ctx, buffer))
+    if (!gss_eap_attr_provider::initWithJsonObject(ctx, obj))
         return false;
 
+    assert(m_authenticated == false);
+    assert(m_attributes.size() == 0);
+
+    JSONObject jattrs = obj["attributes"];
+    size_t nelems = jattrs.size();
+
+    for (size_t i = 0; i < nelems; i++) {
+        JSONObject jattr = jattrs.get(i);
+
+        DDF attr = jattr.ddf();
+        Attribute *attribute = Attribute::unmarshall(attr);
+        m_attributes.push_back(attribute);
+    }
+
+    m_authenticated = obj["authenticated"].integer();
+    m_initialized = true;
+
     return true;
 }
 
 bool
-gss_eap_shib_attr_source::init(void)
+gss_eap_shib_attr_provider::init(void)
 {
-    return ShibbolethResolver::init();
+    if (SPConfig::getConfig().getFeatures() == 0 &&
+        ShibbolethResolver::init() == false)
+        return false;
+
+    gss_eap_attr_ctx::registerProvider(ATTR_TYPE_LOCAL, createAttrContext);
+
+    return true;
 }
 
 void
-gss_eap_shib_attr_source::finalize(void)
+gss_eap_shib_attr_provider::finalize(void)
 {
+    gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_LOCAL);
     ShibbolethResolver::term();
 }
 
-gss_eap_attr_source *
-gss_eap_shib_attr_source::createAttrContext(void)
+OM_uint32
+gss_eap_shib_attr_provider::mapException(OM_uint32 *minor,
+                                         std::exception &e) const
 {
-    return new gss_eap_shib_attr_source;
+    if (typeid(e) == typeid(AttributeException))
+        *minor = GSSEAP_SHIB_ATTR_FAILURE;
+    else if (typeid(e) == typeid(AttributeExtractionException))
+        *minor = GSSEAP_SHIB_ATTR_EXTRACT_FAILURE;
+    else if (typeid(e) == typeid(AttributeFilteringException))
+        *minor = GSSEAP_SHIB_ATTR_FILTER_FAILURE;
+    else if (typeid(e) == typeid(AttributeResolutionException))
+        *minor = GSSEAP_SHIB_ATTR_RESOLVE_FAILURE;
+    else if (typeid(e) == typeid(ConfigurationException))
+        *minor = GSSEAP_SHIB_CONFIG_FAILURE;
+    else if (typeid(e) == typeid(ListenerException))
+        *minor = GSSEAP_SHIB_LISTENER_FAILURE;
+    else
+        return GSS_S_CONTINUE_NEEDED;
+
+    gssEapSaveStatusInfo(*minor, "%s", e.what());
+
+    return GSS_S_FAILURE;
 }
 
-Attribute *
-gss_eap_shib_attr_source::duplicateAttribute(const Attribute *src)
+gss_eap_attr_provider *
+gss_eap_shib_attr_provider::createAttrContext(void)
 {
-    Attribute *attribute;
+    return new gss_eap_shib_attr_provider;
+}
 
+Attribute *
+gss_eap_shib_attr_provider::duplicateAttribute(const Attribute *src)
+{
     DDF obj = src->marshall();
-    attribute = Attribute::unmarshall(obj);
+    Attribute *attribute = Attribute::unmarshall(obj);
     obj.destroy();
 
     return attribute;
 }
 
 vector <Attribute *>
-gss_eap_shib_attr_source::duplicateAttributes(const vector <Attribute *>src)
+gss_eap_shib_attr_provider::duplicateAttributes(const vector <Attribute *>src)
 {
     vector <Attribute *> dst;
 
@@ -396,3 +518,22 @@ gss_eap_shib_attr_source::duplicateAttributes(const vector <Attribute *>src)
 
     return dst;
 }
+
+OM_uint32
+gssEapLocalAttrProviderInit(OM_uint32 *minor)
+{
+    if (!gss_eap_shib_attr_provider::init()) {
+        *minor = GSSEAP_SHIB_INIT_FAILURE;
+        return GSS_S_FAILURE;
+    }
+    return GSS_S_COMPLETE;
+}
+
+OM_uint32
+gssEapLocalAttrProviderFinalize(OM_uint32 *minor)
+{
+    gss_eap_shib_attr_provider::finalize();
+
+    *minor = 0;
+    return GSS_S_COMPLETE;
+}