Add LdapAuthenticator class for logging in users via LDAP
authorBen Rosser <rosser.bjr@gmail.com>
Wed, 23 Dec 2015 04:31:43 +0000 (23:31 -0500)
committerBen Rosser <rosser.bjr@gmail.com>
Sat, 27 May 2017 17:56:37 +0000 (13:56 -0400)
This is based on abustany's pull request #4, refactored into an
authenticator.

LDAP bindings now only get built if WITH_LDAP is set.

Added filters, also added -DHAVE_LDAP flag to compilation from cmake.

CMakeLists.txt
src/core/CMakeLists.txt
src/core/core.cpp
src/core/core.h
src/core/ldapauthenticator.cpp
src/core/ldapauthenticator.h

index 42f2ab3..f8c0a50 100644 (file)
@@ -135,7 +135,7 @@ endif()
 
 # LDAP Authentication (and other authentication backends).
 ####################################################################
 
 # LDAP Authentication (and other authentication backends).
 ####################################################################
-option(WITH_LDAP     "Enable LDAP authentication support if present on system" ON)
+option(WITH_LDAP     "Enable LDAP authentication support if present on system"  ON)
 
 # Setup CMake
 #####################################################################
 
 # Setup CMake
 #####################################################################
@@ -525,6 +525,9 @@ if(WITH_LDAP)
        if(LDAP_FOUND)
                message(STATUS "Enabling LDAP authentication support")
                set(HAVE_LDAP true)
        if(LDAP_FOUND)
                message(STATUS "Enabling LDAP authentication support")
                set(HAVE_LDAP true)
+               if(HAVE_LDAP)
+                       add_definitions(-DHAVE_LDAP)
+               endif(HAVE_LDAP)
        else(LDAP_FOUND)
                message(STATUS "Disabling LDAP authentication support")
        endif(LDAP_FOUND)
        else(LDAP_FOUND)
                message(STATUS "Disabling LDAP authentication support")
        endif(LDAP_FOUND)
index 8d2e9db..f2cbb48 100644 (file)
@@ -64,6 +64,13 @@ if (QCA2-QT5_FOUND)
     list(APPEND LIBS ${QCA2-QT5_LIBRARIES})
 endif()
 
     list(APPEND LIBS ${QCA2-QT5_LIBRARIES})
 endif()
 
+# Build with LDAP if told to do so.
+if(HAVE_LDAP)
+    include_directories(${LDAP_INCLUDE_DIR})
+    set(SOURCES ${SOURCES} ldapauthenticator.cpp)
+    set(MOC_HDRS ${MOC_HDRS} ldapauthenticator.h)
+endif(HAVE_LDAP)
+
 include_directories(${CMAKE_SOURCE_DIR}/src/common)
 
 set(CORE_RCS ${CORE_RCS} ${CMAKE_CURRENT_SOURCE_DIR}/sql.qrc)
 include_directories(${CMAKE_SOURCE_DIR}/src/common)
 
 set(CORE_RCS ${CORE_RCS} ${CMAKE_CURRENT_SOURCE_DIR}/sql.qrc)
@@ -73,3 +80,7 @@ add_library(mod_core STATIC ${SOURCES})
 qt_use_modules(mod_core Core Network Script Sql)
 
 target_link_libraries(mod_core mod_common ${LIBS})
 qt_use_modules(mod_core Core Network Script Sql)
 
 target_link_libraries(mod_core mod_common ${LIBS})
+
+if(HAVE_LDAP)
+    target_link_libraries(mod_core ${LDAP_LIBRARIES})
+endif(HAVE_LDAP)
index c145f5b..035cc41 100644 (file)
 #include "sqlitestorage.h"
 #include "util.h"
 
 #include "sqlitestorage.h"
 #include "util.h"
 
+// Currently building with LDAP bindings is optional.
+#ifdef HAVE_LDAP
+#include "ldapauthenticator.h"
+#endif
+
 // migration related
 #include <QFile>
 #ifdef Q_OS_WIN
 // migration related
 #include <QFile>
 #ifdef Q_OS_WIN
@@ -378,8 +383,10 @@ void Core::unregisterStorageBackend(Storage *backend)
 void Core::registerAuthenticatorBackends()
 {
     // Register new authentication backends here!
 void Core::registerAuthenticatorBackends()
 {
     // Register new authentication backends here!
-    //registerAuthenticatorBackend(new LdapAuthenticator(this));
-    registerAuthenticatorBackend(new SqlAuthenticator(this));
+       registerAuthenticatorBackend(new SqlAuthenticator(this));
+#ifdef HAVE_LDAP
+    registerAuthenticatorBackend(new LdapAuthenticator(this));
+#endif
     
 }
 
     
 }
 
