cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / core / ldapauthenticator.cpp
index 9439a6b..89b390f 100644 (file)
@@ -1,5 +1,5 @@
 /***************************************************************************
- *   Copyright (C) 2005-2015 by the Quassel Project                        *
+ *   Copyright (C) 2005-2022 by the Quassel Project                        *
  *   devel@quassel-irc.org                                                 *
  *                                                                         *
  *   This program is free software; you can redistribute it and/or modify  *
 
 /* 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 "logger.h"
+#include "ldapescaper.h"
 #include "network.h"
 #include "quassel.h"
 
-// Link against LDAP.
+/* We should use openldap on windows if at all possible, rather than trying to
+ * write some kind of compatibility routine.
+#ifdef Q_CC_MSVC
+#include <windows.h>
+#include <winldap.h>
+#else*/
 #include <ldap.h>
+//#endif
 
-LdapAuthenticator::LdapAuthenticator(QObject *parent)
-    : Authenticator(parent),
-       _connection(0)
-{
-}
-
+LdapAuthenticator::LdapAuthenticator(QObject* parent)
+    : Authenticator(parent)
+    , _connection(nullptr)
+{}
 
 LdapAuthenticator::~LdapAuthenticator()
 {
-       if (_connection != 0)
-       {
-               ldap_unbind_ext(_connection, 0, 0);
+    if (_connection != nullptr) {
+        ldap_unbind_ext(_connection, nullptr, nullptr);
     }
 }
 
-
 bool LdapAuthenticator::isAvailable() const
 {
-    // XXX: probably this should test if we can speak to the LDAP server.
+    // FIXME: probably this should test if we can speak to the LDAP server.
     return true;
 }
 
-QString LdapAuthenticator::displayName() const
+QString LdapAuthenticator::backendId() const
 {
-    // We identify the backend to use for the monolithic core by its displayname.
+    // We identify the backend to use for the monolithic core by this identifier.
     // 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
+QString LdapAuthenticator::displayName() const
 {
-    return tr("Authenticate users using an LDAP server.");
+    return tr("LDAP");
 }
 
-QStringList LdapAuthenticator::setupKeys() const
+QString LdapAuthenticator::description() const
 {
-    // The parameters needed for LDAP.
-    QStringList keys;
-    keys << "Hostname"
-         << "Port"
-         << "Bind DN"
-         << "Bind Password"
-         << "Base DN"
-         << "Filter"
-         << "UID Attribute";
-    return keys;
+    return tr("Authenticate users using an LDAP server.");
 }
 
-QVariantMap LdapAuthenticator::setupDefaults() const
+QVariantList LdapAuthenticator::setupData() const
 {
-    QVariantMap map;
-    map["Hostname"] = QVariant(QString("ldap://localhost"));
-    map["Port"] = QVariant(DEFAULT_LDAP_PORT);
-    map["UID Attribute"] = QVariant(QString("uid"));
-    return map;
+    // The parameters needed for LDAP.
+    QVariantList data;
+    data << "Hostname" << tr("Hostname") << QString{"ldap://localhost"} << "Port" << tr("Port") << DEFAULT_LDAP_PORT << "BindDN"
+         << tr("Bind DN") << QString{} << "BindPassword" << tr("Bind Password") << QString{} << "BaseDN" << tr("Base DN") << QString{}
+         << "Filter" << tr("Filter") << QString{} << "UidAttribute" << tr("UID Attribute") << QString{"uid"};
+    return data;
 }
 
-void LdapAuthenticator::setConnectionProperties(const QVariantMap &properties)
+void LdapAuthenticator::setAuthProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment)
 {
-    _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();
+    if (loadFromEnvironment) {
+        _hostName = environment.value("AUTH_LDAP_HOSTNAME");
+        _port = environment.value("AUTH_LDAP_PORT").toInt();
+        _bindDN = environment.value("AUTH_LDAP_BIND_DN");
+        _bindPassword = environment.value("AUTH_LDAP_BIND_PASSWORD");
+        _baseDN = environment.value("AUTH_LDAP_BASE_DN");
+        _filter = environment.value("AUTH_LDAP_FILTER");
+        _uidAttribute = environment.value("AUTH_LDAP_UID_ATTRIBUTE");
+    }
+    else {
+        _hostName = properties["Hostname"].toString();
+        _port = properties["Port"].toInt();
+        _bindDN = properties["BindDN"].toString();
+        _bindPassword = properties["BindPassword"].toString();
+        _baseDN = properties["BaseDN"].toString();
+        _filter = properties["Filter"].toString();
+        _uidAttribute = properties["UidAttribute"].toString();
+    }
 }
 
-// XXX: this code is sufficiently general that in the future, perhaps an abstract
+// TODO: 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)
+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 result = ldapAuth(username, password);
+    if (!result) {
+        return {};
+    }
+
+    // LDAP is case-insensitive, thus we will lowercase the username, in spite of
+    // a better solution :(
+    const QString lUsername = username.toLower();
+
+    // 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 passwords, but authenticator column = LDAP.
+    // On the other hand, if auth succeeds and the user already exists, do a final
+    // cross-check to confirm we're using the right auth provider.
+    UserId quasselId = Core::getUserId(lUsername);
+    if (!quasselId.isValid()) {
+        return Core::addUser(lUsername, QString(), backendId());
+    }
+    else if (!(Core::checkAuthProvider(quasselId, backendId()))) {
+        return 0;
+    }
+    return quasselId;
 }
 
