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