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