X-Git-Url: https://git.netwichtig.de/gitweb/?a=blobdiff_plain;f=src%2Fmodules%2Fm_sqloper.cpp;h=c2e26b0364a7a6e7d818ba78cf10032c8f853a47;hb=HEAD;hp=66fb0550e824c363a96e2ebdf2ab12c0736e3a06;hpb=4e0997924d4052dede401fa1c0a1a91ae81c9aa3;p=user%2Fhenk%2Fcode%2Finspircd.git diff --git a/src/modules/m_sqloper.cpp b/src/modules/m_sqloper.cpp index 66fb0550e..c2e26b036 100644 --- a/src/modules/m_sqloper.cpp +++ b/src/modules/m_sqloper.cpp @@ -1,186 +1,256 @@ -/* +------------------------------------+ - * | Inspire Internet Relay Chat Daemon | - * +------------------------------------+ +/* + * InspIRCd -- Internet Relay Chat Daemon * - * InspIRCd: (C) 2002-2010 InspIRCd Development Team - * See: http://wiki.inspircd.org/Credits + * Copyright (C) 2019 B00mX0r + * Copyright (C) 2018 Dylan Frank + * Copyright (C) 2013-2014, 2018 Attila Molnar + * Copyright (C) 2013, 2017-2018, 2020 Sadie Powell + * Copyright (C) 2012, 2019 Robby + * Copyright (C) 2009-2010 Daniel De Graaf + * Copyright (C) 2009 Uli Schlachter + * Copyright (C) 2007-2008 Dennis Friis + * Copyright (C) 2005-2007, 2010 Craig Edwards * - * This program is free but copyrighted software; see - * the file COPYING for details. + * This file is part of InspIRCd. InspIRCd is free software: you can + * redistribute it and/or modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation, version 2. * - * --------------------------------------------------- + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ -#include "inspircd.h" -#include "sql.h" -#include "hash.h" - -/* $ModDesc: Allows storage of oper credentials in an SQL table */ -static bool OneOfMatches(const char* host, const char* ip, const std::string& hostlist) -{ - std::stringstream hl(hostlist); - std::string xhost; - while (hl >> xhost) - { - if (InspIRCd::Match(host, xhost, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(ip, xhost, ascii_case_insensitive_map)) - { - return true; - } - } - return false; -} +#include "inspircd.h" +#include "modules/sql.h" -class OpMeQuery : public SQLQuery +class OperQuery : public SQL::Query { public: + // This variable will store all the OPER blocks from the DB + std::vector& my_blocks; + /** We want to store the username and password if this is called during an /OPER, as we're responsible for /OPER post-DB fetch + * Note: uid will be empty if this DB update was not called as a result of a user command (i.e. /REHASH) + */ const std::string uid, username, password; - OpMeQuery(Module* me, const std::string& db, const std::string& q, const std::string& u, const std::string& un, const std::string& pw) - : SQLQuery(me, db, q), uid(u), username(un), password(pw) + OperQuery(Module* me, std::vector& mb, const std::string& u, const std::string& un, const std::string& pw) + : SQL::Query(me) + , my_blocks(mb) + , uid(u) + , username(un) + , password(pw) + { + } + OperQuery(Module* me, std::vector& mb) + : SQL::Query(me) + , my_blocks(mb) { - ServerInstance->Logs->Log("m_sqloper",DEBUG, "SQLOPER: db=%s query=\"%s\"", db.c_str(), q.c_str()); } - void OnResult(SQLResult& res) + void OnResult(SQL::Result& res) CXX11_OVERRIDE { - ServerInstance->Logs->Log("m_sqloper",DEBUG, "SQLOPER: result on db=%s for %s", dbid.c_str(), uid.c_str()); - User* user = ServerInstance->FindNick(uid); - if (!user) - return; + ServerConfig::OperIndex& oper_blocks = ServerInstance->Config->oper_blocks; + + // Remove our previous blocks from oper_blocks for a clean update + for (std::vector::const_iterator i = my_blocks.begin(); i != my_blocks.end(); ++i) + { + oper_blocks.erase(*i); + } + my_blocks.clear(); - // multiple rows may exist - SQLEntries row; + SQL::Row row; + // Iterate through DB results to create oper blocks from sqloper rows while (res.GetRow(row)) { -#if 0 - parameterlist cols; + std::vector cols; res.GetCols(cols); - std::vector* items; - reference tag = ConfigTag::create("oper", "", 0, items); - for(unsigned int i=0; i < cols.size(); i++) + // Create the oper tag as if we were the conf file. + ConfigItems* items; + reference tag = ConfigTag::create("oper", MODNAME, 0, items); + + /** Iterate through each column in the SQLOpers table. An infinite number of fields can be specified. + * Column 'x' with cell value 'y' will be the same as x=y in an OPER block in opers.conf. + */ + for (unsigned int i=0; i < cols.size(); ++i) { - if (!row[i].nul) - items->insert(std::make_pair(cols[i], row[i])); + if (!row[i].IsNull()) + (*items)[cols[i]] = row[i]; } -#else - if (OperUser(user, row[0], row[1])) - return; -#endif + const std::string name = tag->getString("name"); + + // Skip both duplicate sqloper blocks and sqloper blocks that attempt to override conf blocks. + if (oper_blocks.find(name) != oper_blocks.end()) + continue; + + const std::string type = tag->getString("type"); + ServerConfig::OperIndex::iterator tblk = ServerInstance->Config->OperTypes.find(type); + if (tblk == ServerInstance->Config->OperTypes.end()) + { + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "Sqloper block " + name + " has missing type " + type); + ServerInstance->SNO->WriteGlobalSno('a', "m_sqloper: Oper block %s has missing type %s", name.c_str(), type.c_str()); + continue; + } + + OperInfo* ifo = new OperInfo(type); + + ifo->type_block = tblk->second->type_block; + ifo->oper_block = tag; + ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end()); + oper_blocks[name] = ifo; + my_blocks.push_back(name); + row.clear(); + } + + // If this was done as a result of /OPER and not a config read + if (!uid.empty()) + { + // Now that we've updated the DB, call any other /OPER hooks and then call /OPER + OperExec(); } - ServerInstance->Logs->Log("m_sqloper",DEBUG, "SQLOPER: no matches for %s (checked %d rows)", uid.c_str(), res.Rows()); - // nobody succeeded... fall back to OPER - fallback(); } - void OnError(SQLerror& error) + void OnError(SQL::Error& error) CXX11_OVERRIDE { - ServerInstance->Logs->Log("m_sqloper",DEFAULT, "SQLOPER: query failed (%s)", error.Str()); - fallback(); + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "query failed (%s)", error.ToString()); + ServerInstance->SNO->WriteGlobalSno('a', "m_sqloper: Failed to update blocks from database"); + if (!uid.empty()) + { + // Fallback. We don't want to block a netadmin from /OPER + OperExec(); + } } - void fallback() + // Call /oper after placing all blocks from the SQL table into the config->oper_blocks list. + void OperExec() { User* user = ServerInstance->FindNick(uid); - if (!user) + LocalUser* localuser = IS_LOCAL(user); + // This should never be true + if (!localuser) return; - Command* oper_command = ServerInstance->Parser->GetHandler("OPER"); + Command* oper_command = ServerInstance->Parser.GetHandler("OPER"); if (oper_command) { - std::vector params; + CommandBase::Params params; params.push_back(username); params.push_back(password); - oper_command->Handle(params, user); - } - else - { - ServerInstance->Logs->Log("m_sqloper",SPARSE, "BUG: WHAT?! Why do we have no OPER command?!"); - } - } - - bool OperUser(User* user, const std::string &pattern, const std::string &type) - { - OperIndex::iterator iter = ServerInstance->Config->oper_blocks.find(" " + type); - if (iter == ServerInstance->Config->oper_blocks.end()) - { - ServerInstance->Logs->Log("m_sqloper",DEFAULT, "SQLOPER: bad type '%s' in returned row for oper %s", type.c_str(), username.c_str()); - return false; - } - OperInfo* ifo = iter->second; - std::string hostname(user->ident); + // Begin callback to other modules (i.e. sslinfo) now that we completed the DB fetch + ModResult MOD_RESULT; - hostname.append("@").append(user->host); + std::string origin = "OPER"; + FIRST_MOD_RESULT(OnPreCommand, MOD_RESULT, (origin, params, localuser, true)); + if (MOD_RESULT == MOD_RES_DENY) + return; - if (OneOfMatches(hostname.c_str(), user->GetIPString(), pattern.c_str())) + // Now handle /OPER. + ClientProtocol::TagMap tags; + oper_command->Handle(user, CommandBase::Params(params, tags)); + } + else { - /* Opertype and host match, looks like this is it. */ - - user->Oper(ifo); - return true; + ServerInstance->Logs->Log(MODNAME, LOG_SPARSE, "BUG: WHAT?! Why do we have no OPER command?!"); } - - return false; } }; class ModuleSQLOper : public Module { - std::string databaseid; + // Whether OperQuery is running + bool active; std::string query; - std::string hashtype; - dynamic_reference SQL; + // Stores oper blocks from DB + std::vector my_blocks; + dynamic_reference SQL; public: - ModuleSQLOper() : SQL(this, "SQL") {} - - void init() + ModuleSQLOper() + : active(false) + , SQL(this, "SQL") { - OnRehash(NULL); - - Implementation eventlist[] = { I_OnRehash, I_OnPreCommand }; - ServerInstance->Modules->Attach(eventlist, this, 2); } - void OnRehash(User* user) + void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE { + // Clear list of our blocks, as ConfigReader just wiped them anyway + my_blocks.clear(); + ConfigTag* tag = ServerInstance->Config->ConfValue("sqloper"); - databaseid = tag->getString("dbid"); - hashtype = tag->getString("hash"); - query = tag->getString("query", "SELECT hostname as host, type FROM ircd_opers WHERE username='$username' AND password='$password'"); + std::string dbid = tag->getString("dbid"); + if (dbid.empty()) + SQL.SetProvider("SQL"); + else + SQL.SetProvider("SQL/" + dbid); + + query = tag->getString("query", "SELECT * FROM ircd_opers WHERE active=1;", 1); + // Update sqloper list from the database. + GetOperBlocks(); } - ModResult OnPreCommand(std::string &command, std::vector ¶meters, LocalUser *user, bool validated, const std::string &original_line) + ~ModuleSQLOper() { - if (validated && command == "OPER" && parameters.size() == 2 && SQL) + // Remove all oper blocks that were from the DB + for (std::vector::const_iterator i = my_blocks.begin(); i != my_blocks.end(); ++i) { - LookupOper(user, parameters[0], parameters[1]); - /* Query is in progress, it will re-invoke OPER if needed */ - return MOD_RES_DENY; + ServerInstance->Config->oper_blocks.erase(*i); } - return MOD_RES_PASSTHRU; } - void LookupOper(User* user, const std::string &username, const std::string &password) + ModResult OnPreCommand(std::string& command, CommandBase::Params& parameters, LocalUser* user, bool validated) CXX11_OVERRIDE { - HashProvider* hash = ServerInstance->Modules->FindDataService("hash/" + hashtype); - - ParamM userinfo; - SQL->PopulateUserInfo(user, userinfo); - userinfo["username"] = username; - userinfo["password"] = hash ? hash->hexsum(password) : password; + // If we are not in the middle of an existing /OPER and someone is trying to oper-up + if (validated && command == "OPER" && parameters.size() >= 2 && !active) + { + if (SQL) + { + GetOperBlocks(user->uuid, parameters[0], parameters[1]); + /** We need to reload oper blocks from the DB before other + * hooks can run (i.e. sslinfo). We will re-call /OPER later. + */ + return MOD_RES_DENY; + } + ServerInstance->Logs->Log(MODNAME, LOG_DEFAULT, "database not present"); + } + else if (active) + { + active = false; + } + // There is either no DB or we successfully reloaded oper blocks + return MOD_RES_PASSTHRU; + } - SQL->submit(new OpMeQuery(this, databaseid, SQL->FormatQuery(query, userinfo), user->uuid, username, password)); + // The one w/o params is for non-/OPER DB updates, such as a rehash. + void GetOperBlocks() + { + SQL->Submit(new OperQuery(this, my_blocks), query); + } + void GetOperBlocks(const std::string u, const std::string& un, const std::string& pw) + { + active = true; + // Call to SQL query to fetch oper list from SQL table. + SQL->Submit(new OperQuery(this, my_blocks, u, un, pw), query); } - Version GetVersion() + void Prioritize() CXX11_OVERRIDE { - return Version("Allows storage of oper credentials in an SQL table", VF_VENDOR); + /** Run before other /OPER hooks that expect populated blocks, i.e. sslinfo or a TOTP module. + * We issue a DENY first, and will re-run OnPreCommand later to trigger the other hooks post-DB update. + */ + ServerInstance->Modules.SetPriority(this, I_OnPreCommand, PRIORITY_FIRST); } + Version GetVersion() CXX11_OVERRIDE + { + return Version("Allows server operators to be authenticated against an SQL table.", VF_VENDOR); + } }; MODULE_INIT(ModuleSQLOper)