ldap: Don't use the backend's display name as identifier
[quassel.git] / src / core / ldapauthenticator.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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 "logger.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(0)
47 {
48 }
49
50
51 LdapAuthenticator::~LdapAuthenticator()
52 {
53     if (_connection != 0) {
54         ldap_unbind_ext(_connection, 0, 0);
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 QStringList LdapAuthenticator::setupKeys() const
87 {
88     // The parameters needed for LDAP.
89     QStringList keys;
90     keys << "Hostname"
91          << "Port"
92          << "Bind DN"
93          << "Bind Password"
94          << "Base DN"
95          << "Filter"
96          << "UID Attribute";
97     return keys;
98 }
99
100
101 QVariantMap LdapAuthenticator::setupDefaults() const
102 {
103     QVariantMap map;
104     map["Hostname"] = QVariant(QString("ldap://localhost"));
105     map["Port"] = QVariant(DEFAULT_LDAP_PORT);
106     map["UID Attribute"] = QVariant(QString("uid"));
107     return map;
108 }
109
110
111 void LdapAuthenticator::setAuthProperties(const QVariantMap &properties)
112 {
113     _hostName = properties["Hostname"].toString();
114     _port = properties["Port"].toInt();
115     _baseDN = properties["Base DN"].toString();
116     _filter = properties["Filter"].toString();
117     _bindDN = properties["Bind DN"].toString();
118     _bindPassword = properties["Bind Password"].toString();
119     _uidAttribute = properties["UID Attribute"].toString();
120 }
121
122 // TODO: this code is sufficiently general that in the future, perhaps an abstract
123 // class should be created implementing it.
124 // i.e. a provider that does its own thing and then pokes at the current storage
125 // through the default core method.
126 UserId LdapAuthenticator::validateUser(const QString &username, const QString &password)
127 {
128     bool result = ldapAuth(username, password);
129     if (!result) {
130         return UserId();
131     }
132
133     // If auth succeeds, but the user has not logged into quassel previously, make
134     // a new user for them and return that ID.
135     // Users created via LDAP have empty passwords, but authenticator column = LDAP.
136     // On the other hand, if auth succeeds and the user already exists, do a final
137     // cross-check to confirm we're using the right auth provider.
138     UserId quasselId = Core::validateUser(username, QString());
139     if (!quasselId.isValid()) {
140         return Core::addUser(username, QString(), backendId());
141     }
142     else if (!(Core::checkAuthProvider(quasselId, backendId()))) {
143         return 0;
144     }
145     return quasselId;
146 }
147
148
149 bool LdapAuthenticator::setup(const QVariantMap &settings)
150 {
151     setAuthProperties(settings);
152     bool status = ldapConnect();
153     return status;
154 }
155
156
157 Authenticator::State LdapAuthenticator::init(const QVariantMap &settings)
158 {
159     setAuthProperties(settings);
160
161     bool status = ldapConnect();
162     if (!status) {
163         quInfo() << qPrintable(backendId()) << "Authenticator cannot connect.";
164         return NotAvailable;
165     }
166
167     quInfo() << qPrintable(backendId()) << "Authenticator is ready.";
168     return IsReady;
169 }
170
171 // Method based on abustany LDAP quassel patch.
172 bool LdapAuthenticator::ldapConnect()
173 {
174     if (_connection != 0) {
175         ldapDisconnect();
176     }
177
178     int res, v = LDAP_VERSION3;
179
180     QString serverURI;
181     QByteArray serverURIArray;
182
183     // Convert info to hostname:port.
184     serverURI = _hostName + ":" + QString::number(_port);
185     serverURIArray = serverURI.toLocal8Bit();
186     res = ldap_initialize(&_connection, serverURIArray);
187
188     if (res != LDAP_SUCCESS) {
189         qWarning() << "Could not connect to LDAP server:" << ldap_err2string(res);
190         return false;
191     }
192
193     res = ldap_set_option(_connection, LDAP_OPT_PROTOCOL_VERSION, (void*)&v);
194
195     if (res != LDAP_SUCCESS) {
196         qWarning() << "Could not set LDAP protocol version to v3:" << ldap_err2string(res);
197         ldap_unbind_ext(_connection, 0, 0);
198         _connection = 0;
199         return false;
200     }
201
202     return true;
203 }
204
205
206 void LdapAuthenticator::ldapDisconnect()
207 {
208     if (_connection == 0) {
209         return;
210     }
211
212     ldap_unbind_ext(_connection, 0, 0);
213     _connection = 0;
214 }
215
216
217 bool LdapAuthenticator::ldapAuth(const QString &username, const QString &password)
218 {
219     if (password.isEmpty()) {
220         return false;
221     }
222
223     int res;
224
225     // Attempt to establish a connection.
226     if (_connection == 0) {
227         if (!ldapConnect()) {
228             return false;
229         }
230     }
231
232     struct berval cred;
233
234     // Convert some things to byte arrays as needed.
235     QByteArray bindPassword = _bindPassword.toLocal8Bit();
236     QByteArray bindDN = _bindDN.toLocal8Bit();
237     QByteArray baseDN = _baseDN.toLocal8Bit();
238     QByteArray uidAttribute = _uidAttribute.toLocal8Bit();
239
240     cred.bv_val = (bindPassword.size() > 0 ? bindPassword.data() : NULL);
241     cred.bv_len = bindPassword.size();
242
243     res = ldap_sasl_bind_s(_connection, bindDN.size() > 0 ? bindDN.constData() : 0, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
244
245     if (res != LDAP_SUCCESS) {
246         qWarning() << "Refusing connection from" << username << "(LDAP bind failed:" << ldap_err2string(res) << ")";
247         ldapDisconnect();
248         return false;
249     }
250
251     LDAPMessage *msg = NULL, *entry = NULL;
252
253     const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")";
254
255     res = ldap_search_ext_s(_connection, baseDN.constData(), LDAP_SCOPE_SUBTREE, ldapQuery.constData(), 0, 0, 0, 0, 0, 0, &msg);
256
257     if (res != LDAP_SUCCESS) {
258         qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")";
259         return false;
260     }
261
262     if (ldap_count_entries(_connection, msg) > 1) {
263         qWarning() << "Refusing connection from" << username << "(LDAP search returned more than one result)";
264         ldap_msgfree(msg);
265         return false;
266     }
267
268     entry = ldap_first_entry(_connection, msg);
269
270     if (entry == 0) {
271         qWarning() << "Refusing connection from" << username << "(LDAP search returned no results)";
272         ldap_msgfree(msg);
273         return false;
274     }
275
276     QByteArray passwordArray = password.toLocal8Bit();
277     cred.bv_val = passwordArray.data();
278     cred.bv_len = password.size();
279
280     char *userDN = ldap_get_dn(_connection, entry);
281
282     res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
283
284     if (res != LDAP_SUCCESS) {
285         qWarning() << "Refusing connection from" << username << "(LDAP authentication failed)";
286         ldap_memfree(userDN);
287         ldap_msgfree(msg);
288         return false;
289     }
290
291     // The original implementation had requiredAttributes. I have not included this code
292     // but it would be easy to re-add if someone wants this feature.
293     // Ben Rosser <bjr@acm.jhu.edu> (12/23/15).
294
295     ldap_memfree(userDN);
296     ldap_msgfree(msg);
297     return true;
298 }