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