]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/extra/m_sqlauth.cpp
0cd1ced24f3d6d624e0dc9aded23cd1dbe31133c
[user/henk/code/inspircd.git] / src / modules / extra / m_sqlauth.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 "m_sqlv2.h"
16 #include "m_sqlutils.h"
17 #include "m_hash.h"
18
19 /* $ModDesc: Allow/Deny connections based upon an arbitary SQL table */
20 /* $ModDep: m_sqlv2.h m_sqlutils.h m_hash.h */
21
22 class ModuleSQLAuth : public Module
23 {
24         Module* SQLutils;
25         Module* SQLprovider;
26
27         std::string freeformquery;
28         std::string killreason;
29         std::string allowpattern;
30         std::string databaseid;
31
32         bool verbose;
33
34 public:
35         ModuleSQLAuth(InspIRCd* Me)
36         : Module(Me)
37         {
38                 ServerInstance->Modules->UseInterface("SQLutils");
39                 ServerInstance->Modules->UseInterface("SQL");
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_sqlauth.so.");
44
45                 SQLprovider = ServerInstance->Modules->FindFeature("SQL");
46                 if (!SQLprovider)
47                         throw ModuleException("Can't find an SQL provider module. Please load one before attempting to load m_sqlauth.");
48
49                 OnRehash(NULL,"");
50                 Implementation eventlist[] = { I_OnUserDisconnect, I_OnCheckReady, I_OnRequest, I_OnRehash, I_OnUserRegister };
51                 ServerInstance->Modules->Attach(eventlist, this, 5);
52         }
53
54         virtual ~ModuleSQLAuth()
55         {
56                 ServerInstance->Modules->DoneWithInterface("SQL");
57                 ServerInstance->Modules->DoneWithInterface("SQLutils");
58         }
59
60
61         virtual void OnRehash(User* user, const std::string &parameter)
62         {
63                 ConfigReader Conf(ServerInstance);
64
65                 databaseid      = Conf.ReadValue("sqlauth", "dbid", 0);                 /* Database ID, given to the SQL service provider */
66                 freeformquery   = Conf.ReadValue("sqlauth", "query", 0);        /* Field name where username can be found */
67                 killreason      = Conf.ReadValue("sqlauth", "killreason", 0);   /* Reason to give when access is denied to a user (put your reg details here) */
68                 allowpattern    = Conf.ReadValue("sqlauth", "allowpattern",0 ); /* Allow nicks matching this pattern without requiring auth */
69                 verbose         = Conf.ReadFlag("sqlauth", "verbose", 0);               /* Set to true if failed connects should be reported to operators */
70         }
71
72         virtual int OnUserRegister(User* user)
73         {
74                 if ((!allowpattern.empty()) && (InspIRCd::Match(user->nick,allowpattern)))
75                 {
76                         user->Extend("sqlauthed");
77                         return 0;
78                 }
79
80                 if (!CheckCredentials(user))
81                 {
82                         ServerInstance->Users->QuitUser(user, killreason);
83                         return 1;
84                 }
85                 return 0;
86         }
87
88         void SearchAndReplace(std::string& newline, const std::string &find, const std::string &replace)
89         {
90                 std::string::size_type x = newline.find(find);
91                 while (x != std::string::npos)
92                 {
93                         newline.erase(x, find.length());
94                         if (!replace.empty())
95                                 newline.insert(x, replace);
96                         x = newline.find(find);
97                 }
98         }
99
100         bool CheckCredentials(User* user)
101         {
102                 std::string thisquery = freeformquery;
103                 std::string safepass = user->password;
104
105                 /* Search and replace the escaped nick and escaped pass into the query */
106
107                 SearchAndReplace(safepass, "\"", "");
108
109                 SearchAndReplace(thisquery, "$nick", user->nick);
110                 SearchAndReplace(thisquery, "$pass", safepass);
111                 SearchAndReplace(thisquery, "$host", user->host);
112                 SearchAndReplace(thisquery, "$ip", user->GetIPString());
113                 SearchAndReplace(thisquery, "$gecos", user->fullname);
114                 SearchAndReplace(thisquery, "$ident", user->ident);
115                 SearchAndReplace(thisquery, "$server", user->server);
116                 SearchAndReplace(thisquery, "$uuid", user->uuid);
117
118                 Module* HashMod = ServerInstance->Modules->Find("m_md5.so");
119
120                 if (HashMod)
121                 {
122                         HashResetRequest(this, HashMod).Send();
123                         SearchAndReplace(thisquery, "$md5pass", HashSumRequest(this, HashMod, user->password).Send());
124                 }
125
126                 HashMod = ServerInstance->Modules->Find("m_sha256.so");
127
128                 if (HashMod)
129                 {
130                         HashResetRequest(this, HashMod).Send();
131                         SearchAndReplace(thisquery, "$sha256pass", HashSumRequest(this, HashMod, user->password).Send());
132                 }
133
134                 /* Build the query */
135                 SQLrequest req = SQLrequest(this, SQLprovider, databaseid, SQLquery(thisquery));
136
137                 if(req.Send())
138                 {
139                         /* When we get the query response from the service provider we will be given an ID to play with,
140                          * just an ID number which is unique to this query. We need a way of associating that ID with a User
141                          * so we insert it into a map mapping the IDs to users.
142                          * Thankfully m_sqlutils provides this, it will associate a ID with a user or channel, and if the user quits it removes the
143                          * association. This means that if the user quits during a query we will just get a failed lookup from m_sqlutils - telling
144                          * us to discard the query.
145                          */
146                         AssociateUser(this, SQLutils, req.id, user).Send();
147
148                         return true;
149                 }
150                 else
151                 {
152                         if (verbose)
153                                 ServerInstance->SNO->WriteToSnoMask('A', "Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), req.error.Str());
154                         return false;
155                 }
156         }
157
158         virtual const char* OnRequest(Request* request)
159         {
160                 if(strcmp(SQLRESID, request->GetId()) == 0)
161                 {
162                         SQLresult* res = static_cast<SQLresult*>(request);
163
164                         User* user = GetAssocUser(this, SQLutils, res->id).S().user;
165                         UnAssociate(this, SQLutils, res->id).S();
166
167                         if(user)
168                         {
169                                 if(res->error.Id() == SQL_NO_ERROR)
170                                 {
171                                         if(res->Rows())
172                                         {
173                                                 /* We got a row in the result, this is enough really */
174                                                 user->Extend("sqlauthed");
175                                         }
176                                         else if (verbose)
177                                         {
178                                                 /* No rows in result, this means there was no record matching the user */
179                                                 ServerInstance->SNO->WriteToSnoMask('A', "Forbidden connection from %s!%s@%s (SQL query returned no matches)", user->nick.c_str(), user->ident.c_str(), user->host.c_str());
180                                                 user->Extend("sqlauth_failed");
181                                         }
182                                 }
183                                 else if (verbose)
184                                 {
185                                         ServerInstance->SNO->WriteToSnoMask('A', "Forbidden connection from %s!%s@%s (SQL query failed: %s)", user->nick.c_str(), user->ident.c_str(), user->host.c_str(), res->error.Str());
186                                         user->Extend("sqlauth_failed");
187                                 }
188                         }
189                         else
190                         {
191                                 return NULL;
192                         }
193
194                         if (!user->GetExt("sqlauthed"))
195                         {
196                                 ServerInstance->Users->QuitUser(user, killreason);
197                         }
198                         return SQLSUCCESS;
199                 }
200                 return NULL;
201         }
202
203         virtual void OnUserDisconnect(User* user)
204         {
205                 user->Shrink("sqlauthed");
206                 user->Shrink("sqlauth_failed");
207         }
208
209         virtual bool OnCheckReady(User* user)
210         {
211                 return user->GetExt("sqlauthed");
212         }
213
214         virtual Version GetVersion()
215         {
216                 return Version("$Id$", VF_VENDOR, API_VERSION);
217         }
218
219 };
220
221 MODULE_INIT(ModuleSQLAuth)