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 */
41 class ModuleLDAPAuth : public Module
43 LocalIntExt ldapAuthed;
44 LocalStringExt ldapVhost;
46 std::string attribute;
47 std::string ldapserver;
48 std::string allowpattern;
49 std::string killreason;
53 std::vector<std::string> whitelistedcidrs;
54 std::vector<std::pair<std::string, std::string> > requiredattributes;
62 : ldapAuthed("ldapauth", this)
63 , ldapVhost("ldapauth_vhost", this)
70 Implementation eventlist[] = { I_OnCheckReady, I_OnRehash,I_OnUserRegister, I_OnUserConnect };
71 ServerInstance->Modules->Attach(eventlist, this, 4);
78 ldap_unbind_ext(conn, NULL, NULL);
81 void OnRehash(User* user)
83 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
84 whitelistedcidrs.clear();
85 requiredattributes.clear();
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");
99 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
101 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
103 std::string cidr = i->second->getString("cidr");
105 whitelistedcidrs.push_back(cidr);
109 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
111 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
113 const std::string attr = i->second->getString("attribute");
114 const std::string val = i->second->getString("value");
116 if (!attr.empty() && !val.empty())
117 requiredattributes.push_back(make_pair(attr, val));
121 searchscope = LDAP_SCOPE_BASE;
122 else if (scope == "onelevel")
123 searchscope = LDAP_SCOPE_ONELEVEL;
124 else searchscope = LDAP_SCOPE_SUBTREE;
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)
138 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
143 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
144 if (res != LDAP_SUCCESS)
147 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
148 ldap_unbind_ext(conn, NULL, NULL);
155 std::string SafeReplace(const std::string &text, std::map<std::string,
156 std::string> &replacements)
159 result.reserve(MAXBUF);
161 for (unsigned int i = 0; i < text.length(); ++i) {
164 // find the first nonalpha
166 unsigned int start = i;
168 while (i < text.length() - 1 && isalpha(text[i + 1]))
171 std::string key = text.substr(start, (i - start) + 1);
172 result.append(replacements[key]);
181 virtual void OnUserConnect(LocalUser *user)
183 std::string* cc = ldapVhost.get(user);
186 user->ChangeDisplayedHost(cc->c_str());
187 ldapVhost.unset(user);
191 ModResult OnUserRegister(LocalUser* user)
193 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
195 ldapAuthed.set(user,1);
196 return MOD_RES_PASSTHRU;
199 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
201 if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
203 ldapAuthed.set(user,1);
204 return MOD_RES_PASSTHRU;
208 if (!CheckCredentials(user))
210 ServerInstance->Users->QuitUser(user, killreason);
213 return MOD_RES_PASSTHRU;
216 bool CheckCredentials(LocalUser* user)
222 if (user->password.empty())
225 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
230 // bind anonymously if no bind DN and authentication are given in the config
232 cred.bv_val = const_cast<char*>(password.c_str());
233 cred.bv_len = password.length();
235 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
237 if (res == LDAP_SERVER_DOWN)
239 // Attempt to reconnect if the connection dropped
241 ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
243 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
246 if (res != LDAP_SUCCESS)
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);
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)
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)
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);
268 if (res == LDAP_SUCCESS)
270 // Trim the user: prefix, leaving just 'pass' for later password check
271 user->password = user->password.substr(pos + 1);
275 // It may have found based on user:pass check above.
276 if (res != LDAP_SUCCESS)
279 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
283 if (ldap_count_entries(conn, msg) > 1)
286 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
290 if ((entry = ldap_first_entry(conn, msg)) == NULL)
293 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
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)
302 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
307 if (!requiredattributes.empty())
311 for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
313 const std::string &attr = it->first;
314 const std::string &val = it->second;
316 struct berval attr_value;
317 attr_value.bv_val = const_cast<char*>(val.c_str());
318 attr_value.bv_len = val.length();
320 ServerInstance->Logs->Log("m_ldapauth", DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
322 authed = (ldap_compare_ext_s(conn, ldap_get_dn(conn, entry), attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
331 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
339 irc::commasepstream stream(ldap_get_dn(conn, entry));
341 // mashed map of key:value parts of the DN
342 std::map<std::string, std::string> dnParts;
345 while (stream.GetToken(dnPart))
347 std::string::size_type pos = dnPart.find('=');
348 if (pos == std::string::npos) // malformed
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;
356 // change host according to config key
357 ldapVhost.set(user, SafeReplace(vhost, dnParts));
361 ldapAuthed.set(user,1);
365 ModResult OnCheckReady(LocalUser* user)
367 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
372 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
377 MODULE_INIT(ModuleLDAPAuth)