2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
34 # pragma comment(lib, "ldap.lib")
35 # pragma comment(lib, "lber.lib")
38 /* $ModDesc: Allow/Deny connections based upon answer from LDAP server */
39 /* $LinkerFlags: -lldap */
45 RAIILDAPString(char *Str)
60 operator std::string()
66 struct RAIILDAPMessage
82 operator LDAPMessage*()
87 LDAPMessage **operator &()
95 class ModuleLDAPAuth : public Module
97 LocalIntExt ldapAuthed;
98 LocalStringExt ldapVhost;
100 std::string attribute;
101 std::string ldapserver;
102 std::string allowpattern;
103 std::string killreason;
104 std::string username;
105 std::string password;
107 std::vector<std::string> whitelistedcidrs;
108 std::vector<std::pair<std::string, std::string> > requiredattributes;
116 : ldapAuthed("ldapauth", this)
117 , ldapVhost("ldapauth_vhost", this)
124 ServerInstance->Modules->AddService(ldapAuthed);
125 ServerInstance->Modules->AddService(ldapVhost);
126 Implementation eventlist[] = { I_OnCheckReady, I_OnRehash,I_OnUserRegister, I_OnUserConnect };
127 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
134 ldap_unbind_ext(conn, NULL, NULL);
137 void OnRehash(User* user)
139 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
140 whitelistedcidrs.clear();
141 requiredattributes.clear();
143 base = tag->getString("baserdn");
144 attribute = tag->getString("attribute");
145 ldapserver = tag->getString("server");
146 allowpattern = tag->getString("allowpattern");
147 killreason = tag->getString("killreason");
148 std::string scope = tag->getString("searchscope");
149 username = tag->getString("binddn");
150 password = tag->getString("bindauth");
151 vhost = tag->getString("host");
152 verbose = tag->getBool("verbose"); /* Set to true if failed connects should be reported to operators */
153 useusername = tag->getBool("userfield");
155 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
157 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
159 std::string cidr = i->second->getString("cidr");
161 whitelistedcidrs.push_back(cidr);
165 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
167 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
169 const std::string attr = i->second->getString("attribute");
170 const std::string val = i->second->getString("value");
172 if (!attr.empty() && !val.empty())
173 requiredattributes.push_back(make_pair(attr, val));
177 searchscope = LDAP_SCOPE_BASE;
178 else if (scope == "onelevel")
179 searchscope = LDAP_SCOPE_ONELEVEL;
180 else searchscope = LDAP_SCOPE_SUBTREE;
188 ldap_unbind_ext(conn, NULL, NULL);
189 int res, v = LDAP_VERSION3;
190 res = ldap_initialize(&conn, ldapserver.c_str());
191 if (res != LDAP_SUCCESS)
194 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
199 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
200 if (res != LDAP_SUCCESS)
203 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
204 ldap_unbind_ext(conn, NULL, NULL);
211 std::string SafeReplace(const std::string &text, std::map<std::string,
212 std::string> &replacements)
215 result.reserve(MAXBUF);
217 for (unsigned int i = 0; i < text.length(); ++i) {
220 // find the first nonalpha
222 unsigned int start = i;
224 while (i < text.length() - 1 && isalpha(text[i + 1]))
227 std::string key = text.substr(start, (i - start) + 1);
228 result.append(replacements[key]);
237 virtual void OnUserConnect(LocalUser *user)
239 std::string* cc = ldapVhost.get(user);
242 user->ChangeDisplayedHost(cc->c_str());
243 ldapVhost.unset(user);
247 ModResult OnUserRegister(LocalUser* user)
249 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
251 ldapAuthed.set(user,1);
252 return MOD_RES_PASSTHRU;
255 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
257 if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
259 ldapAuthed.set(user,1);
260 return MOD_RES_PASSTHRU;
264 if (!CheckCredentials(user))
266 ServerInstance->Users->QuitUser(user, killreason);
269 return MOD_RES_PASSTHRU;
272 bool CheckCredentials(LocalUser* user)
278 if (user->password.empty())
281 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
286 // bind anonymously if no bind DN and authentication are given in the config
288 cred.bv_val = const_cast<char*>(password.c_str());
289 cred.bv_len = password.length();
291 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
293 if (res == LDAP_SERVER_DOWN)
295 // Attempt to reconnect if the connection dropped
297 ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
299 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
302 if (res != LDAP_SUCCESS)
305 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP bind failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
306 ldap_unbind_ext(conn, NULL, NULL);
313 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
314 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
316 // Do a second search, based on password, if it contains a :
317 // That is, PASS <user>:<password> will work.
318 size_t pos = user->password.find(":");
319 if (pos != std::string::npos)
321 // manpage says we must deallocate regardless of success or failure
322 // since we're about to do another query (and reset msg), first
326 std::string cutpassword = user->password.substr(0, pos);
327 res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
329 if (res == LDAP_SUCCESS)
331 // Trim the user: prefix, leaving just 'pass' for later password check
332 user->password = user->password.substr(pos + 1);
336 // It may have found based on user:pass check above.
337 if (res != LDAP_SUCCESS)
340 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
344 if (ldap_count_entries(conn, msg) > 1)
347 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
352 if ((entry = ldap_first_entry(conn, msg)) == NULL)
355 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
358 cred.bv_val = (char*)user->password.data();
359 cred.bv_len = user->password.length();
360 RAIILDAPString DN(ldap_get_dn(conn, entry));
361 if ((res = ldap_sasl_bind_s(conn, DN, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
364 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
368 if (!requiredattributes.empty())
372 for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
374 const std::string &attr = it->first;
375 const std::string &val = it->second;
377 struct berval attr_value;
378 attr_value.bv_val = const_cast<char*>(val.c_str());
379 attr_value.bv_len = val.length();
381 ServerInstance->Logs->Log("m_ldapauth", DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
383 authed = (ldap_compare_ext_s(conn, DN, attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
392 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
399 irc::commasepstream stream(DN);
401 // mashed map of key:value parts of the DN
402 std::map<std::string, std::string> dnParts;
405 while (stream.GetToken(dnPart))
407 std::string::size_type pos = dnPart.find('=');
408 if (pos == std::string::npos) // malformed
411 std::string key = dnPart.substr(0, pos);
412 std::string value = dnPart.substr(pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself
413 dnParts[key] = value;
416 // change host according to config key
417 ldapVhost.set(user, SafeReplace(vhost, dnParts));
420 ldapAuthed.set(user,1);
424 ModResult OnCheckReady(LocalUser* user)
426 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
431 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
436 MODULE_INIT(ModuleLDAPAuth)