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