2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 Sadie Powell <sadie@witchery.services>
5 * Copyright (C) 2019 Robby <robby@chatbelgie.be>
6 * Copyright (C) 2014-2015 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2014 Thiago Crepaldi <thiago@thiagocrepaldi.com>
8 * Copyright (C) 2013-2014, 2017 Adam <Adam@anope.org>
10 * This file is part of InspIRCd. InspIRCd is free software: you can
11 * redistribute it and/or modify it under the terms of the GNU General Public
12 * License as published by the Free Software Foundation, version 2.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "modules/ldap.h"
30 std::string killreason;
34 LocalStringExt* vhosts;
35 std::vector<std::pair<std::string, std::string> > requiredattributes;
38 class BindInterface : public LDAPInterface
40 const std::string provider;
41 const std::string uid;
43 bool checkingAttributes;
47 static std::string SafeReplace(const std::string& text, std::map<std::string, std::string>& replacements)
50 result.reserve(text.length());
52 for (unsigned int i = 0; i < text.length(); ++i)
57 // find the first nonalpha
59 unsigned int start = i;
61 while (i < text.length() - 1 && isalpha(text[i + 1]))
64 std::string key(text, start, (i - start) + 1);
65 result.append(replacements[key]);
74 static void SetVHost(User* user, const std::string& DN)
78 irc::commasepstream stream(DN);
80 // mashed map of key:value parts of the DN
81 std::map<std::string, std::string> dnParts;
84 while (stream.GetToken(dnPart))
86 std::string::size_type pos = dnPart.find('=');
87 if (pos == std::string::npos) // malformed
90 std::string key(dnPart, 0, pos);
91 std::string value(dnPart, pos + 1, dnPart.length() - pos + 1); // +1s to skip the = itself
95 // change host according to config key
96 vhosts->set(user, SafeReplace(vhost, dnParts));
101 BindInterface(Module* c, const std::string& p, const std::string& u, const std::string& dn)
103 , provider(p), uid(u), DN(dn), checkingAttributes(false), passed(false), attrCount(0)
107 void OnResult(const LDAPResult& r) CXX11_OVERRIDE
109 User* user = ServerInstance->FindUUID(uid);
110 dynamic_reference<LDAPProvider> LDAP(me, provider);
114 if (!checkingAttributes || !--attrCount)
119 if (!checkingAttributes && requiredattributes.empty())
122 ServerInstance->SNO->WriteToSnoMask('c', "Successful connection from %s (dn=%s)", user->GetFullRealHost().c_str(), DN.c_str());
124 // We're done, there are no attributes to check
126 authed->set(user, 1);
132 // Already checked attributes?
133 if (checkingAttributes)
137 // Only one has to pass
141 ServerInstance->SNO->WriteToSnoMask('c', "Successful connection from %s (dn=%s)", user->GetFullRealHost().c_str(), DN.c_str());
144 authed->set(user, 1);
147 // Delete this if this is the last ref
154 // check required attributes
155 checkingAttributes = true;
157 for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
159 // Note that only one of these has to match for it to be success
160 const std::string& attr = it->first;
161 const std::string& val = it->second;
163 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
166 LDAP->Compare(this, DN, attr, val);
169 catch (LDAPException &ex)
172 ServerInstance->SNO->WriteToSnoMask('c', "Unable to compare attributes %s=%s: %s", attr.c_str(), val.c_str(), ex.GetReason().c_str());
180 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (dn=%s) (unable to validate attributes)", user->GetFullRealHost().c_str(), DN.c_str());
181 ServerInstance->Users->QuitUser(user, killreason);
186 void OnError(const LDAPResult& err) CXX11_OVERRIDE
188 if (checkingAttributes && --attrCount)
197 User* user = ServerInstance->FindUUID(uid);
201 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), err.getError().c_str());
202 ServerInstance->Users->QuitUser(user, killreason);
209 class SearchInterface : public LDAPInterface
211 const std::string provider;
212 const std::string uid;
215 SearchInterface(Module* c, const std::string& p, const std::string& u)
216 : LDAPInterface(c), provider(p), uid(u)
220 void OnResult(const LDAPResult& r) CXX11_OVERRIDE
222 LocalUser* user = IS_LOCAL(ServerInstance->FindUUID(uid));
223 dynamic_reference<LDAPProvider> LDAP(me, provider);
224 if (!LDAP || r.empty() || !user)
227 ServerInstance->Users->QuitUser(user, killreason);
234 const LDAPAttributes& a = r.get(0);
235 std::string bindDn = a.get("dn");
238 ServerInstance->Users->QuitUser(user, killreason);
243 LDAP->Bind(new BindInterface(this->creator, provider, uid, bindDn), bindDn, user->password);
245 catch (LDAPException& ex)
247 ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason());
252 void OnError(const LDAPResult& err) CXX11_OVERRIDE
254 ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: %s", err.getError().c_str());
255 User* user = ServerInstance->FindUUID(uid);
257 ServerInstance->Users->QuitUser(user, killreason);
262 class AdminBindInterface : public LDAPInterface
264 const std::string provider;
265 const std::string uuid;
266 const std::string base;
267 const std::string what;
270 AdminBindInterface(Module* c, const std::string& p, const std::string& u, const std::string& b, const std::string& w)
271 : LDAPInterface(c), provider(p), uuid(u), base(b), what(w)
275 void OnResult(const LDAPResult& r) CXX11_OVERRIDE
277 dynamic_reference<LDAPProvider> LDAP(me, provider);
282 LDAP->Search(new SearchInterface(this->creator, provider, uuid), base, what);
284 catch (LDAPException& ex)
286 ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason());
292 void OnError(const LDAPResult& err) CXX11_OVERRIDE
294 ServerInstance->SNO->WriteToSnoMask('a', "Error binding as manager to LDAP server: " + err.getError());
299 class ModuleLDAPAuth : public Module
301 dynamic_reference<LDAPProvider> LDAP;
302 LocalIntExt ldapAuthed;
303 LocalStringExt ldapVhost;
305 std::string attribute;
306 std::vector<std::string> allowpatterns;
307 std::vector<std::string> whitelistedcidrs;
313 , ldapAuthed("ldapauth", ExtensionItem::EXT_USER, this)
314 , ldapVhost("ldapauth_vhost", ExtensionItem::EXT_USER, this)
317 authed = &ldapAuthed;
321 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
323 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
324 whitelistedcidrs.clear();
325 requiredattributes.clear();
327 base = tag->getString("baserdn");
328 attribute = tag->getString("attribute");
329 killreason = tag->getString("killreason");
330 vhost = tag->getString("host");
331 // Set to true if failed connects should be reported to operators
332 verbose = tag->getBool("verbose");
333 useusername = tag->getBool("userfield");
335 LDAP.SetProvider("LDAP/" + tag->getString("dbid"));
337 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
339 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
341 std::string cidr = i->second->getString("cidr");
343 whitelistedcidrs.push_back(cidr);
347 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
349 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
351 const std::string attr = i->second->getString("attribute");
352 const std::string val = i->second->getString("value");
354 if (!attr.empty() && !val.empty())
355 requiredattributes.push_back(make_pair(attr, val));
358 std::string allowpattern = tag->getString("allowpattern");
359 irc::spacesepstream ss(allowpattern);
360 for (std::string more; ss.GetToken(more); )
362 allowpatterns.push_back(more);
366 void OnUserConnect(LocalUser *user) CXX11_OVERRIDE
368 std::string* cc = ldapVhost.get(user);
371 user->ChangeDisplayedHost(*cc);
372 ldapVhost.unset(user);
376 ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
378 for (std::vector<std::string>::const_iterator i = allowpatterns.begin(); i != allowpatterns.end(); ++i)
380 if (InspIRCd::Match(user->nick, *i))
382 ldapAuthed.set(user,1);
383 return MOD_RES_PASSTHRU;
387 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
389 if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
391 ldapAuthed.set(user,1);
392 return MOD_RES_PASSTHRU;
396 if (user->password.empty())
399 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (no password provided)", user->GetFullRealHost().c_str());
400 ServerInstance->Users->QuitUser(user, killreason);
407 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (unable to find LDAP provider)", user->GetFullRealHost().c_str());
408 ServerInstance->Users->QuitUser(user, killreason);
413 std::string::size_type pos = user->password.find(':');
414 if (pos != std::string::npos)
416 what = attribute + "=" + user->password.substr(0, pos);
418 // Trim the user: prefix, leaving just 'pass' for later password check
419 user->password = user->password.substr(pos + 1);
423 what = attribute + "=" + (useusername ? user->ident : user->nick);
428 LDAP->BindAsManager(new AdminBindInterface(this, LDAP.GetProvider(), user->uuid, base, what));
430 catch (LDAPException &ex)
432 ServerInstance->SNO->WriteToSnoMask('a', "LDAP exception: " + ex.GetReason());
433 ServerInstance->Users->QuitUser(user, killreason);
439 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
441 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
444 Version GetVersion() CXX11_OVERRIDE
446 return Version("Allows connecting users to be authenticated against an LDAP database.", VF_VENDOR);
450 MODULE_INIT(ModuleLDAPAuth)