]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ldapauth.cpp
Replace OnRehash() with ReadConfig() that is called on boot, on module load and on...
[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         }
126
127         ~ModuleLDAPAuth()
128         {
129                 if (conn)
130                         ldap_unbind_ext(conn, NULL, NULL);
131         }
132
133         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
134         {
135                 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
136                 whitelistedcidrs.clear();
137                 requiredattributes.clear();
138
139                 base                    = tag->getString("baserdn");
140                 attribute               = tag->getString("attribute");
141                 ldapserver              = tag->getString("server");
142                 allowpattern    = tag->getString("allowpattern");
143                 killreason              = tag->getString("killreason");
144                 std::string scope       = tag->getString("searchscope");
145                 username                = tag->getString("binddn");
146                 password                = tag->getString("bindauth");
147                 vhost                   = tag->getString("host");
148                 verbose                 = tag->getBool("verbose");              /* Set to true if failed connects should be reported to operators */
149                 useusername             = tag->getBool("userfield");
150
151                 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
152
153                 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
154                 {
155                         std::string cidr = i->second->getString("cidr");
156                         if (!cidr.empty()) {
157                                 whitelistedcidrs.push_back(cidr);
158                         }
159                 }
160
161                 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
162
163                 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
164                 {
165                         const std::string attr = i->second->getString("attribute");
166                         const std::string val = i->second->getString("value");
167
168                         if (!attr.empty() && !val.empty())
169                                 requiredattributes.push_back(make_pair(attr, val));
170                 }
171
172                 if (scope == "base")
173                         searchscope = LDAP_SCOPE_BASE;
174                 else if (scope == "onelevel")
175                         searchscope = LDAP_SCOPE_ONELEVEL;
176                 else searchscope = LDAP_SCOPE_SUBTREE;
177
178                 Connect();
179         }
180
181         bool Connect()
182         {
183                 if (conn != NULL)
184                         ldap_unbind_ext(conn, NULL, NULL);
185                 int res, v = LDAP_VERSION3;
186                 res = ldap_initialize(&conn, ldapserver.c_str());
187                 if (res != LDAP_SUCCESS)
188                 {
189                         if (verbose)
190                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
191                         conn = NULL;
192                         return false;
193                 }
194
195                 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
196                 if (res != LDAP_SUCCESS)
197                 {
198                         if (verbose)
199                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
200                         ldap_unbind_ext(conn, NULL, NULL);
201                         conn = NULL;
202                         return false;
203                 }
204                 return true;
205         }
206
207         std::string SafeReplace(const std::string &text, std::map<std::string,
208                         std::string> &replacements)
209         {
210                 std::string result;
211                 result.reserve(text.length());
212
213                 for (unsigned int i = 0; i < text.length(); ++i) {
214                         char c = text[i];
215                         if (c == '$') {
216                                 // find the first nonalpha
217                                 i++;
218                                 unsigned int start = i;
219
220                                 while (i < text.length() - 1 && isalpha(text[i + 1]))
221                                         ++i;
222
223                                 std::string key = text.substr(start, (i - start) + 1);
224                                 result.append(replacements[key]);
225                         } else {
226                                 result.push_back(c);
227                         }
228                 }
229
230            return result;
231         }
232
233         void OnUserConnect(LocalUser *user) CXX11_OVERRIDE
234         {
235                 std::string* cc = ldapVhost.get(user);
236                 if (cc)
237                 {
238                         user->ChangeDisplayedHost(cc->c_str());
239                         ldapVhost.unset(user);
240                 }
241         }
242
243         ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
244         {
245                 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
246                 {
247                         ldapAuthed.set(user,1);
248                         return MOD_RES_PASSTHRU;
249                 }
250
251                 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
252                 {
253                         if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
254                         {
255                                 ldapAuthed.set(user,1);
256                                 return MOD_RES_PASSTHRU;
257                         }
258                 }
259
260                 if (!CheckCredentials(user))
261                 {
262                         ServerInstance->Users->QuitUser(user, killreason);
263                         return MOD_RES_DENY;
264                 }
265                 return MOD_RES_PASSTHRU;
266         }
267
268         bool CheckCredentials(LocalUser* user)
269         {
270                 if (conn == NULL)
271                         if (!Connect())
272                                 return false;
273
274                 if (user->password.empty())
275                 {
276                         if (verbose)
277                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
278                         return false;
279                 }
280
281                 int res;
282                 // bind anonymously if no bind DN and authentication are given in the config
283                 struct berval cred;
284                 cred.bv_val = const_cast<char*>(password.c_str());
285                 cred.bv_len = password.length();
286
287                 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
288                 {
289                         if (res == LDAP_SERVER_DOWN)
290                         {
291                                 // Attempt to reconnect if the connection dropped
292                                 if (verbose)
293                                         ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
294                                 Connect();
295                                 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
296                         }
297
298                         if (res != LDAP_SUCCESS)
299                         {
300                                 if (verbose)
301                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP bind failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
302                                 ldap_unbind_ext(conn, NULL, NULL);
303                                 conn = NULL;
304                                 return false;
305                         }
306                 }
307
308                 RAIILDAPMessage msg;
309                 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
310                 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
311                 {
312                         // Do a second search, based on password, if it contains a :
313                         // That is, PASS <user>:<password> will work.
314                         size_t pos = user->password.find(":");
315                         if (pos != std::string::npos)
316                         {
317                                 // manpage says we must deallocate regardless of success or failure
318                                 // since we're about to do another query (and reset msg), first
319                                 // free the old one.
320                                 msg.dealloc();
321
322                                 std::string cutpassword = user->password.substr(0, pos);
323                                 res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
324
325                                 if (res == LDAP_SUCCESS)
326                                 {
327                                         // Trim the user: prefix, leaving just 'pass' for later password check
328                                         user->password = user->password.substr(pos + 1);
329                                 }
330                         }
331
332                         // It may have found based on user:pass check above.
333                         if (res != LDAP_SUCCESS)
334                         {
335                                 if (verbose)
336                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
337                                 return false;
338                         }
339                 }
340                 if (ldap_count_entries(conn, msg) > 1)
341                 {
342                         if (verbose)
343                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
344                         return false;
345                 }
346
347                 LDAPMessage *entry;
348                 if ((entry = ldap_first_entry(conn, msg)) == NULL)
349                 {
350                         if (verbose)
351                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
352                         return false;
353                 }
354                 cred.bv_val = (char*)user->password.data();
355                 cred.bv_len = user->password.length();
356                 RAIILDAPString DN(ldap_get_dn(conn, entry));
357                 if ((res = ldap_sasl_bind_s(conn, DN, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
358                 {
359                         if (verbose)
360                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
361                         return false;
362                 }
363
364                 if (!requiredattributes.empty())
365                 {
366                         bool authed = false;
367
368                         for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
369                         {
370                                 const std::string &attr = it->first;
371                                 const std::string &val = it->second;
372
373                                 struct berval attr_value;
374                                 attr_value.bv_val = const_cast<char*>(val.c_str());
375                                 attr_value.bv_len = val.length();
376
377                                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
378
379                                 authed = (ldap_compare_ext_s(conn, DN, attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
380
381                                 if (authed)
382                                         break;
383                         }
384
385                         if (!authed)
386                         {
387                                 if (verbose)
388                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
389                                 return false;
390                         }
391                 }
392
393                 if (!vhost.empty())
394                 {
395                         irc::commasepstream stream(DN);
396
397                         // mashed map of key:value parts of the DN
398                         std::map<std::string, std::string> dnParts;
399
400                         std::string dnPart;
401                         while (stream.GetToken(dnPart))
402                         {
403                                 std::string::size_type pos = dnPart.find('=');
404                                 if (pos == std::string::npos) // malformed
405                                         continue;
406
407                                 std::string key = dnPart.substr(0, pos);
408                                 std::string value = dnPart.substr(pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself
409                                 dnParts[key] = value;
410                         }
411
412                         // change host according to config key
413                         ldapVhost.set(user, SafeReplace(vhost, dnParts));
414                 }
415
416                 ldapAuthed.set(user,1);
417                 return true;
418         }
419
420         ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
421         {
422                 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
423         }
424
425         Version GetVersion() CXX11_OVERRIDE
426         {
427                 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
428         }
429 };
430
431 MODULE_INIT(ModuleLDAPAuth)