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