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())
121 // We're done, there are no attributes to check
123 authed->set(user, 1);
129 // Already checked attributes?
130 if (checkingAttributes)
134 // Only one has to pass
138 authed->set(user, 1);
141 // Delete this if this is the last ref
148 // check required attributes
149 checkingAttributes = true;
151 for (std::vector<std::pair<std::string, std::string> >::const_iterator it = requiredattributes.begin(); it != requiredattributes.end(); ++it)
153 // Note that only one of these has to match for it to be success
154 const std::string& attr = it->first;
155 const std::string& val = it->second;
157 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "LDAP compare: %s=%s", attr.c_str(), val.c_str());
160 LDAP->Compare(this, DN, attr, val);
163 catch (LDAPException &ex)
166 ServerInstance->SNO->WriteToSnoMask('c', "Unable to compare attributes %s=%s: %s", attr.c_str(), val.c_str(), ex.GetReason().c_str());
174 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (unable to validate attributes)", user->GetFullRealHost().c_str());
175 ServerInstance->Users->QuitUser(user, killreason);
180 void OnError(const LDAPResult& err) CXX11_OVERRIDE
182 if (checkingAttributes && --attrCount)
191 User* user = ServerInstance->FindUUID(uid);
195 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (%s)", user->GetFullRealHost().c_str(), err.getError().c_str());
196 ServerInstance->Users->QuitUser(user, killreason);
203 class SearchInterface : public LDAPInterface
205 const std::string provider;
206 const std::string uid;
209 SearchInterface(Module* c, const std::string& p, const std::string& u)
210 : LDAPInterface(c), provider(p), uid(u)
214 void OnResult(const LDAPResult& r) CXX11_OVERRIDE
216 LocalUser* user = IS_LOCAL(ServerInstance->FindUUID(uid));
217 dynamic_reference<LDAPProvider> LDAP(me, provider);
218 if (!LDAP || r.empty() || !user)
221 ServerInstance->Users->QuitUser(user, killreason);
228 const LDAPAttributes& a = r.get(0);
229 std::string bindDn = a.get("dn");
232 ServerInstance->Users->QuitUser(user, killreason);
237 LDAP->Bind(new BindInterface(this->creator, provider, uid, bindDn), bindDn, user->password);
239 catch (LDAPException& ex)
241 ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason());
246 void OnError(const LDAPResult& err) CXX11_OVERRIDE
248 ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: %s", err.getError().c_str());
249 User* user = ServerInstance->FindUUID(uid);
251 ServerInstance->Users->QuitUser(user, killreason);
256 class AdminBindInterface : public LDAPInterface
258 const std::string provider;
259 const std::string uuid;
260 const std::string base;
261 const std::string what;
264 AdminBindInterface(Module* c, const std::string& p, const std::string& u, const std::string& b, const std::string& w)
265 : LDAPInterface(c), provider(p), uuid(u), base(b), what(w)
269 void OnResult(const LDAPResult& r) CXX11_OVERRIDE
271 dynamic_reference<LDAPProvider> LDAP(me, provider);
276 LDAP->Search(new SearchInterface(this->creator, provider, uuid), base, what);
278 catch (LDAPException& ex)
280 ServerInstance->SNO->WriteToSnoMask('a', "Error searching LDAP server: " + ex.GetReason());
286 void OnError(const LDAPResult& err) CXX11_OVERRIDE
288 ServerInstance->SNO->WriteToSnoMask('a', "Error binding as manager to LDAP server: " + err.getError());
293 class ModuleLDAPAuth : public Module
295 dynamic_reference<LDAPProvider> LDAP;
296 LocalIntExt ldapAuthed;
297 LocalStringExt ldapVhost;
299 std::string attribute;
300 std::vector<std::string> allowpatterns;
301 std::vector<std::string> whitelistedcidrs;
307 , ldapAuthed("ldapauth", ExtensionItem::EXT_USER, this)
308 , ldapVhost("ldapauth_vhost", ExtensionItem::EXT_USER, this)
311 authed = &ldapAuthed;
315 void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
317 ConfigTag* tag = ServerInstance->Config->ConfValue("ldapauth");
318 whitelistedcidrs.clear();
319 requiredattributes.clear();
321 base = tag->getString("baserdn");
322 attribute = tag->getString("attribute");
323 killreason = tag->getString("killreason");
324 vhost = tag->getString("host");
325 // Set to true if failed connects should be reported to operators
326 verbose = tag->getBool("verbose");
327 useusername = tag->getBool("userfield");
329 LDAP.SetProvider("LDAP/" + tag->getString("dbid"));
331 ConfigTagList whitelisttags = ServerInstance->Config->ConfTags("ldapwhitelist");
333 for (ConfigIter i = whitelisttags.first; i != whitelisttags.second; ++i)
335 std::string cidr = i->second->getString("cidr");
337 whitelistedcidrs.push_back(cidr);
341 ConfigTagList attributetags = ServerInstance->Config->ConfTags("ldaprequire");
343 for (ConfigIter i = attributetags.first; i != attributetags.second; ++i)
345 const std::string attr = i->second->getString("attribute");
346 const std::string val = i->second->getString("value");
348 if (!attr.empty() && !val.empty())
349 requiredattributes.push_back(make_pair(attr, val));
352 std::string allowpattern = tag->getString("allowpattern");
353 irc::spacesepstream ss(allowpattern);
354 for (std::string more; ss.GetToken(more); )
356 allowpatterns.push_back(more);
360 void OnUserConnect(LocalUser *user) CXX11_OVERRIDE
362 std::string* cc = ldapVhost.get(user);
365 user->ChangeDisplayedHost(*cc);
366 ldapVhost.unset(user);
370 ModResult OnUserRegister(LocalUser* user) CXX11_OVERRIDE
372 for (std::vector<std::string>::const_iterator i = allowpatterns.begin(); i != allowpatterns.end(); ++i)
374 if (InspIRCd::Match(user->nick, *i))
376 ldapAuthed.set(user,1);
377 return MOD_RES_PASSTHRU;
381 for (std::vector<std::string>::iterator i = whitelistedcidrs.begin(); i != whitelistedcidrs.end(); i++)
383 if (InspIRCd::MatchCIDR(user->GetIPString(), *i, ascii_case_insensitive_map))
385 ldapAuthed.set(user,1);
386 return MOD_RES_PASSTHRU;
390 if (user->password.empty())
393 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (no password provided)", user->GetFullRealHost().c_str());
394 ServerInstance->Users->QuitUser(user, killreason);
401 ServerInstance->SNO->WriteToSnoMask('c', "Forbidden connection from %s (unable to find LDAP provider)", user->GetFullRealHost().c_str());
402 ServerInstance->Users->QuitUser(user, killreason);
407 std::string::size_type pos = user->password.find(':');
408 if (pos != std::string::npos)
410 what = attribute + "=" + user->password.substr(0, pos);
412 // Trim the user: prefix, leaving just 'pass' for later password check
413 user->password = user->password.substr(pos + 1);
417 what = attribute + "=" + (useusername ? user->ident : user->nick);
422 LDAP->BindAsManager(new AdminBindInterface(this, LDAP.GetProvider(), user->uuid, base, what));
424 catch (LDAPException &ex)
426 ServerInstance->SNO->WriteToSnoMask('a', "LDAP exception: " + ex.GetReason());
427 ServerInstance->Users->QuitUser(user, killreason);
433 ModResult OnCheckReady(LocalUser* user) CXX11_OVERRIDE
435 return ldapAuthed.get(user) ? MOD_RES_PASSTHRU : MOD_RES_DENY;
438 Version GetVersion() CXX11_OVERRIDE
440 return Version("Allow/deny connections based upon answers from an LDAP server", VF_VENDOR);
444 MODULE_INIT(ModuleLDAPAuth)