-bool LdapAuthenticator::setup(const QVariantMap &settings)
+bool LdapAuthenticator::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
 {
-       setConnectionProperties(settings);
-       bool status = ldapConnect();
-       return status;
+    setAuthProperties(settings, environment, loadFromEnvironment);
+    bool status = ldapConnect();
+    return status;
 }
 
-Authenticator::State LdapAuthenticator::init(const QVariantMap &settings)
+Authenticator::State LdapAuthenticator::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
 {
-       setConnectionProperties(settings);
-       
-       bool status = ldapConnect();
-       if (!status)
-       {
-               quInfo() << qPrintable(displayName()) << "Authenticator cannot connect.";
-               return NotAvailable;
-       }
-       
-       quInfo() << qPrintable(displayName()) << "Authenticator is ready.";
-       return IsReady;
+    setAuthProperties(settings, environment, loadFromEnvironment);
+
+    bool status = ldapConnect();
+    if (!status) {
+        qInfo() << qPrintable(backendId()) << "authenticator cannot connect.";
+        return NotAvailable;
+    }
+
+    qInfo() << qPrintable(backendId()) << "authenticator is ready.";
+    return IsReady;
 }
 
 // Method based on abustany LDAP quassel patch.
 bool LdapAuthenticator::ldapConnect()
 {
-    if (_connection != 0) {
+    if (_connection != nullptr) {
         ldapDisconnect();
     }
 
     int res, v = LDAP_VERSION3;
 
-       QString serverURI;
-       QByteArray serverURIArray;
-       
-       // Convert info to hostname:port.
-       serverURI = _hostName + ":" + QString::number(_port);
-       serverURIArray = serverURI.toLocal8Bit();
+    QString serverURI;
+    QByteArray serverURIArray;
+
+    // Convert info to hostname:port.
+    serverURI = _hostName + ":" + QString::number(_port);
+    serverURIArray = serverURI.toLocal8Bit();
     res = ldap_initialize(&_connection, serverURIArray);
 
+    qInfo() << "LDAP: Connecting to" << serverURI;
+
     if (res != LDAP_SUCCESS) {
         qWarning() << "Could not connect to LDAP server:" << ldap_err2string(res);
         return false;
@@ -175,8 +188,8 @@ bool LdapAuthenticator::ldapConnect()
 
     if (res != LDAP_SUCCESS) {
         qWarning() << "Could not set LDAP protocol version to v3:" << ldap_err2string(res);
-        ldap_unbind_ext(_connection, 0, 0);
-        _connection = 0;
+        ldap_unbind_ext(_connection, nullptr, nullptr);
+        _connection = nullptr;
         return false;
     }
 
@@ -185,15 +198,15 @@ bool LdapAuthenticator::ldapConnect()
 
 void LdapAuthenticator::ldapDisconnect()
 {
-    if (_connection == 0) {
+    if (_connection == nullptr) {
         return;
     }
 
-    ldap_unbind_ext(_connection, 0, 0);
-    _connection = 0;
+    ldap_unbind_ext(_connection, nullptr, nullptr);
+    _connection = nullptr;
 }
 
-bool LdapAuthenticator::ldapAuth(const QString &username, const QString &password)
+bool LdapAuthenticator::ldapAuth(const QString& username, const QString& password)
 {
     if (password.isEmpty()) {
         return false;
@@ -201,25 +214,25 @@ bool LdapAuthenticator::ldapAuth(const QString &username, const QString &passwor
 
     int res;
 
-       // Attempt to establish a connection.
-    if (_connection == 0) {
-        if (not ldapConnect()) {
+    // Attempt to establish a connection.
+    if (_connection == nullptr) {
+        if (!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);
+
+    // 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 = (bindPassword.size() > 0 ? bindPassword.data() : nullptr);
     cred.bv_len = bindPassword.size();
 
-    res = ldap_sasl_bind_s(_connection, bindDN.size() > 0 ? bindDN.constData() : 0, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
+    res = ldap_sasl_bind_s(_connection, bindDN.size() > 0 ? bindDN.constData() : nullptr, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr);
 
     if (res != LDAP_SUCCESS) {
         qWarning() << "Refusing connection from" << username << "(LDAP bind failed:" << ldap_err2string(res) << ")";
@@ -227,11 +240,21 @@ bool LdapAuthenticator::ldapAuth(const QString &username, const QString &passwor
         return false;
     }
 
-    LDAPMessage *msg = NULL, *entry = NULL;
+    LDAPMessage *msg = nullptr, *entry = nullptr;
 
-    const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")";
+    const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + LdapEscaper::escapeQuery(username).toLatin1() + ")" + _filter.toLocal8Bit() + ")";
 
-    res = ldap_search_ext_s(_connection, baseDN.constData(), LDAP_SCOPE_SUBTREE, ldapQuery.constData(), 0, 0, 0, 0, 0, 0, &msg);
+    res = ldap_search_ext_s(_connection,
+                            baseDN.constData(),
+                            LDAP_SCOPE_SUBTREE,
+                            ldapQuery.constData(),
+                            nullptr,
+                            0,
+                            nullptr,
+                            nullptr,
+                            nullptr,
+                            0,
+                            &msg);
 
     if (res != LDAP_SUCCESS) {
         qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")";
@@ -246,19 +269,19 @@ bool LdapAuthenticator::ldapAuth(const QString &username, const QString &passwor
 
     entry = ldap_first_entry(_connection, msg);
 
-    if (entry == 0) {
+    if (entry == nullptr) {
         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());
+    QByteArray passwordArray = password.toLocal8Bit();
+    cred.bv_val = passwordArray.data();
     cred.bv_len = password.size();
 
-    char *userDN = ldap_get_dn(_connection, entry);
+    charuserDN = ldap_get_dn(_connection, entry);
 
-    res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
+    res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr);
 
     if (res != LDAP_SUCCESS) {
         qWarning() << "Refusing connection from" << username << "(LDAP authentication failed)";
@@ -268,10 +291,10 @@ bool LdapAuthenticator::ldapAuth(const QString &username, const QString &passwor
     }
 
     // The original implementation had requiredAttributes. I have not included this code
-    // but it would be easy to re-add if someone wants this feature. 
+    // 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
+    return true;
+}