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