]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_ldapauth.cpp
5d4d90d44122fc1ed12ab9f2e91cc8d588e49922
[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 /* $ModDesc: Allow/Deny connections based upon answer from LDAP server */
39 /* $LinkerFlags: -lldap */
40
41 class ModuleLDAPAuth : public Module
42 {
43         LocalIntExt ldapAuthed;
44         LocalStringExt ldapVhost;
45         std::string base;
46         std::string attribute;
47         std::string ldapserver;
48         std::string allowpattern;
49         std::string killreason;
50         std::string username;
51         std::string password;
52         std::string vhost;
53         std::vector<std::string> whitelistedcidrs;
54         std::vector<std::pair<std::string, std::string> > requiredattributes;
55         int searchscope;
56         bool verbose;
57         bool useusername;
58         LDAP *conn;
59
60 public:
61         ModuleLDAPAuth()
62                 : ldapAuthed("ldapauth", this)
63                 , ldapVhost("ldapauth_vhost", this)
64         {
65                 conn = NULL;
66         }
67
68         void init()
69         {
70                 Implementation eventlist[] = { I_OnCheckReady, I_OnRehash,I_OnUserRegister, I_OnUserConnect };
71                 ServerInstance->Modules->Attach(eventlist, this, 4);
72                 OnRehash(NULL);
73         }
74
75         ~ModuleLDAPAuth()
76         {
77                 if (conn)
78                         ldap_unbind_ext(conn, NULL, NULL);
79         }
80
81         void OnRehash(User* user)
82         {
83                 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
84                 whitelistedcidrs.clear();
85                 requiredattributes.clear();
86
87                 base                    = tag->getString("baserdn");
88                 attribute               = tag->getString("attribute");
89                 ldapserver              = tag->getString("server");
90                 allowpattern    = tag->getString("allowpattern");
91                 killreason              = tag->getString("killreason");
92                 std::string scope       = tag->getString("searchscope");
93                 username                = tag->getString("binddn");
94                 password                = tag->getString("bindauth");
95                 vhost                   = tag->getString("host");
96                 verbose                 = tag->getBool("verbose");              /* Set to true if failed connects should be reported to operators */
97                 useusername             = tag->getBool("userfield");
98
99                 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
100
101                 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
102                 {
103                         std::string cidr = i->second->getString("cidr");
104                         if (!cidr.empty()) {
105                                 whitelistedcidrs.push_back(cidr);
106                         }
107                 }
108
109                 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
110
111                 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
112                 {
113                         const std::string attr = i->second->getString("attribute");
114                         const std::string val = i->second->getString("value");
115
116                         if (!attr.empty() && !val.empty())
117                                 requiredattributes.push_back(make_pair(attr, val));
118                 }
119
120                 if (scope == "base")
121                         searchscope = LDAP_SCOPE_BASE;
122                 else if (scope == "onelevel")
123                         searchscope = LDAP_SCOPE_ONELEVEL;
124                 else searchscope = LDAP_SCOPE_SUBTREE;
125
126                 Connect();
127         }
128
129         bool Connect()
130         {
131                 if (conn != NULL)
132                         ldap_unbind_ext(conn, NULL, NULL);
133                 int res, v = LDAP_VERSION3;
134                 res = ldap_initialize(&conn, ldapserver.c_str());
135                 if (res != LDAP_SUCCESS)
136                 {
137                         if (verbose)
138                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
139                         conn = NULL;
140                         return false;
141                 }
142
143                 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
144                 if (res != LDAP_SUCCESS)
145                 {
146                         if (verbose)
147                                 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
148                         ldap_unbind_ext(conn, NULL, NULL);
149                         conn = NULL;
150                         return false;
151                 }
152                 return true;
153         }
154
155         std::string SafeReplace(const std::string &text, std::map<std::string,
156                         std::string> &replacements)
157         {
158                 std::string result;
159                 result.reserve(MAXBUF);
160
161                 for (unsigned int i = 0; i < text.length(); ++i) {
162                         char c = text[i];
163                         if (c == '$') {
164                                 // find the first nonalpha
165                                 i++;
166                                 unsigned int start = i;
167
168                                 while (i < text.length() - 1 && isalpha(text[i + 1]))
169                                         ++i;
170
171                                 std::string key = text.substr(start, (i - start) + 1);
172                                 result.append(replacements[key]);
173                         } else {
174                                 result.push_back(c);
175                         }
176                 }
177
178            return result;
179         }
180
181         virtual void OnUserConnect(LocalUser *user)
182         {
183                 std::string* cc = ldapVhost.get(user);
184                 if (cc)
185                 {
186                         user->ChangeDisplayedHost(cc->c_str());
187                         ldapVhost.unset(user);
188                 }
189         }
190
191         ModResult OnUserRegister(LocalUser* user)
192         {
193                 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
194                 {
195                         ldapAuthed.set(user,1);
196                         return MOD_RES_PASSTHRU;
197                 }
198
199                 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
200                 {
201                         if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
202                         {
203                                 ldapAuthed.set(user,1);
204                                 return MOD_RES_PASSTHRU;
205                         }
206                 }
207
208                 if (!CheckCredentials(user))
209                 {
210                         ServerInstance->Users->QuitUser(user, killreason);
211                         return MOD_RES_DENY;
212                 }
213                 return MOD_RES_PASSTHRU;
214         }
215
216         bool CheckCredentials(LocalUser* user)
217         {
218                 if (conn == NULL)
219                         if (!Connect())
220                                 return false;
221
222                 if (user->password.empty())
223                 {
224                         if (verbose)
225                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
226                         return false;
227                 }
228
229                 int res;
230                 // bind anonymously if no bind DN and authentication are given in the config
231                 struct berval cred;
232                 cred.bv_val = const_cast<char*>(password.c_str());
233                 cred.bv_len = password.length();
234
235                 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
236                 {
237                         if (res == LDAP_SERVER_DOWN)
238                         {
239                                 // Attempt to reconnect if the connection dropped
240                                 if (verbose)
241                                         ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
242                                 Connect();
243                                 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
244                         }
245
246                         if (res != LDAP_SUCCESS)
247                         {
248                                 if (verbose)
249                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP bind failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
250                                 ldap_unbind_ext(conn, NULL, NULL);
251                                 conn = NULL;
252                                 return false;
253                         }
254                 }
255
256                 LDAPMessage *msg, *entry;
257                 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
258                 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
259                 {
260                         // Do a second search, based on password, if it contains a :
261                         // That is, PASS <user>:<password> will work.
262                         size_t pos = user->password.find(":");
263                         if (pos != std::string::npos)
264                         {
265                                 std::string cutpassword = user->password.substr(0, pos);
266                                 res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
267
268                                 if (res == LDAP_SUCCESS)
269                                 {
270                                         // Trim the user: prefix, leaving just 'pass' for later password check
271                                         user->password = user->password.substr(pos + 1);
272                                 }
273                         }
274
275                         // It may have found based on user:pass check above.
276                         if (res != LDAP_SUCCESS)
277                         {
278                                 if (verbose)
279                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
280                                 return false;
281                         }
282                 }
283                 if (ldap_count_entries(conn, msg) > 1)
284                 {
285                         if (verbose)
286                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
287                         ldap_msgfree(msg);
288                         return false;
289                 }
290                 if ((entry = ldap_first_entry(conn, msg)) == NULL)
291                 {
292                         if (verbose)
293                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
294                         ldap_msgfree(msg);
295                         return false;
296                 }
297                 cred.bv_val = (char*)user->password.data();
298                 cred.bv_len = user->password.length();
299                 if ((res = ldap_sasl_bind_s(conn, ldap_get_dn(conn, entry), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
300                 {
301                         if (verbose)
302                                 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
303                         ldap_msgfree(msg);
304                         return false;
305                 }
306
307                 if (!requiredattributes.empty())
308                 {
309                         bool authed = false;
310
311                         for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
312                         {
313                                 const std::string &attr = it->first;
314                                 const std::string &val = it->second;
315
316                                 struct berval attr_value;
317                                 attr_value.bv_val = const_cast<char*>(val.c_str());
318                                 attr_value.bv_len = val.length();
319
320                                 ServerInstance->Logs->Log("m_ldapauth", DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
321
322                                 authed = (ldap_compare_ext_s(conn, ldap_get_dn(conn, entry), attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
323
324                                 if (authed)
325                                         break;
326                         }
327
328                         if (!authed)
329                         {
330                                 if (verbose)
331                                         ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
332                                 ldap_msgfree(msg);
333                                 return false;
334                         }
335                 }
336
337                 if (!vhost.empty())
338                 {
339                         irc::commasepstream stream(ldap_get_dn(conn, entry));
340
341                         // mashed map of key:value parts of the DN
342                         std::map<std::string, std::string> dnParts;
343
344                         std::string dnPart;
345                         while (stream.GetToken(dnPart))
346                         {
347                                 std::string::size_type pos = dnPart.find('=');
348                                 if (pos == std::string::npos) // malformed
349                                         continue;
350
351                                 std::string key = dnPart.substr(0, pos);
352                                 std::string value = dnPart.substr(pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself
353                                 dnParts[key] = value;
354                         }
355
356                         // change host according to config key
357                         ldapVhost.set(user, SafeReplace(vhost, dnParts));
358                 }
359
360                 ldap_msgfree(msg);
361                 ldapAuthed.set(user,1);
362                 return true;
363         }
364
365         ModResult OnCheckReady(LocalUser* user)
366         {
367                 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
368         }
369
370         Version GetVersion()
371         {
372                 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
373         }
374
375 };
376
377 MODULE_INIT(ModuleLDAPAuth)