]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ldapauth.cpp
Issue #604, fix m_dnsbl, broken in accccc212cd4f08a3c5532b1ae7a17e76bac8718
[user/henk/code/inspircd.git] / src / modules / extra / m_ldapauth.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2011 Pierre Carrier <pierre@spotify.com>
5  *   Copyright (C) 2009-2010 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2009 Daniel De Graaf <danieldg@inspircd.org>
7  *   Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8  *   Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
9  *   Copyright (C) 2008 Dennis Friis <peavey@inspircd.org>
10  *   Copyright (C) 2007 Carsten Valdemar Munk <carsten.munk+inspircd@gmail.com>
11  *
12  * This file is part of InspIRCd.  InspIRCd is free software: you can
13  * redistribute it and/or modify it under the terms of the GNU General Public
14  * License as published by the Free Software Foundation, version 2.
15  *
16  * This program is distributed in the hope that it will be useful, but WITHOUT
17  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
19  * details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23  */
24
25
26 #include "inspircd.h"
27 #include "users.h"
28 #include "channels.h"
29 #include "modules.h"
30
31 #include <ldap.h>
32
33 #ifdef _WIN32
34 # pragma comment(lib, "ldap.lib")
35 # pragma comment(lib, "lber.lib")
36 #endif
37
38 /* $LinkerFlags: -lldap */
39
40 struct RAIILDAPString
41 {
42         char *str;
43
44         RAIILDAPString(char *Str)
45                 : str(Str)
46         {
47         }
48
49         ~RAIILDAPString()
50         {
51                 ldap_memfree(str);
52         }
53
54         operator char*()
55         {
56                 return str;
57         }
58
59         operator std::string()
60         {
61                 return str;
62         }
63 };
64
65 struct RAIILDAPMessage
66 {
67         RAIILDAPMessage()
68         {
69         }
70
71         ~RAIILDAPMessage()
72         {
73                 dealloc();
74         }
75
76         void dealloc()
77         {
78                 ldap_msgfree(msg);
79         }
80
81         operator LDAPMessage*()
82         {
83                 return msg;
84         }
85
86         LDAPMessage **operator &()
87         {
88                 return &msg;
89         }
90
91         LDAPMessage *msg;
92 };
93
94 class ModuleLDAPAuth : public Module
95 {
96         LocalIntExt ldapAuthed;
97         LocalStringExt ldapVhost;
98         std::string base;
99         std::string attribute;
100         std::string ldapserver;
101         std::string allowpattern;
102         std::string killreason;
103         std::string username;
104         std::string password;
105         std::string vhost;
106         std::vector<std::string> whitelistedcidrs;
107         std::vector<std::pair<std::string, std::string> > requiredattributes;
108         int searchscope;
109         bool verbose;
110         bool useusername;
111         LDAP *conn;
112
113 public:
114         ModuleLDAPAuth()
115                 : ldapAuthed("ldapauth", this)
116                 , ldapVhost("ldapauth_vhost", this)
117         {
118                 conn = NULL;
119         }
120
121         void init() CXX11_OVERRIDE
122         {
123                 ServerInstance->Modules->AddService(ldapAuthed);
124                 ServerInstance->Modules->AddService(ldapVhost);
125                 OnRehash(NULL);
126         }
127
128         ~ModuleLDAPAuth()
129         {
130                 if (conn)
131                         ldap_unbind_ext(conn, NULL, NULL);
132         }
133
134         void OnRehash(User* user) CXX11_OVERRIDE
135         {
136                 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
137                 whitelistedcidrs.clear();
138                 requiredattributes.clear();
139
140                 base                    = tag->getString("baserdn");
141                 attribute               = tag->getString("attribute");
142                 ldapserver              = tag->getString("server");
143                 allowpattern    = tag->getString("allowpattern");
144                 killreason              = tag->getString("killreason");
145                 std::string scope       = tag->getString("searchscope");
146                 username                = tag->getString("binddn");
147                 password                = tag->getString("bindauth");
148                 vhost                   = tag->getString("host");
149                 verbose                 = tag->getBool("verbose");              /* Set to true if failed connects should be reported to operators */
150                 useusername             = tag->getBool("userfield");
151
152                 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
153
154                 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
155                 {
156                         std::string cidr = i->second->getString("cidr");
157                         if (!cidr.empty()) {
158                                 whitelistedcidrs.push_back(cidr);
159                         }
160                 }
161
162                 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
163
164                 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
165                 {
166                         const std::string attr = i->second->getString("attribute");
167                         const std::string val = i->second->getString("value");
168
169                         if (!attr.empty() && !val.empty())
170                                 requiredattributes.push_back(make_pair(attr, val));
171                 }
172
173                 if (scope == "base")
174                         searchscope = LDAP_SCOPE_BASE;
175                 else if (scope == "onelevel")
176                         searchscope = LDAP_SCOPE_ONELEVEL;
177                 else searchscope = LDAP_SCOPE_SUBTREE;
178
179                 Connect();
180         }
181
182         bool Connect()
183         {
184                 if (conn != NULL)
185                         ldap_unbind_ext(conn, NULL, NULL);
186                 int res, v = LDAP_VERSION3;
187                 res = ldap_initialize(&conn, ldapserver.c_str());
188                 if (res != LDAP_SUCCESS)
189                 {
190                         if (verbose)
191                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
192                         conn = NULL;
193                         return false;
194                 }
195
196                 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
197                 if (res != LDAP_SUCCESS)
198                 {
199                         if (verbose)
200                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
201                         ldap_unbind_ext(conn, NULL, NULL);
202                         conn = NULL;
203                         return false;
204                 }
205                 return true;
206         }
207
208         std::string SafeReplace(const std::string &text, std::map<std::string,
209                         std::string> &replacements)
210         {
211                 std::string result;
212                 result.reserve(text.length());
213
214                 for (unsigned int i = 0; i < text.length(); ++i) {
215                         char c = text[i];
216                         if (c == '$') {
217                                 // find the first nonalpha
218                                 i++;
219                                 unsigned int start = i;
220
221                                 while (i < text.length() - 1 && isalpha(text[i + 1]))
222                                         ++i;
223
224                                 std::string key = text.substr(start, (i - start) + 1);
225                                 result.append(replacements[key]);
226                         } else {
227                                 result.push_back(c);
228                         }
229                 }
230
231            return result;
232         }
233
234         void OnUserConnect(LocalUser *user) CXX11_OVERRIDE
235         {
236                 std::string* cc = ldapVhost.get(user);
237                 if (cc)
238                 {
239                         user->ChangeDisplayedHost(cc->c_str());
240                         ldapVhost.unset(user);
241                 }
242         }
243
244         ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
245         {
246                 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
247                 {
248                         ldapAuthed.set(user,1);
249                         return MOD_RES_PASSTHRU;
250                 }
251
252                 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
253                 {
254                         if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
255                         {
256                                 ldapAuthed.set(user,1);
257                                 return MOD_RES_PASSTHRU;
258                         }
259                 }
260
261                 if (!CheckCredentials(user))
262                 {
263                         ServerInstance->Users->QuitUser(user, killreason);
264                         return MOD_RES_DENY;
265                 }
266                 return MOD_RES_PASSTHRU;
267         }
268
269         bool CheckCredentials(LocalUser* user)
270         {
271                 if (conn == NULL)
272                         if (!Connect())
273                                 return false;
274
275                 if (user->password.empty())
276                 {
277                         if (verbose)
278                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
279                         return false;
280                 }
281
282                 int res;
283                 // bind anonymously if no bind DN and authentication are given in the config
284                 struct berval cred;
285                 cred.bv_val = const_cast<char*>(password.c_str());
286                 cred.bv_len = password.length();
287
288                 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
289                 {
290                         if (res == LDAP_SERVER_DOWN)
291                         {
292                                 // Attempt to reconnect if the connection dropped
293                                 if (verbose)
294                                         ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
295                                 Connect();
296                                 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
297                         }
298
299                         if (res != LDAP_SUCCESS)
300                         {
301                                 if (verbose)
302                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP bind failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
303                                 ldap_unbind_ext(conn, NULL, NULL);
304                                 conn = NULL;
305                                 return false;
306                         }
307                 }
308
309                 RAIILDAPMessage msg;
310                 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
311                 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
312                 {
313                         // Do a second search, based on password, if it contains a :
314                         // That is, PASS <user>:<password> will work.
315                         size_t pos = user->password.find(":");
316                         if (pos != std::string::npos)
317                         {
318                                 // manpage says we must deallocate regardless of success or failure
319                                 // since we're about to do another query (and reset msg), first
320                                 // free the old one.
321                                 msg.dealloc();
322
323                                 std::string cutpassword = user->password.substr(0, pos);
324                                 res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
325
326                                 if (res == LDAP_SUCCESS)
327                                 {
328                                         // Trim the user: prefix, leaving just 'pass' for later password check
329                                         user->password = user->password.substr(pos + 1);
330                                 }
331                         }
332
333                         // It may have found based on user:pass check above.
334                         if (res != LDAP_SUCCESS)
335                         {
336                                 if (verbose)
337                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
338                                 return false;
339                         }
340                 }
341                 if (ldap_count_entries(conn, msg) > 1)
342                 {
343                         if (verbose)
344                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
345                         return false;
346                 }
347
348                 LDAPMessage *entry;
349                 if ((entry = ldap_first_entry(conn, msg)) == NULL)
350                 {
351                         if (verbose)
352                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
353                         return false;
354                 }
355                 cred.bv_val = (char*)user->password.data();
356                 cred.bv_len = user->password.length();
357                 RAIILDAPString DN(ldap_get_dn(conn, entry));
358                 if ((res = ldap_sasl_bind_s(conn, DN, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
359                 {
360                         if (verbose)
361                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
362                         return false;
363                 }
364
365                 if (!requiredattributes.empty())
366                 {
367                         bool authed = false;
368
369                         for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
370                         {
371                                 const std::string &attr = it->first;
372                                 const std::string &val = it->second;
373
374                                 struct berval attr_value;
375                                 attr_value.bv_val = const_cast<char*>(val.c_str());
376                                 attr_value.bv_len = val.length();
377
378                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
379
380                                 authed = (ldap_compare_ext_s(conn, DN, attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
381
382                                 if (authed)
383                                         break;
384                         }
385
386                         if (!authed)
387                         {
388                                 if (verbose)
389                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
390                                 return false;
391                         }
392                 }
393
394                 if (!vhost.empty())
395                 {
396                         irc::commasepstream stream(DN);
397
398                         // mashed map of key:value parts of the DN
399                         std::map<std::string, std::string> dnParts;
400
401                         std::string dnPart;
402                         while (stream.GetToken(dnPart))
403                         {
404                                 std::string::size_type pos = dnPart.find('=');
405                                 if (pos == std::string::npos) // malformed
406                                         continue;
407
408                                 std::string key = dnPart.substr(0, pos);
409                                 std::string value = dnPart.substr(pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself
410                                 dnParts[key] = value;
411                         }
412
413                         // change host according to config key
414                         ldapVhost.set(user, SafeReplace(vhost, dnParts));
415                 }
416
417                 ldapAuthed.set(user,1);
418                 return true;
419         }
420
421         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
422         {
423                 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
424         }
425
426         Version GetVersion() CXX11_OVERRIDE
427         {
428                 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
429         }
430 };
431
432 MODULE_INIT(ModuleLDAPAuth)