Add a flag to enable Qt deprecation warnings on Qt < 5.13
[quassel.git] / src / core / ldapauthenticator.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2019 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 /* This file contains an implementation of an LDAP Authenticator, as an example
22  * of what a custom external auth provider could do.
23  *
24  * It's based off of this pull request for quassel by abustany:
25  * https://github.com/quassel/quassel/pull/4/
26  *
27  */
28
29 #include "ldapauthenticator.h"
30
31 #include "network.h"
32 #include "quassel.h"
33
34 /* We should use openldap on windows if at all possible, rather than trying to
35  * write some kind of compatiblity routine.
36 #ifdef Q_CC_MSVC
37 #include <windows.h>
38 #include <winldap.h>
39 #else*/
40 #include <ldap.h>
41 //#endif
42
43 LdapAuthenticator::LdapAuthenticator(QObject* parent)
44     : Authenticator(parent)
45     , _connection(nullptr)
46 {}
47
48 LdapAuthenticator::~LdapAuthenticator()
49 {
50     if (_connection != nullptr) {
51         ldap_unbind_ext(_connection, nullptr, nullptr);
52     }
53 }
54
55 bool LdapAuthenticator::isAvailable() const
56 {
57     // FIXME: probably this should test if we can speak to the LDAP server.
58     return true;
59 }
60
61 QString LdapAuthenticator::backendId() const
62 {
63     // We identify the backend to use for the monolithic core by this identifier.
64     // so only change this string if you _really_ have to and make sure the core
65     // setup for the mono client still works ;)
66     return QString("LDAP");
67 }
68
69 QString LdapAuthenticator::displayName() const
70 {
71     return tr("LDAP");
72 }
73
74 QString LdapAuthenticator::description() const
75 {
76     return tr("Authenticate users using an LDAP server.");
77 }
78
79 QVariantList LdapAuthenticator::setupData() const
80 {
81     // The parameters needed for LDAP.
82     QVariantList data;
83     data << "Hostname" << tr("Hostname") << QString{"ldap://localhost"} << "Port" << tr("Port") << DEFAULT_LDAP_PORT << "BindDN"
84          << tr("Bind DN") << QString{} << "BindPassword" << tr("Bind Password") << QString{} << "BaseDN" << tr("Base DN") << QString{}
85          << "Filter" << tr("Filter") << QString{} << "UidAttribute" << tr("UID Attribute") << QString{"uid"};
86     return data;
87 }
88
89 void LdapAuthenticator::setAuthProperties(const QVariantMap& properties, const QProcessEnvironment& environment, bool loadFromEnvironment)
90 {
91     if (loadFromEnvironment) {
92         _hostName = environment.value("AUTH_LDAP_HOSTNAME");
93         _port = environment.value("AUTH_LDAP_PORT").toInt();
94         _bindDN = environment.value("AUTH_LDAP_BIND_DN");
95         _bindPassword = environment.value("AUTH_LDAP_BIND_PASSWORD");
96         _baseDN = environment.value("AUTH_LDAP_BASE_DN");
97         _filter = environment.value("AUTH_LDAP_FILTER");
98         _uidAttribute = environment.value("AUTH_LDAP_UID_ATTRIBUTE");
99     }
100     else {
101         _hostName = properties["Hostname"].toString();
102         _port = properties["Port"].toInt();
103         _bindDN = properties["BindDN"].toString();
104         _bindPassword = properties["BindPassword"].toString();
105         _baseDN = properties["BaseDN"].toString();
106         _filter = properties["Filter"].toString();
107         _uidAttribute = properties["UidAttribute"].toString();
108     }
109 }
110
111 // TODO: this code is sufficiently general that in the future, perhaps an abstract
112 // class should be created implementing it.
113 // i.e. a provider that does its own thing and then pokes at the current storage
114 // through the default core method.
115 UserId LdapAuthenticator::validateUser(const QString& username, const QString& password)
116 {
117     bool result = ldapAuth(username, password);
118     if (!result) {
119         return {};
120     }
121
122     // LDAP is case-insensitive, thus we will lowercase the username, in spite of
123     // a better solution :(
124     const QString lUsername = username.toLower();
125
126     // If auth succeeds, but the user has not logged into quassel previously, make
127     // a new user for them and return that ID.
128     // Users created via LDAP have empty passwords, but authenticator column = LDAP.
129     // On the other hand, if auth succeeds and the user already exists, do a final
130     // cross-check to confirm we're using the right auth provider.
131     UserId quasselId = Core::getUserId(lUsername);
132     if (!quasselId.isValid()) {
133         return Core::addUser(lUsername, QString(), backendId());
134     }
135     else if (!(Core::checkAuthProvider(quasselId, backendId()))) {
136         return 0;
137     }
138     return quasselId;
139 }
140
141 bool LdapAuthenticator::setup(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
142 {
143     setAuthProperties(settings, environment, loadFromEnvironment);
144     bool status = ldapConnect();
145     return status;
146 }
147
148 Authenticator::State LdapAuthenticator::init(const QVariantMap& settings, const QProcessEnvironment& environment, bool loadFromEnvironment)
149 {
150     setAuthProperties(settings, environment, loadFromEnvironment);
151
152     bool status = ldapConnect();
153     if (!status) {
154         qInfo() << qPrintable(backendId()) << "authenticator cannot connect.";
155         return NotAvailable;
156     }
157
158     qInfo() << qPrintable(backendId()) << "authenticator is ready.";
159     return IsReady;
160 }
161
162 // Method based on abustany LDAP quassel patch.
163 bool LdapAuthenticator::ldapConnect()
164 {
165     if (_connection != nullptr) {
166         ldapDisconnect();
167     }
168
169     int res, v = LDAP_VERSION3;
170
171     QString serverURI;
172     QByteArray serverURIArray;
173
174     // Convert info to hostname:port.
175     serverURI = _hostName + ":" + QString::number(_port);
176     serverURIArray = serverURI.toLocal8Bit();
177     res = ldap_initialize(&_connection, serverURIArray);
178
179     qInfo() << "LDAP: Connecting to" << serverURI;
180
181     if (res != LDAP_SUCCESS) {
182         qWarning() << "Could not connect to LDAP server:" << ldap_err2string(res);
183         return false;
184     }
185
186     res = ldap_set_option(_connection, LDAP_OPT_PROTOCOL_VERSION, (void*)&v);
187
188     if (res != LDAP_SUCCESS) {
189         qWarning() << "Could not set LDAP protocol version to v3:" << ldap_err2string(res);
190         ldap_unbind_ext(_connection, nullptr, nullptr);
191         _connection = nullptr;
192         return false;
193     }
194
195     return true;
196 }
197
198 void LdapAuthenticator::ldapDisconnect()
199 {
200     if (_connection == nullptr) {
201         return;
202     }
203
204     ldap_unbind_ext(_connection, nullptr, nullptr);
205     _connection = nullptr;
206 }
207
208 bool LdapAuthenticator::ldapAuth(const QString& username, const QString& password)
209 {
210     if (password.isEmpty()) {
211         return false;
212     }
213
214     int res;
215
216     // Attempt to establish a connection.
217     if (_connection == nullptr) {
218         if (!ldapConnect()) {
219             return false;
220         }
221     }
222
223     struct berval cred;
224
225     // Convert some things to byte arrays as needed.
226     QByteArray bindPassword = _bindPassword.toLocal8Bit();
227     QByteArray bindDN = _bindDN.toLocal8Bit();
228     QByteArray baseDN = _baseDN.toLocal8Bit();
229     QByteArray uidAttribute = _uidAttribute.toLocal8Bit();
230
231     cred.bv_val = (bindPassword.size() > 0 ? bindPassword.data() : nullptr);
232     cred.bv_len = bindPassword.size();
233
234     res = ldap_sasl_bind_s(_connection, bindDN.size() > 0 ? bindDN.constData() : nullptr, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr);
235
236     if (res != LDAP_SUCCESS) {
237         qWarning() << "Refusing connection from" << username << "(LDAP bind failed:" << ldap_err2string(res) << ")";
238         ldapDisconnect();
239         return false;
240     }
241
242     LDAPMessage *msg = nullptr, *entry = nullptr;
243
244     const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")";
245
246     res = ldap_search_ext_s(_connection,
247                             baseDN.constData(),
248                             LDAP_SCOPE_SUBTREE,
249                             ldapQuery.constData(),
250                             nullptr,
251                             0,
252                             nullptr,
253                             nullptr,
254                             nullptr,
255                             0,
256                             &msg);
257
258     if (res != LDAP_SUCCESS) {
259         qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")";
260         return false;
261     }
262
263     if (ldap_count_entries(_connection, msg) > 1) {
264         qWarning() << "Refusing connection from" << username << "(LDAP search returned more than one result)";
265         ldap_msgfree(msg);
266         return false;
267     }
268
269     entry = ldap_first_entry(_connection, msg);
270
271     if (entry == nullptr) {
272         qWarning() << "Refusing connection from" << username << "(LDAP search returned no results)";
273         ldap_msgfree(msg);
274         return false;
275     }
276
277     QByteArray passwordArray = password.toLocal8Bit();
278     cred.bv_val = passwordArray.data();
279     cred.bv_len = password.size();
280
281     char* userDN = ldap_get_dn(_connection, entry);
282
283     res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, nullptr, nullptr, nullptr);
284
285     if (res != LDAP_SUCCESS) {
286         qWarning() << "Refusing connection from" << username << "(LDAP authentication failed)";
287         ldap_memfree(userDN);
288         ldap_msgfree(msg);
289         return false;
290     }
291
292     // The original implementation had requiredAttributes. I have not included this code
293     // but it would be easy to re-add if someone wants this feature.
294     // Ben Rosser <bjr@acm.jhu.edu> (12/23/15).
295
296     ldap_memfree(userDN);
297     ldap_msgfree(msg);
298     return true;
299 }