]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqloper.cpp
Change this to use our md5 provider rather than MD5() in the query
[user/henk/code/inspircd.git] / src / modules / extra / m_sqloper.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include <string>
15 #include "users.h"
16 #include "channels.h"
17 #include "modules.h"
18 #include "inspircd.h"
19 #include "configreader.h"
20
21 #include "m_sqlv2.h"
22 #include "m_sqlutils.h"
23 #include "m_hash.h"
24 #include "commands/cmd_oper.h"
25
26 /* $ModDesc: Allows storage of oper credentials in an SQL table */
27 /* $ModDep: m_sqlv2.h m_sqlutils.h */
28
29 class ModuleSQLOper : public Module
30 {
31         InspIRCd* Srv;
32         Module* SQLutils;
33         Module* HashModule;
34         std::string databaseid;
35
36 public:
37         ModuleSQLOper(InspIRCd* Me)
38         : Module::Module(Me), Srv(Me)
39         {
40                 ServerInstance->UseInterface("SQLutils");
41                 ServerInstance->UseInterface("SQL");
42                 ServerInstance->UseInterface("HashRequest");
43
44                 /* Attempt to locate the md5 service provider, bail if we can't find it */
45                 HashModule = ServerInstance->FindModule("m_md5.so");
46                 if (!HashModule)
47                         throw ModuleException("Can't find m_md5.so. Please load m_md5.so before m_sqloper.so.");
48
49                 SQLutils = ServerInstance->FindModule("m_sqlutils.so");
50                 if (!SQLutils)
51                         throw ModuleException("Can't find m_sqlutils.so. Please load m_sqlutils.so before m_sqloper.so.");
52
53                 OnRehash(NULL,"");
54         }
55
56         virtual ~ModuleSQLOper()
57         {
58                 ServerInstance->DoneWithInterface("SQL");
59                 ServerInstance->DoneWithInterface("SQLutils");
60                 ServerInstance->DoneWithInterface("HashRequest");
61         }
62
63         void Implements(char* List)
64         {
65                 List[I_OnRequest] = List[I_OnRehash] = List[I_OnPreCommand] = 1;
66         }
67
68         virtual void OnRehash(userrec* user, const std::string &parameter)
69         {
70                 ConfigReader Conf(Srv);
71                 
72                 databaseid = Conf.ReadValue("sqloper", "dbid", 0); /* Database ID of a database configured for the service provider module */
73         }
74
75         virtual int OnPreCommand(const std::string &command, const char** parameters, int pcnt, userrec *user, bool validated, const std::string &original_line)
76         {
77                 if ((validated) && (command == "OPER"))
78                 {
79                         if (LookupOper(user, parameters[0], parameters[1]))
80                         {       
81                                 /* Returning true here just means the query is in progress, or on it's way to being
82                                  * in progress. Nothing about the /oper actually being successful..
83                                  * If the oper lookup fails later, we pass the command to the original handler
84                                  * for /oper by calling its Handle method directly.
85                                  */
86                                 return 1;
87                         }
88                 }
89                 return 0;
90         }
91
92         bool LookupOper(userrec* user, const std::string &username, const std::string &password)
93         {
94                 Module* target;
95                 
96                 target = Srv->FindFeature("SQL");
97
98                 if (target)
99                 {
100                         /* Reset hash module first back to MD5 standard state */
101                         HashResetRequest(this, HashModule).Send();
102                         /* Make an MD5 hash of the password for using in the query */
103                         std::string md5_pass_hash = HashSumRequest(this, HashModule, password.c_str()).Send();
104
105                         SQLrequest req = SQLreq(this, target, databaseid, "SELECT username, password, hostname, type FROM ircd_opers WHERE username = '?' AND password='?'", username, md5_pass_hash);
106                         
107                         if (req.Send())
108                         {
109                                 /* When we get the query response from the service provider we will be given an ID to play with,
110                                  * just an ID number which is unique to this query. We need a way of associating that ID with a userrec
111                                  * so we insert it into a map mapping the IDs to users.
112                                  * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the
113                                  * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling
114                                  * us to discard the query.
115                                  */
116                                 ServerInstance->Log(DEBUG, "Sent query, got given ID %lu", req.id);
117                                 
118                                 AssociateUser(this, SQLutils, req.id, user).Send();
119
120                                 user->Extend("oper_user", strdup(username.c_str()));
121                                 user->Extend("oper_pass", strdup(password.c_str()));
122                                         
123                                 return true;
124                         }
125                         else
126                         {
127                                 ServerInstance->Log(DEBUG, "SQLrequest failed: %s", req.error.Str());
128                         
129                                 return false;
130                         }
131                 }
132                 else
133                 {
134                         ServerInstance->Log(SPARSE, "WARNING: Couldn't find SQL provider module. NOBODY will be able to oper up unless their o:line is statically configured");
135                         return false;
136                 }
137         }
138         
139         virtual char* OnRequest(Request* request)
140         {
141                 if (strcmp(SQLRESID, request->GetId()) == 0)
142                 {
143                         SQLresult* res;
144                 
145                         res = static_cast<SQLresult*>(request);
146                         
147                         ServerInstance->Log(DEBUG, "Got SQL result (%s) with ID %lu", res->GetId(), res->id);
148                         
149                         userrec* user = GetAssocUser(this, SQLutils, res->id).S().user;
150                         UnAssociate(this, SQLutils, res->id).S();
151
152                         char* tried_user = NULL;
153                         char* tried_pass = NULL;
154
155                         user->GetExt("oper_user", tried_user);
156                         user->GetExt("oper_pass", tried_pass);
157                         
158                         if (user)
159                         {
160                                 if (res->error.Id() == NO_ERROR)
161                                 {                               
162                                         ServerInstance->Log(DEBUG, "Associated query ID %lu with user %s", res->id, user->nick);                        
163                                         ServerInstance->Log(DEBUG, "Got result with %d rows and %d columns", res->Rows(), res->Cols());
164                         
165                                         if (res->Rows())
166                                         {
167                                                 /* We got a row in the result, this means there was a record for the oper..
168                                                  * now we just need to check if their host matches, and if it does then
169                                                  * oper them up.
170                                                  * 
171                                                  * We now (previous versions of the module didn't) support multiple SQL
172                                                  * rows per-oper in the same way the config file does, all rows will be tried
173                                                  * until one is found which matches. This is useful to define several different
174                                                  * hosts for a single oper.
175                                                  * 
176                                                  * The for() loop works as SQLresult::GetRowMap() returns an empty map when there
177                                                  * are no more rows to return.
178                                                  */
179                                                 
180                                                 for (SQLfieldMap& row = res->GetRowMap(); row.size(); row = res->GetRowMap())
181                                                 {
182                                                         ServerInstance->Log(DEBUG, "Trying to oper user %s with username = '%s', passhash = '%s', hostname = '%s', type = '%s'", user->nick, row["username"].d.c_str(), row["password"].d.c_str(), row["hostname"].d.c_str(), row["type"].d.c_str());
183                                                         
184                                                         if (OperUser(user, row["username"].d, row["password"].d, row["hostname"].d, row["type"].d))
185                                                         {
186                                                                 /* If/when one of the rows matches, stop checking and return */
187                                                                 return SQLSUCCESS;
188                                                         }
189                                                         if (tried_user && tried_pass)
190                                                         {
191                                                                 LoginFail(user, tried_user, tried_pass);
192                                                                 free(tried_user);
193                                                                 free(tried_pass);
194                                                                 user->Shrink("oper_user");
195                                                                 user->Shrink("oper_pass");
196                                                         }
197                                                 }
198                                         }
199                                         else
200                                         {
201                                                 /* No rows in result, this means there was no oper line for the user,
202                                                  * we should have already checked the o:lines so now we need an
203                                                  * "insufficient awesomeness" (invalid credentials) error
204                                                  */
205                                                 if (tried_user && tried_pass)
206                                                 {
207                                                         LoginFail(user, tried_user, tried_pass);
208                                                         free(tried_user);
209                                                         free(tried_pass);
210                                                         user->Shrink("oper_user");
211                                                         user->Shrink("oper_pass");
212                                                 }
213                                         }
214                                 }
215                                 else
216                                 {
217                                         /* This one shouldn't happen, the query failed for some reason.
218                                          * We have to fail the /oper request and give them the same error
219                                          * as above.
220                                          */
221                                         ServerInstance->Log(DEBUG, "Query failed: %s", res->error.Str());
222
223                                         if (tried_user && tried_pass)
224                                         {
225                                                 LoginFail(user, tried_user, tried_pass);
226                                                 free(tried_user);
227                                                 free(tried_pass);
228                                                 user->Shrink("oper_user");
229                                                 user->Shrink("oper_pass");
230                                         }
231
232                                 }
233                         }
234                         else
235                         {
236                                 ServerInstance->Log(DEBUG, "Got query with unknown ID, this probably means the user quit while the query was in progress");
237                         }
238                 
239                         return SQLSUCCESS;
240                 }
241                 
242                 ServerInstance->Log(DEBUG, "Got unsupported API version string: %s", request->GetId());
243
244                 return NULL;
245         }
246
247         void LoginFail(userrec* user, const std::string &username, const std::string &pass)
248         {
249                 command_t* oper_command = ServerInstance->Parser->GetHandler("OPER");
250
251                 if (oper_command)
252                 {
253                         const char* params[] = { username.c_str(), pass.c_str() };
254                         oper_command->Handle(params, 2, user);
255                 }
256                 else
257                 {
258                         ServerInstance->Log(DEBUG, "WHAT?! Why do we have no OPER command?!");
259                 }
260         }
261
262         bool OperUser(userrec* user, const std::string &username, const std::string &password, const std::string &pattern, const std::string &type)
263         {
264                 ConfigReader Conf(Srv);
265                 
266                 for (int j = 0; j < Conf.Enumerate("type"); j++)
267                 {
268                         std::string tname = Conf.ReadValue("type","name",j);
269                         
270                         ServerInstance->Log(DEBUG, "Scanning opertype: %s", tname.c_str());
271                         
272                         std::string hostname(user->ident);
273                         hostname.append("@").append(user->host);
274                                                         
275                         if ((tname == type) && OneOfMatches(hostname.c_str(), user->GetIPString(), pattern.c_str()))
276                         {
277                                 /* Opertype and host match, looks like this is it. */
278                                 ServerInstance->Log(DEBUG, "Host (%s matched %s OR %s) and type (%s)", pattern.c_str(), hostname.c_str(), user->GetIPString(), type.c_str());
279                                 
280                                 std::string operhost = Conf.ReadValue("type", "host", j);
281                                                         
282                                 if (operhost.size())
283                                         user->ChangeDisplayedHost(operhost.c_str());
284                                                                 
285                                 Srv->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s", user->nick, user->ident, user->host, type.c_str());
286                                 user->WriteServ("381 %s :You are now an IRC operator of type %s", user->nick, type.c_str());
287                                 
288                                 if (!user->modes[UM_OPERATOR])
289                                         user->Oper(type);
290                                                                 
291                                 return true;
292                         }
293                 }
294                 
295                 return false;
296         }
297
298         virtual Version GetVersion()
299         {
300                 return Version(1,1,1,0,VF_VENDOR,API_VERSION);
301         }
302         
303 };
304
305 class ModuleSQLOperFactory : public ModuleFactory
306 {
307  public:
308         ModuleSQLOperFactory()
309         {
310         }
311         
312         ~ModuleSQLOperFactory()
313         {
314         }
315         
316         virtual Module * CreateModule(InspIRCd* Me)
317         {
318                 return new ModuleSQLOper(Me);
319         }
320         
321 };
322
323
324 extern "C" void * init_module( void )
325 {
326         return new ModuleSQLOperFactory;
327 }
328