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