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;
45 std::string attribute;
46 std::string ldapserver;
47 std::string allowpattern;
48 std::string killreason;
51 std::vector<std::string> whitelistedcidrs;
52 std::vector<std::pair<std::string, std::string> > requiredattributes;
59 ModuleLDAPAuth() : ldapAuthed("ldapauth", this)
66 Implementation eventlist[] = { I_OnCheckReady, I_OnRehash, I_OnUserRegister };
67 ServerInstance->Modules->Attach(eventlist, this, 3);
74 ldap_unbind_ext(conn, NULL, NULL);
77 void OnRehash(User* user)
79 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
80 whitelistedcidrs.clear();
81 requiredattributes.clear();
83 base = tag->getString("baserdn");
84 attribute = tag->getString("attribute");
85 ldapserver = tag->getString("server");
86 allowpattern = tag->getString("allowpattern");
87 killreason = tag->getString("killreason");
88 std::string scope = tag->getString("searchscope");
89 username = tag->getString("binddn");
90 password = tag->getString("bindauth");
91 verbose = tag->getBool("verbose"); /* Set to true if failed connects should be reported to operators */
92 useusername = tag->getBool("userfield");
94 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
96 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
98 std::string cidr = i->second->getString("cidr");
100 whitelistedcidrs.push_back(cidr);
104 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
106 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
108 const std::string attr = i->second->getString("attribute");
109 const std::string val = i->second->getString("value");
111 if (!attr.empty() && !val.empty())
112 requiredattributes.push_back(make_pair(attr, val));
116 searchscope = LDAP_SCOPE_BASE;
117 else if (scope == "onelevel")
118 searchscope = LDAP_SCOPE_ONELEVEL;
119 else searchscope = LDAP_SCOPE_SUBTREE;
127 ldap_unbind_ext(conn, NULL, NULL);
128 int res, v = LDAP_VERSION3;
129 res = ldap_initialize(&conn, ldapserver.c_str());
130 if (res != LDAP_SUCCESS)
133 ServerInstance->SNO->WriteToSnoMask('c', "LDAP connection failed: %s", ldap_err2string(res));
138 res = ldap_set_option(conn, LDAP_OPT_PROTOCOL_VERSION, (void *)&v);
139 if (res != LDAP_SUCCESS)
142 ServerInstance->SNO->WriteToSnoMask('c', "LDAP set protocol to v3 failed: %s", ldap_err2string(res));
143 ldap_unbind_ext(conn, NULL, NULL);
150 ModResult OnUserRegister(LocalUser* user)
152 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
154 ldapAuthed.set(user,1);
155 return MOD_RES_PASSTHRU;
158 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
160 if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
162 ldapAuthed.set(user,1);
163 return MOD_RES_PASSTHRU;
167 if (!CheckCredentials(user))
169 ServerInstance->Users->QuitUser(user, killreason);
172 return MOD_RES_PASSTHRU;
175 bool CheckCredentials(LocalUser* user)
181 if (user->password.empty())
184 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (No password provided)", user->GetFullRealHost().c_str());
189 // bind anonymously if no bind DN and authentication are given in the config
191 cred.bv_val = const_cast<char*>(password.c_str());
192 cred.bv_len = password.length();
194 if ((res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
196 if (res == LDAP_SERVER_DOWN)
198 // Attempt to reconnect if the connection dropped
200 ServerInstance->SNO->WriteToSnoMask('a', "LDAP server has gone away - reconnecting...");
202 res = ldap_sasl_bind_s(conn, username.c_str(), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
205 if (res != LDAP_SUCCESS)
208 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP bind failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
209 ldap_unbind_ext(conn, NULL, NULL);
215 LDAPMessage *msg, *entry;
216 std::string what = (attribute + "=" + (useusername ? user->ident : user->nick));
217 if ((res = ldap_search_ext_s(conn, base.c_str(), searchscope, what.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg)) != LDAP_SUCCESS)
219 // Do a second search, based on password, if it contains a :
220 // That is, PASS <user>:<password> will work.
221 size_t pos = user->password.find(":");
222 if (pos != std::string::npos)
224 std::string cutpassword = user->password.substr(0, pos);
225 res = ldap_search_ext_s(conn, base.c_str(), searchscope, cutpassword.c_str(), NULL, 0, NULL, NULL, NULL, 0, &msg);
227 if (res == LDAP_SUCCESS)
229 // Trim the user: prefix, leaving just 'pass' for later password check
230 user->password = user->password.substr(pos + 1);
234 // It may have found based on user:pass check above.
235 if (res != LDAP_SUCCESS)
238 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search failed: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
242 if (ldap_count_entries(conn, msg) > 1)
245 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned more than one result: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
249 if ((entry = ldap_first_entry(conn, msg)) == NULL)
252 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (LDAP search returned no results: %s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
256 cred.bv_val = (char*)user->password.data();
257 cred.bv_len = user->password.length();
258 if ((res = ldap_sasl_bind_s(conn, ldap_get_dn(conn, entry), LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL)) != LDAP_SUCCESS)
261 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), ldap_err2string(res));
266 if (!requiredattributes.empty())
270 for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
272 const std::string &attr = it->first;
273 const std::string &val = it->second;
275 struct berval attr_value;
276 attr_value.bv_val = const_cast<char*>(val.c_str());
277 attr_value.bv_len = val.length();
279 ServerInstance->Logs->Log("m_ldapauth", DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
281 authed = (ldap_compare_ext_s(conn, ldap_get_dn(conn, entry), attr.c_str(), &attr_value, NULL, NULL) == LDAP_COMPARE_TRUE);
290 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (Lacks required LDAP attributes)", user->GetFullRealHost().c_str());
297 ldapAuthed.set(user,1);
301 ModResult OnCheckReady(LocalUser* user)
303 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
308 return Version("Allow/Deny connections based upon answer from LDAP server", VF_VENDOR);
313 MODULE_INIT(ModuleLDAPAuth)