]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_sqloper.cpp
Reset the already_sent IDs during slow garbage collection
[user/henk/code/inspircd.git] / src / modules / m_sqloper.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2010 InspIRCd Development Team
6  * See: http://wiki.inspircd.org/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "m_sqlv2.h"
16 #include "m_sqlutils.h"
17 #include "m_hash.h"
18
19 /* $ModDesc: Allows storage of oper credentials in an SQL table */
20 /* $ModDep: m_sqlv2.h m_sqlutils.h m_hash.h */
21
22 typedef std::map<irc::string, Module*> hashymodules;
23
24 class ModuleSQLOper : public Module
25 {
26         LocalStringExt saved_user;
27         LocalStringExt saved_pass;
28         Module* SQLutils;
29         std::string databaseid;
30         std::string hashtype;
31         parameterlist names;
32
33 public:
34         ModuleSQLOper() : saved_user("sqloper_user", this), saved_pass("sqloper_pass", this)
35         {
36                 OnRehash(NULL);
37
38                 SQLutils = ServerInstance->Modules->Find("m_sqlutils.so");
39                 if (!SQLutils)
40                         throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqloper.so.");
41
42                 Implementation eventlist[] = { I_OnRehash, I_OnPreCommand, I_OnLoadModule };
43                 ServerInstance->Modules->Attach(eventlist, this, 3);
44                 ServerInstance->Modules->AddService(saved_user);
45                 ServerInstance->Modules->AddService(saved_pass);
46         }
47
48         bool OneOfMatches(const char* host, const char* ip, const char* hostlist)
49         {
50                 std::stringstream hl(hostlist);
51                 std::string xhost;
52                 while (hl >> xhost)
53                 {
54                         if (InspIRCd::Match(host, xhost, ascii_case_insensitive_map) || InspIRCd::MatchCIDR(ip, xhost, ascii_case_insensitive_map))
55                         {
56                                 return true;
57                         }
58                 }
59                 return false;
60         }
61
62         virtual void OnRehash(User* user)
63         {
64                 ConfigReader Conf;
65
66                 databaseid = Conf.ReadValue("sqloper", "dbid", 0); /* Database ID of a database configured for the service provider module */
67                 hashtype = Conf.ReadValue("sqloper", "hash", 0);
68         }
69
70         virtual ModResult OnPreCommand(std::string &command, std::vector<std::string> &parameters, LocalUser *user, bool validated, const std::string &original_line)
71         {
72                 if ((validated) && (command == "OPER"))
73                 {
74                         if (LookupOper(user, parameters[0], parameters[1]))
75                         {
76                                 /* Returning true here just means the query is in progress, or on it's way to being
77                                  * in progress. Nothing about the /oper actually being successful..
78                                  * If the oper lookup fails later, we pass the command to the original handler
79                                  * for /oper by calling its Handle method directly.
80                                  */
81                                 return MOD_RES_DENY;
82                         }
83                 }
84                 return MOD_RES_PASSTHRU;
85         }
86
87         bool LookupOper(User* user, const std::string &username, const std::string &password)
88         {
89                 ServiceProvider* prov = ServerInstance->Modules->FindService(SERVICE_DATA, "SQL");
90                 if (prov)
91                 {
92                         Module* target = prov->creator;
93                         HashProvider* hash = ServerInstance->Modules->FindDataService<HashProvider>("hash/" + hashtype);
94
95                         /* Make an MD5 hash of the password for using in the query */
96                         std::string md5_pass_hash = hash ? hash->hexsum(password) : password;
97
98                         /* We generate our own sum here because some database providers (e.g. SQLite) dont have a builtin md5/sha256 function,
99                          * also hashing it in the module and only passing a remote query containing a hash is more secure.
100                          */
101                         SQLrequest req = SQLrequest(this, target, databaseid,
102                                         SQLquery("SELECT username, password, hostname, type FROM ircd_opers WHERE username = '?' AND password='?'") % username % md5_pass_hash);
103
104                         /* When we get the query response from the service provider we will be given an ID to play with,
105                          * just an ID number which is unique to this query. We need a way of associating that ID with a User
106                          * so we insert it into a map mapping the IDs to users.
107                          * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the
108                          * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling
109                          * us to discard the query.
110                          */
111                         AssociateUser(this, SQLutils, req.id, user).Send();
112
113                         saved_user.set(user, username);
114                         saved_pass.set(user, password);
115
116                         return true;
117                 }
118                 else
119                 {
120                         ServerInstance->Logs->Log("m_sqloper",SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be able to oper up unless their o:line is statically configured");
121                         return false;
122                 }
123         }
124
125         void OnRequest(Request& request)
126         {
127                 if (strcmp(SQLRESID, request.id) == 0)
128                 {
129                         SQLresult* res = static_cast<SQLresult*>(&request);
130
131                         User* user = GetAssocUser(this, SQLutils, res->id).S().user;
132                         UnAssociate(this, SQLutils, res->id).S();
133
134                         if (user)
135                         {
136                                 std::string* tried_user = saved_user.get(user);
137                                 std::string* tried_pass = saved_pass.get(user);
138                                 if (res->error.Id() == SQL_NO_ERROR)
139                                 {
140                                         if (res->Rows())
141                                         {
142                                                 /* We got a row in the result, this means there was a record for the oper..
143                                                  * now we just need to check if their host matches, and if it does then
144                                                  * oper them up.
145                                                  *
146                                                  * We now (previous versions of the module didn't) support multiple SQL
147                                                  * rows per-oper in the same way the config file does, all rows will be tried
148                                                  * until one is found which matches. This is useful to define several different
149                                                  * hosts for a single oper.
150                                                  *
151                                                  * The for() loop works as SQLresult::GetRowMap() returns an empty map when there
152                                                  * are no more rows to return.
153                                                  */
154
155                                                 for (SQLfieldMap& row = res->GetRowMap(); row.size(); row = res->GetRowMap())
156                                                 {
157                                                         if (OperUser(user, row["hostname"].d, row["type"].d))
158                                                         {
159                                                                 /* If/when one of the rows matches, stop checking and return */
160                                                                 saved_user.unset(user);
161                                                                 saved_pass.unset(user);
162                                                         }
163                                                         if (tried_user && tried_pass)
164                                                         {
165                                                                 LoginFail(user, *tried_user, *tried_pass);
166                                                                 saved_user.unset(user);
167                                                                 saved_pass.unset(user);
168                                                         }
169                                                 }
170                                         }
171                                         else
172                                         {
173                                                 /* No rows in result, this means there was no oper line for the user,
174                                                  * we should have already checked the o:lines so now we need an
175                                                  * "insufficient awesomeness" (invalid credentials) error
176                                                  */
177                                                 if (tried_user && tried_pass)
178                                                 {
179                                                         LoginFail(user, *tried_user, *tried_pass);
180                                                         saved_user.unset(user);
181                                                         saved_pass.unset(user);
182                                                 }
183                                         }
184                                 }
185                                 else
186                                 {
187                                         /* This one shouldn't happen, the query failed for some reason.
188                                          * We have to fail the /oper request and give them the same error
189                                          * as above.
190                                          */
191                                         if (tried_user && tried_pass)
192                                         {
193                                                 LoginFail(user, *tried_user, *tried_pass);
194                                                 saved_user.unset(user);
195                                                 saved_pass.unset(user);
196                                         }
197
198                                 }
199                         }
200                 }
201         }
202
203         void LoginFail(User* user, const std::string &username, const std::string &pass)
204         {
205                 Command* oper_command = ServerInstance->Parser->GetHandler("OPER");
206
207                 if (oper_command)
208                 {
209                         std::vector<std::string> params;
210                         params.push_back(username);
211                         params.push_back(pass);
212                         oper_command->Handle(params, user);
213                 }
214                 else
215                 {
216                         ServerInstance->Logs->Log("m_sqloper",DEBUG, "BUG: WHAT?! Why do we have no OPER command?!");
217                 }
218         }
219
220         bool OperUser(User* user, const std::string &pattern, const std::string &type)
221         {
222                 OperIndex::iterator iter = ServerInstance->Config->oper_blocks.find(" " + type);
223                 if (iter == ServerInstance->Config->oper_blocks.end())
224                         return false;
225                 OperInfo* ifo = iter->second;
226
227                 std::string hostname(user->ident);
228
229                 hostname.append("@").append(user->host);
230
231                 if (OneOfMatches(hostname.c_str(), user->GetIPString(), pattern.c_str()))
232                 {
233                         /* Opertype and host match, looks like this is it. */
234
235                         user->Oper(ifo);
236                         return true;
237                 }
238
239                 return false;
240         }
241
242         Version GetVersion()
243         {
244                 return Version("Allows storage of oper credentials in an SQL table", VF_VENDOR);
245         }
246
247 };
248
249 MODULE_INIT(ModuleSQLOper)