@@ -392,7 +399,7 @@ bool Core::registerAuthenticatorBackend(Authenticator *authenticator)
        } else {
                authenticator->deleteLater();
                return false;
        } else {
                authenticator->deleteLater();
                return false;
-        }
+       }
 }
 
 void Core::unregisterAuthenticatorBackends()
 }
 
 void Core::unregisterAuthenticatorBackends()
index f63a32b..ff226a8 100644 (file)
@@ -84,6 +84,16 @@ public:
     static inline UserId authenticateUser(const QString &userName, const QString &password) {
         return instance()->_authenticator->validateUser(userName, password);
     }
     static inline UserId authenticateUser(const QString &userName, const QString &password) {
         return instance()->_authenticator->validateUser(userName, password);
     }
+    
+    //! Add a new user, exposed so auth providers can call this without being the storage.
+    /**
+     * \param userName The user's login name
+     * \param password The user's uncrypted password
+     * \return The user's ID if valid; 0 otherwise
+     */
+    static inline UserId addUser(const QString &userName, const QString &password) {
+        return instance()->_storage->addUser(userName, password);
+    }
 
     //! Change a user's password
     /**
 
     //! Change a user's password
     /**
index 40085e2..9439a6b 100644 (file)
  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
  ***************************************************************************/
 
  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
  ***************************************************************************/
 
+/* This file contains an implementation of an LDAP Authenticator, as an example
+ * of what a custom external auth provider could do.
+ * 
+ * It's based off of this pull request for quassel by abustany:
+ * https://github.com/quassel/quassel/pull/4/
+ * 
+ */
+
 #include "ldapauthenticator.h"
 
 #include "ldapauthenticator.h"
 
+#include "logger.h"
 #include "network.h"
 #include "quassel.h"
 
 #include "network.h"
 #include "quassel.h"
 
+// Link against LDAP.
+#include <ldap.h>
+
 LdapAuthenticator::LdapAuthenticator(QObject *parent)
 LdapAuthenticator::LdapAuthenticator(QObject *parent)
-    : LdapAuthenticator(parent),
-    _port(-1)
+    : Authenticator(parent),
+       _connection(0)
 {
 }
 
 
 LdapAuthenticator::~LdapAuthenticator()
 {
 {
 }
 
 
 LdapAuthenticator::~LdapAuthenticator()
 {
+       if (_connection != 0)
+       {
+               ldap_unbind_ext(_connection, 0, 0);
+    }
+}
+
+
+bool LdapAuthenticator::isAvailable() const
+{
+    // XXX: probably this should test if we can speak to the LDAP server.
+    return true;
+}
+
+QString LdapAuthenticator::displayName() const
+{
+    // We identify the backend to use for the monolithic core by its displayname.
+    // so only change this string if you _really_ have to and make sure the core
+    // setup for the mono client still works ;)
+    return QString("LDAP");
+}
+
+QString LdapAuthenticator::description() const
+{
+    return tr("Authenticate users using an LDAP server.");
+}
+
+QStringList LdapAuthenticator::setupKeys() const
+{
+    // The parameters needed for LDAP.
+    QStringList keys;
+    keys << "Hostname"
+         << "Port"
+         << "Bind DN"
+         << "Bind Password"
+         << "Base DN"
+         << "Filter"
+         << "UID Attribute";
+    return keys;
+}
+
+QVariantMap LdapAuthenticator::setupDefaults() const
+{
+    QVariantMap map;
+    map["Hostname"] = QVariant(QString("ldap://localhost"));
+    map["Port"] = QVariant(DEFAULT_LDAP_PORT);
+    map["UID Attribute"] = QVariant(QString("uid"));
+    return map;
+}
+
+void LdapAuthenticator::setConnectionProperties(const QVariantMap &properties)
+{
+    _hostName = properties["Hostname"].toString();
+    _port = properties["Port"].toInt();
+    _baseDN = properties["Base DN"].toString();
+       _filter = properties["Filter"].toString();
+    _bindDN = properties["Bind DN"].toString();
+    _bindPassword = properties["Bind Password"].toString();
+    _uidAttribute = properties["UID Attribute"].toString();
+}
+
+// XXX: this code is sufficiently general that in the future, perhaps an abstract
+// class should be created implementing it.
+// i.e. a provider that does its own thing and then pokes at the current storage
+// through the default core method.
+UserId LdapAuthenticator::validateUser(const QString &username, const QString &password)
+{
+       bool result = ldapAuth(username, password);
+       if (!result)
+       {
+               return UserId();
+       }
+
+       // If auth succeeds, but the user has not logged into quassel previously, make
+       // a new user for them and return that ID.
+       // Users created via LDAP have empty usernames.
+       UserId quasselID = Core::validateUser(username, QString());
+       if (!quasselID.isValid())
+       {
+               return Core::addUser(username, QString());
+       }
+       return quasselID;
+}
+
+bool LdapAuthenticator::setup(const QVariantMap &settings)
+{
+       setConnectionProperties(settings);
+       bool status = ldapConnect();
+       return status;
 }
 
 }
 
