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 /* $LinkerFlags: -lldap */
44 RAIILDAPString(char *Str)
59 operator std::string()
65 struct RAIILDAPMessage
81 operator LDAPMessage*()
86 LDAPMessage **operator &()
94 class ModuleLDAPAuth : public Module
96 LocalIntExt ldapAuthed;
97 LocalStringExt ldapVhost;
99 std::string attribute;
100 std::string ldapserver;
101 std::string allowpattern;
102 std::string killreason;
103 std::string username;
104 std::string password;
106 std::vector<std::string> whitelistedcidrs;
107 std::vector<std::pair<std::string, std::string> > requiredattributes;
115 : ldapAuthed("ldapauth", this)
116 , ldapVhost("ldapauth_vhost", this)
124 ldap_unbind_ext(conn, NULL, NULL);
127 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
129 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
130 whitelistedcidrs.clear();
131 requiredattributes.clear();
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");
145 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
147 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
149 std::string cidr = i->second->getString("cidr");
151 whitelistedcidrs.push_back(cidr);
155 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
157 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
159 const std::string attr = i->second->getString("attribute");
160 const std::string val = i->second->getString("value");
162 if (!attr.empty() && !val.empty())
163 requiredattributes.push_back(make_pair(attr, val));
167 searchscope = LDAP_SCOPE_BASE;
168 else if (scope == "onelevel")
169 searchscope = LDAP_SCOPE_ONELEVEL;
170 else searchscope = LDAP_SCOPE_SUBTREE;
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)
184 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
189 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
190 if (res != LDAP_SUCCESS)
193 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
194 ldap_unbind_ext(conn, NULL, NULL);
201 std::string SafeReplace(const std::string &text, std::map<std::string,
202 std::string> &replacements)
205 result.reserve(text.length());
207 for (unsigned int i = 0; i < text.length(); ++i) {
210 // find the first nonalpha
212 unsigned int start = i;
214 while (i < text.length() - 1 && isalpha(text[i + 1]))
217 std::string key = text.substr(start, (i - start) + 1);
218 result.append(replacements[key]);
227 void OnUserConnect(LocalUser *user) CXX11_OVERRIDE
229 std::string* cc = ldapVhost.get(user);
232 user->ChangeDisplayedHost(cc->c_str());
233 ldapVhost.unset(user);
237 ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
239 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
241 ldapAuthed.set(user,1);
242 return MOD_RES_PASSTHRU;
245 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
247 if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
249 ldapAuthed.set(user,1);
250 return MOD_RES_PASSTHRU;
254 if (!CheckCredentials(user))
256 ServerInstance->Users->QuitUser(user, killreason);
259 return MOD_RES_PASSTHRU;
262 bool CheckCredentials(LocalUser* user)
268 if (user->password.empty())
271 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
276 // bind anonymously if no bind DN and authentication are given in the config
278 cred.bv_val = const_cast<char*>(password.c_str());
279 cred.bv_len = password.length();
281 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
283 if (res == LDAP_SERVER_DOWN)
285 // Attempt to reconnect if the connection dropped
287 ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
289 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
292 if (res != LDAP_SUCCESS)
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);
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)
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)
311 // manpage says we must deallocate regardless of success or failure
312 // since we're about to do another query (and reset msg), first
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);
319 if (res == LDAP_SUCCESS)
321 // Trim the user: prefix, leaving just 'pass' for later password check
322 user->password = user->password.substr(pos + 1);
326 // It may have found based on user:pass check above.
327 if (res != LDAP_SUCCESS)
330 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
334 if (ldap_count_entries(conn, msg) > 1)
337 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
342 if ((entry = ldap_first_entry(conn, msg)) == NULL)
345 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
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)
354 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
358 if (!requiredattributes.empty())
362 for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
364 const std::string &attr = it->first;
365 const std::string &val = it->second;
367 struct berval attr_value;
368 attr_value.bv_val = const_cast<char*>(val.c_str());
369 attr_value.bv_len = val.length();
371 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
373 authed = (ldap_compare_ext_s(conn, DN, attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
382 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
389 irc::commasepstream stream(DN);
391 // mashed map of key:value parts of the DN
392 std::map<std::string, std::string> dnParts;
395 while (stream.GetToken(dnPart))
397 std::string::size_type pos = dnPart.find('=');
398 if (pos == std::string::npos) // malformed
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;
406 // change host according to config key
407 ldapVhost.set(user, SafeReplace(vhost, dnParts));
410 ldapAuthed.set(user,1);
414 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
416 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
419 Version GetVersion() CXX11_OVERRIDE
421 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
425 MODULE_INIT(ModuleLDAPAuth)