Make authenticator changes to protocol backwards-compatible
[quassel.git] / src / core / ldapauthenticator.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2015 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 // Link against LDAP.
36 #include <ldap.h>
37
38 LdapAuthenticator::LdapAuthenticator(QObject *parent)
39     : Authenticator(parent),
40     _connection(0)
41 {
42 }
43
44
45 LdapAuthenticator::~LdapAuthenticator()
46 {
47     if (_connection != 0)
48     {
49         ldap_unbind_ext(_connection, 0, 0);
50     }
51 }
52
53
54 bool LdapAuthenticator::isAvailable() const
55 {
56     // XXX: probably this should test if we can speak to the LDAP server.
57     return true;
58 }
59
60 QString LdapAuthenticator::displayName() const
61 {
62     // We identify the backend to use for the monolithic core by its displayname.
63     // so only change this string if you _really_ have to and make sure the core
64     // setup for the mono client still works ;)
65     return QString("LDAP");
66 }
67
68 QString LdapAuthenticator::description() const
69 {
70     return tr("Authenticate users using an LDAP server.");
71 }
72
73 QStringList LdapAuthenticator::setupKeys() const
74 {
75     // The parameters needed for LDAP.
76     QStringList keys;
77     keys << "Hostname"
78          << "Port"
79          << "Bind DN"
80          << "Bind Password"
81          << "Base DN"
82          << "Filter"
83          << "UID Attribute";
84     return keys;
85 }
86
87 QVariantMap LdapAuthenticator::setupDefaults() const
88 {
89     QVariantMap map;
90     map["Hostname"] = QVariant(QString("ldap://localhost"));
91     map["Port"] = QVariant(DEFAULT_LDAP_PORT);
92     map["UID Attribute"] = QVariant(QString("uid"));
93     return map;
94 }
95
96 void LdapAuthenticator::setConnectionProperties(const QVariantMap &properties)
97 {
98     _hostName = properties["Hostname"].toString();
99     _port = properties["Port"].toInt();
100     _baseDN = properties["Base DN"].toString();
101     _filter = properties["Filter"].toString();
102     _bindDN = properties["Bind DN"].toString();
103     _bindPassword = properties["Bind Password"].toString();
104     _uidAttribute = properties["UID Attribute"].toString();
105 }
106
107 // XXX: this code is sufficiently general that in the future, perhaps an abstract
108 // class should be created implementing it.
109 // i.e. a provider that does its own thing and then pokes at the current storage
110 // through the default core method.
111 UserId LdapAuthenticator::validateUser(const QString &username, const QString &password)
112 {
113     bool result = ldapAuth(username, password);
114     if (!result)
115     {
116         return UserId();
117     }
118
119     // If auth succeeds, but the user has not logged into quassel previously, make
120     // a new user for them and return that ID.
121     // Users created via LDAP have empty usernames.
122     UserId quasselID = Core::validateUser(username, QString());
123     if (!quasselID.isValid())
124     {
125         return Core::addUser(username, QString());
126     }
127     return quasselID;
128 }
129
130 bool LdapAuthenticator::setup(const QVariantMap &settings)
131 {
132     setConnectionProperties(settings);
133     bool status = ldapConnect();
134     return status;
135 }
136
137 Authenticator::State LdapAuthenticator::init(const QVariantMap &settings)
138 {
139     setConnectionProperties(settings);
140
141     bool status = ldapConnect();
142     if (!status)
143     {
144         quInfo() << qPrintable(displayName()) << "Authenticator cannot connect.";
145         return NotAvailable;
146     }
147
148     quInfo() << qPrintable(displayName()) << "Authenticator is ready.";
149     return IsReady;
150 }
151
152 // Method based on abustany LDAP quassel patch.
153 bool LdapAuthenticator::ldapConnect()
154 {
155     if (_connection != 0) {
156         ldapDisconnect();
157     }
158
159     int res, v = LDAP_VERSION3;
160
161     QString serverURI;
162     QByteArray serverURIArray;
163
164     // Convert info to hostname:port.
165     serverURI = _hostName + ":" + QString::number(_port);
166     serverURIArray = serverURI.toLocal8Bit();
167     res = ldap_initialize(&_connection, serverURIArray);
168
169     if (res != LDAP_SUCCESS) {
170         qWarning() << "Could not connect to LDAP server:" << ldap_err2string(res);
171         return false;
172     }
173
174     res = ldap_set_option(_connection, LDAP_OPT_PROTOCOL_VERSION, (void*)&v);
175
176     if (res != LDAP_SUCCESS) {
177         qWarning() << "Could not set LDAP protocol version to v3:" << ldap_err2string(res);
178         ldap_unbind_ext(_connection, 0, 0);
179         _connection = 0;
180         return false;
181     }
182
183     return true;
184 }
185
186 void LdapAuthenticator::ldapDisconnect()
187 {
188     if (_connection == 0) {
189         return;
190     }
191
192     ldap_unbind_ext(_connection, 0, 0);
193     _connection = 0;
194 }
195
196 bool LdapAuthenticator::ldapAuth(const QString &username, const QString &password)
197 {
198     if (password.isEmpty()) {
199         return false;
200     }
201
202     int res;
203
204     // Attempt to establish a connection.
205     if (_connection == 0) {
206         if (not ldapConnect()) {
207             return false;
208         }
209     }
210
211     struct berval cred;
212
213     // Convert some things to byte arrays as needed.
214     QByteArray bindPassword = _bindPassword.toLocal8Bit();
215     QByteArray bindDN = _bindDN.toLocal8Bit();
216     QByteArray baseDN = _baseDN.toLocal8Bit();
217     QByteArray uidAttribute = _uidAttribute.toLocal8Bit();
218
219     cred.bv_val = const_cast<char*>(bindPassword.size() > 0 ? bindPassword.constData() : NULL);
220     cred.bv_len = bindPassword.size();
221
222     res = ldap_sasl_bind_s(_connection, bindDN.size() > 0 ? bindDN.constData() : 0, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
223
224     if (res != LDAP_SUCCESS) {
225         qWarning() << "Refusing connection from" << username << "(LDAP bind failed:" << ldap_err2string(res) << ")";
226         ldapDisconnect();
227         return false;
228     }
229
230     LDAPMessage *msg = NULL, *entry = NULL;
231
232     const QByteArray ldapQuery = "(&(" + uidAttribute + '=' + username.toLocal8Bit() + ")" + _filter.toLocal8Bit() + ")";
233
234     res = ldap_search_ext_s(_connection, baseDN.constData(), LDAP_SCOPE_SUBTREE, ldapQuery.constData(), 0, 0, 0, 0, 0, 0, &msg);
235
236     if (res != LDAP_SUCCESS) {
237         qWarning() << "Refusing connection from" << username << "(LDAP search failed:" << ldap_err2string(res) << ")";
238         return false;
239     }
240
241     if (ldap_count_entries(_connection, msg) > 1) {
242         qWarning() << "Refusing connection from" << username << "(LDAP search returned more than one result)";
243         ldap_msgfree(msg);
244         return false;
245     }
246
247     entry = ldap_first_entry(_connection, msg);
248
249     if (entry == 0) {
250         qWarning() << "Refusing connection from" << username << "(LDAP search returned no results)";
251         ldap_msgfree(msg);
252         return false;
253     }
254
255     const QByteArray passwordArray = password.toLocal8Bit();
256     cred.bv_val = const_cast<char*>(passwordArray.constData());
257     cred.bv_len = password.size();
258
259     char *userDN = ldap_get_dn(_connection, entry);
260
261     res = ldap_sasl_bind_s(_connection, userDN, LDAP_SASL_SIMPLE, &cred, 0, 0, 0);
262
263     if (res != LDAP_SUCCESS) {
264         qWarning() << "Refusing connection from" << username << "(LDAP authentication failed)";
265         ldap_memfree(userDN);
266         ldap_msgfree(msg);
267         return false;
268     }
269
270     // The original implementation had requiredAttributes. I have not included this code
271     // but it would be easy to re-add if someone wants this feature.
272     // Ben Rosser <bjr@acm.jhu.edu> (12/23/15).
273
274     ldap_memfree(userDN);
275     ldap_msgfree(msg);
276     return true;
277 }