-// XXX: TODO: write the actual LDAP code.
\ No newline at end of file
+Authenticator::State LdapAuthenticator::init(const QVariantMap &settings)
+{
+       setConnectionProperties(settings);
+       
+       bool status = ldapConnect();
+       if (!status)
+       {
+               quInfo() << qPrintable(displayName()) << "Authenticator cannot connect.";
+               return NotAvailable;
+       }
+       
+       quInfo() << qPrintable(displayName()) << "Authenticator is ready.";
+       return IsReady;
+}
+
+// Method based on abustany LDAP quassel patch.
+bool LdapAuthenticator::ldapConnect()
+{
+    if (_connection != 0) {
+        ldapDisconnect();
+    }
+
+    int res, v = LDAP_VERSION3;
+
+       QString serverURI;
+       QByteArray serverURIArray;
+       
+       // Convert info to hostname:port.
+       serverURI = _hostName + ":" + QString::number(_port);
+       serverURIArray = serverURI.toLocal8Bit();
+    res = ldap_initialize(&_connection, serverURIArray);
+
+    if (res != LDAP_SUCCESS) {
+        qWarning() << "Could not connect to LDAP server:" << ldap_err2string(res);
+        return false;
+    }
+
+    res = ldap_set_option(_connection, LDAP_OPT_PROTOCOL_VERSION, (void*)&v);
+
+    if (res != LDAP_SUCCESS) {
+        qWarning() << "Could not set LDAP protocol version to v3:" << ldap_err2string(res);
+        ldap_unbind_ext(_connection, 0, 0);
+        _connection = 0;
+        return false;
+    }
+
+    return true;
+}
+
+void LdapAuthenticator::ldapDisconnect()
+{
+    if (_connection == 0) {
+        return;
+    }
+
+    ldap_unbind_ext(_connection, 0, 0);
+    _connection = 0;
+}
+
+bool LdapAuthenticator::ldapAuth(const QString &username, const QString &password)
+{
+    if (password.isEmpty()) {
+        return false;
+    }
+
+    int res;
+
+       // Attempt to establish a connection.
+    if (_connection == 0) {
+        if (not ldapConnect()) {
+            return false;
+        }
+    }
+
+    struct berval cred;
+       
+       // Convert some things to byte arrays as needed.
+       QByteArray bindPassword = _bindPassword.toLocal8Bit();
+       QByteArray bindDN = _bindDN.toLocal8Bit();
+       QByteArray baseDN = _baseDN.toLocal8Bit();
+       QByteArray uidAttribute = _uidAttribute.toLocal8Bit();
+
+    cred.bv_val = const_cast<char*>(bindPassword.size() > 0 ? bindPassword.constData() : NULL);
+    cred.bv_len = bindPassword.size();
+
+    res = ldap_sasl_bind_s(_connection, bindDN.size() > 0 ? bindDN.constData() : 0, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
+
+    if (res != LDAP_SUCCESS) {
+        qWarning() << "Refusing connection from" << username << "(LDAP bind failed:" << ldap_err2string(res) << ")";
+        ldapDisconnect();
+        return false;
+    }
+
+    LDAPMessage *msg = NULL, *entry = NULL;
+
+    const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")";
+
+    res = ldap_search_ext_s(_connection, baseDN.constData(), LDAP_SCOPE_SUBTREE, ldapQuery.constData(), 0, 0, 0, 0, 0, 0, &msg);
+
+    if (res != LDAP_SUCCESS) {
+        qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")";
+        return false;
+    }
+
+    if (ldap_count_entries(_connection, msg) > 1) {
+        qWarning() << "Refusing connection from" << username << "(LDAP search returned more than one result)";
+        ldap_msgfree(msg);
+        return false;
+    }
+
+    entry = ldap_first_entry(_connection, msg);
+
+    if (entry == 0) {
+        qWarning() << "Refusing connection from" << username << "(LDAP search returned no results)";
+        ldap_msgfree(msg);
+        return false;
+    }
+
+    const QByteArray passwordArray = password.toLocal8Bit();
+    cred.bv_val = const_cast<char*>(passwordArray.constData());
+    cred.bv_len = password.size();
+
+    char *userDN = ldap_get_dn(_connection, entry);
+
+    res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
+
+    if (res != LDAP_SUCCESS) {
+        qWarning() << "Refusing connection from" << username << "(LDAP authentication failed)";
+        ldap_memfree(userDN);
+        ldap_msgfree(msg);
+        return false;
+    }
+
+    // The original implementation had requiredAttributes. I have not included this code
+    // but it would be easy to re-add if someone wants this feature. 
+    // Ben Rosser <bjr@acm.jhu.edu> (12/23/15).
+    
+    ldap_memfree(userDN);
+    ldap_msgfree(msg);
+    return true;       
+}
\ No newline at end of file
index c6ee7f1..3b7c2aa 100644 (file)
  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
  ***************************************************************************/
 
  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
  ***************************************************************************/
 
+/* This file contains an implementation of an LDAP Authenticator, as an example
+ * of what a custom external auth provider could do.
+ * 
+ * It's based off of this pull request for quassel by abustany:
+ * https://github.com/quassel/quassel/pull/4/
+ * 
+ */
+
 #ifndef LDAPAUTHENTICATOR_H
 #define LDAPAUTHENTICATOR_H
 
 #include "authenticator.h"
 
 #ifndef LDAPAUTHENTICATOR_H
 #define LDAPAUTHENTICATOR_H
 
 #include "authenticator.h"
 
+#include "core.h"
+
+// Link against LDAP.
+#include <ldap.h>
+
+// Default LDAP server port.
+#define DEFAULT_LDAP_PORT 389
+
 class LdapAuthenticator : public Authenticator
 {
     Q_OBJECT
 class LdapAuthenticator : public Authenticator
 {
     Q_OBJECT
@@ -33,27 +49,40 @@ public:
 
 public slots:
     /* General */
 
 public slots:
     /* General */
-    virtual bool isAvailable() const;
-    virtual QString displayName() const;
-    virtual QString description() const;
+    bool isAvailable() const;
+    QString displayName() const;
+    QString description() const;
     virtual QStringList setupKeys() const;
     virtual QVariantMap setupDefaults() const;
     virtual QStringList setupKeys() const;
     virtual QVariantMap setupDefaults() const;
-
-    /* User handling */
-    virtual UserId getUserId(const QString &username);
  
  
-protected:
-       // Protecte methods for retrieving info about the LDAP connection.
-       inline virtual QString hostName() { return _hostName; }
-       inline virtual int port() { return _port; }
-       inline virtual QString bindDN() { return _bindDN; }
-       inline virtual QString baseDN() { return _baseDN; }
+    bool setup(const QVariantMap &settings = QVariantMap());
+    State init(const QVariantMap &settings = QVariantMap());
+    UserId validateUser(const QString &user, const QString &password);
        
        
+protected:
+    virtual void setConnectionProperties(const QVariantMap &properties);
+    bool ldapConnect();
+    void ldapDisconnect();
+    bool ldapAuth(const QString &username, const QString &password);
+
+    // Protected methods for retrieving info about the LDAP connection.
+    inline virtual QString hostName() { return _hostName; }
+    inline virtual int port() { return _port; }
+    inline virtual QString bindDN() { return _bindDN; }
+    inline virtual QString baseDN() { return _baseDN; }
+
 private:
     QString _hostName;
     int _port;
 private:
     QString _hostName;
     int _port;
-       QString _bindDN;
-       QString _baseDN;
+    QString _bindDN;
+    QString _baseDN;
+       QString _filter;
+    QString _bindPassword;
+    QString _uidAttribute;
+
+       // The actual connection object.
+       LDAP *_connection;
+       
 };
 
 
 };