]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blame - plugins/sql_auth/sql_auth.php
Disable permission checks when no auth plugin exists
[irc/unrealircd/unrealircd-webpanel.git] / plugins / sql_auth / sql_auth.php
CommitLineData
ea27475b
VP
1<?php
2
3require_once "SQL/sql.php";
ce9cf366 4require_once "SQL/settings.php";
4d634d0a 5
ea27475b
VP
6class sql_auth
7{
b44a2e97 8 public $name = "SQLAuth";
ea27475b
VP
9 public $author = "Valware";
10 public $version = "1.0";
11 public $description = "Provides a User Auth and Management Panel with an SQL backend";
b65f0496 12 public $email = "v.a.pond@outlook.com";
ea27475b
VP
13
14 function __construct()
15 {
5015c85c 16 self::create_tables();
b44a2e97 17 Hook::func(HOOKTYPE_PRE_HEADER, 'sql_auth::session_start');
33f512fa 18 Hook::func(HOOKTYPE_FOOTER, 'sql_auth::add_footer_info');
6930484c
VP
19 Hook::func(HOOKTYPE_USER_LOOKUP, 'sql_auth::get_user');
20 Hook::func(HOOKTYPE_USERMETA_ADD, 'sql_auth::add_usermeta');
21 Hook::func(HOOKTYPE_USERMETA_DEL, 'sql_auth::del_usermeta');
22 Hook::func(HOOKTYPE_USERMETA_GET, 'sql_auth::get_usermeta');
180b8ec1
VP
23 Hook::func(HOOKTYPE_USER_CREATE, 'sql_auth::user_create');
24 Hook::func(HOOKTYPE_GET_USER_LIST, 'sql_auth::get_user_list');
25 Hook::func(HOOKTYPE_USER_DELETE, 'sql_auth::user_delete');
5a7f0cde 26 Hook::func(HOOKTYPE_EDIT_USER, 'sql_auth::edit_core');
b6a7129b 27 Hook::func(HOOKTYPE_PRE_OVERVIEW_CARD, 'sql_auth::add_pre_overview_card');
c00c34d2 28 AuthModLoaded::$status = 1;
4d634d0a
VP
29
30 if (defined('SQL_DEFAULT_USER')) // we've got a default account
31 {
6930484c 32 $lkup = new PanelUser(SQL_DEFAULT_USER['username']);
4d634d0a
VP
33
34 if (!$lkup->id) // doesn't exist, add it with full privileges
35 {
180b8ec1
VP
36 $user = [];
37 $user['user_name'] = SQL_DEFAULT_USER['username'];
38 $user['user_pass'] = SQL_DEFAULT_USER['password'];
39 $user['err'] = "";
40 create_new_user($user);
4d634d0a 41 }
79d2194c
VP
42 $lkup = new PanelUser(SQL_DEFAULT_USER['username']);
43 if (!user_can($lkup, PERMISSION_MANAGE_USERS))
44 $lkup->add_permission(PERMISSION_MANAGE_USERS);
4d634d0a 45 }
ea27475b
VP
46 }
47
ea27475b 48
33f512fa
VP
49 public static function add_footer_info($empty)
50 {
94890799 51 if (!($user = unreal_get_current_user()))
33f512fa
VP
52 return;
53
54 else {
55 echo "<code>Admin Panel v" . WEBPANEL_VERSION . "</code>";
56 }
57 }
58
b6a7129b
BM
59 public static function add_pre_overview_card($empty)
60 {
61 if (defined('SQL_DEFAULT_USER'))
62 Message::Fail("Warning: SQL_DEFAULT_USER is set in config.php. You should remove that item now, as it is only used during installation.");
63 }
64
3a8ffab8 65 /* pre-Header hook */
b44a2e97
VP
66 public static function session_start($n)
67 {
06369f59
VP
68 if (!isset($_SESSION))
69 {
70 session_set_cookie_params(3600);
71 session_start();
72 }
454379e3 73 if (!isset($_SESSION['id']) || empty($_SESSION))
b44a2e97 74 {
bc75e1cb 75 $current_page = $_SERVER['REQUEST_URI'];
ce9cf366
VP
76 $tok = split($_SERVER['SCRIPT_FILENAME'], "/");
77 if ($check = security_check() && $tok[count($tok) - 1] !== "error.php") {
78 header("Location: " . BASE_URL . "plugins/sql_auth/error.php");
79 die();
80 }
bc75e1cb 81 header("Location: ".BASE_URL."login/?redirect=".urlencode($current_page));
454379e3 82 die();
b44a2e97 83 }
08ce3aa7
VP
84 else
85 {
94890799 86 if (!unreal_get_current_user()) // user no longer exists
08ce3aa7
VP
87 {
88 session_destroy();
321b7b81 89 header("Location: ".BASE_URL."login");
f5e3ecee 90 die();
08ce3aa7 91 }
e3e93dde 92 // you'll be automatically logged out after one hour of inactivity
08ce3aa7 93 }
b44a2e97 94 }
ea27475b 95
ce9cf366
VP
96 /**
97 * Create the tables we'll be using in the SQLdb
98 * @return void
99 */
5015c85c
VP
100 public static function create_tables()
101 {
102 $conn = sqlnew();
103 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "users (
104 user_id int AUTO_INCREMENT NOT NULL,
105 user_name VARCHAR(255) NOT NULL,
106 user_pass VARCHAR(255) NOT NULL,
9a674833 107 user_email VARCHAR(255),
5015c85c
VP
108 user_fname VARCHAR(255),
109 user_lname VARCHAR(255),
110 user_bio VARCHAR(255),
111 created VARCHAR(255),
112 PRIMARY KEY (user_id)
113 )");
9a674833
VP
114
115 /**
116 * Patch for beta users
117 * This adds the email column to existing tables without it
118 */
119 $columns = $conn->query("SHOW COLUMNS FROM " . SQL_PREFIX . "users");
120 $column_names = array();
121 $c = $columns->fetchAll();
f5173b9c 122
9a674833
VP
123 foreach($c as $column) {
124 $column_names[] = $column['Field'];
125 }
126 $column_exists = in_array("user_email", $column_names);
127 if (!$column_exists) {
128 $conn->query("ALTER TABLE " . SQL_PREFIX . "users ADD COLUMN user_email varchar(255)");
129 }
130
f5173b9c
VP
131 /**
132 * Another patch for beta users
133 * This changes the size of the meta_value so we can store more
134 */
50023a80 135
5015c85c
VP
136 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "user_meta (
137 meta_id int AUTO_INCREMENT NOT NULL,
138 user_id int NOT NULL,
139 meta_key VARCHAR(255) NOT NULL,
140 meta_value VARCHAR(255),
141 PRIMARY KEY (meta_id)
142 )");
ce9cf366
VP
143 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "auth_settings (
144 id int AUTO_INCREMENT NOT NULL,
145 setting_key VARCHAR(255) NOT NULL,
146 setting_value VARCHAR(255),
147 PRIMARY KEY (id)
148 )");
33f512fa
VP
149 $conn->query("CREATE TABLE IF NOT EXISTS " . SQL_PREFIX . "fail2ban (
150 id int AUTO_INCREMENT NOT NULL,
151 ip VARCHAR(255) NOT NULL,
152 count VARCHAR(255),
153 PRIMARY KEY (id)
154 )");
50023a80
VP
155 $c = [];
156 if (($columns = $conn->query("SHOW COLUMNS FROM ".SQL_PREFIX."user_meta")));
157 $c = $columns->fetchAll();
158 if (!empty($c))
159 $conn->query("ALTER TABLE `".SQL_PREFIX."user_meta` CHANGE `meta_value` `meta_value` VARCHAR(5000) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NULL DEFAULT NULL");
160
161
9c643401 162 new AuthSettings();
5015c85c
VP
163 }
164
6930484c
VP
165 /* We convert $u with a full user as an object ;D*/
166 public static function get_user(&$u)
167 {
168 $id = $u['id'];
169 $name = $u['name'];
170 $conn = sqlnew();
171
172 if ($id)
173 {
174 $prep = $conn->prepare("SELECT * FROM " . SQL_PREFIX . "users WHERE user_id = :id LIMIT 1");
175 $prep->execute(["id" => strtolower($id)]);
176 }
177 elseif ($name)
178 {
179 $prep = $conn->prepare("SELECT * FROM " . SQL_PREFIX . "users WHERE LOWER(user_name) = :name LIMIT 1");
180 $prep->execute(["name" => strtolower($name)]);
181 }
182 $data = NULL;
183 $obj = (object) [];
184 if ($prep)
185 $data = $prep->fetchAll();
186 if (isset($data[0]) && $data = $data[0])
187 {
188 $obj->id = $data['user_id'];
189 $obj->username = $data['user_name'];
190 $obj->passhash = $data['user_pass'];
191 $obj->first_name = $data['user_fname'] ?? NULL;
192 $obj->last_name = $data['user_lname'] ?? NULL;
193 $obj->created = $data['created'];
194 $obj->bio = $data['user_bio'];
9a674833 195 $obj->email = $data['user_email'];
6930484c
VP
196 $obj->user_meta = (new PanelUser_Meta($obj->id))->list;
197 }
198 $u['object'] = $obj;
199 }
200
201 public static function get_usermeta(&$u)
202 {
6930484c
VP
203 $list = &$u['meta'];
204 $id = $u['id'];
205 $conn = sqlnew();
206 if (isset($id))
207 {
208 $prep = $conn->prepare("SELECT * FROM " . SQL_PREFIX . "user_meta WHERE user_id = :id");
209 $prep->execute(["id" => $id]);
210 }
211 foreach ($prep->fetchAll() as $row)
212 {
213 $list[$row['meta_key']] = $row['meta_value'];
214 }
215 }
216
217 public static function add_usermeta(&$meta)
218 {
da6fa2d1 219 $meta = $meta['meta'];
6930484c
VP
220 $conn = sqlnew();
221 /* check if it exists first, update it if it does */
222 $query = "SELECT * FROM " . SQL_PREFIX . "user_meta WHERE user_id = :id AND meta_key = :key";
223 $stmt = $conn->prepare($query);
224 $stmt->execute(["id" => $meta['id'], "key" => $meta['key']]);
225 if ($stmt->rowCount()) // it exists, update instead of insert
226 {
227 $query = "UPDATE " . SQL_PREFIX . "user_meta SET meta_value = :value WHERE user_id = :id AND meta_key = :key";
228 $stmt = $conn->prepare($query);
229 $stmt->execute($meta);
230 if ($stmt->rowCount())
231 return true;
232 return false;
233 }
234
235 else
236 {
237 $query = "INSERT INTO " . SQL_PREFIX . "user_meta (user_id, meta_key, meta_value) VALUES (:id, :key, :value)";
238 $stmt = $conn->prepare($query);
239 $stmt->execute($meta);
240 if ($stmt->rowCount())
241 return true;
242 return false;
243 }
244 }
245 public static function del_usermeta(&$u)
246 {
247 $conn = sqlnew();
248 $query = "DELETE FROM " . SQL_PREFIX . "user_meta WHERE user_id = :id AND meta_key = :key";
249 $stmt = $conn->prepare($query);
250 $stmt->execute($u['meta']);
251 if ($stmt->rowCount())
252 return true;
253 return false;
254 }
180b8ec1
VP
255 public static function user_create(&$u)
256 {
257 $username = $u['user_name'];
9f9d16d5
VP
258 $first_name = $u['fname'] ?? NULL;
259 $last_name = $u['lname'] ?? NULL;
260 $password = $u['user_pass'] ?? NULL;
261 $user_bio = $u['user_bio'] ?? NULL;
262 $user_email = $u['user_email'] ?? NULL;
180b8ec1 263 $conn = sqlnew();
9a674833
VP
264 $prep = $conn->prepare("INSERT INTO " . SQL_PREFIX . "users (user_name, user_pass, user_fname, user_lname, user_bio, user_email, created) VALUES (:name, :pass, :fname, :lname, :user_bio, :user_email, :created)");
265 $prep->execute(["name" => $username, "pass" => $password, "fname" => $first_name, "lname" => $last_name, "user_bio" => $user_bio, "user_email" => $user_email, "created" => date("Y-m-d H:i:s")]);
180b8ec1
VP
266 if ($prep->rowCount())
267 $u['success'] = true;
268 else
269 $u['errmsg'][] = "Could not add user";
270 }
271
272 public static function get_user_list(&$list)
273 {
274 $conn = sqlnew();
275 $result = $conn->query("SELECT user_id FROM " . SQL_PREFIX . "users");
276 if (!$result) // impossible
277 {
278 die("Something went wrong.");
279 }
280 $userlist = [];
281 while($row = $result->fetch())
282 {
283 $userlist[] = new PanelUser(NULL, $row['user_id']);
284 }
285 if (!empty($userlist))
286 $list = $userlist;
287
288 }
289 public static function user_delete(&$u)
290 {
291 $user = $u['user'];
292 $query = "DELETE FROM " . SQL_PREFIX . "users WHERE user_id = :id";
293 $conn = sqlnew();
294 $stmt = $conn->prepare($query);
295 $stmt->execute(["id" => $user->id]);
296 $deleted = $stmt->rowCount();
297 if ($deleted)
298 {
299 $u['info'][] = "Successfully deleted user \"$user->username\"";
300 $u['boolint'] = 1;
301 } else {
302 $u['info'][] = "Unknown error";
303 $u['boolint'] = 0;
304 }
305 }
5a7f0cde
VP
306
307 public static function edit_core($arr)
308 {
309 $conn = sqlnew();
310 $user = $arr['user'];
311 $info = $arr['info'];
312 foreach($info as $key => $val)
313 {
e9c858fd 314 $value = NULL;
5a7f0cde
VP
315 if (!$val)
316 continue;
e9c858fd
VP
317 if (!strcmp($key,"update_fname") && $val != $user->first_name)
318 {
5a7f0cde 319 $value = "user_fname";
e9c858fd
VP
320 $valuestr = "first name";
321 }
322 elseif (!strcmp($key,"update_lname") && $val != $user->last_name)
323 {
5a7f0cde 324 $value = "user_lname";
e9c858fd
VP
325 $valuestr = "last name";
326 }
327 elseif (!strcmp($key,"update_bio") && $val != $user->bio)
328 {
5a7f0cde 329 $value = "user_bio";
e9c858fd
VP
330 $valuestr = "bio";
331 }
5a7f0cde 332 elseif (!strcmp($key,"update_pass") || !strcmp($key,"update_pass_conf"))
e9c858fd 333 {
5a7f0cde 334 $value = "user_pass";
e9c858fd
VP
335 $valuestr = "password";
336 }
337 elseif(!strcmp($key,"update_email") && $val != $user->email)
338 {
5a7f0cde 339 $value = "user_email";
e9c858fd
VP
340 $valuestr = "email address";
341 }
342
343 if (!$value)
344 continue;
5a7f0cde
VP
345 $query = "UPDATE " . SQL_PREFIX . "users SET $value=:value WHERE user_id = :id";
346 $stmt = $conn->prepare($query);
347 $stmt->execute(["value" => $val, "id" => $user->id]);
e9c858fd
VP
348
349 if (!$stmt->rowCount() && $stmt->errorInfo()[0] != "00000")
350 Message::Fail("Could not update $valuestr for $user->username: ".$stmt->errorInfo()[0]." (CODE: ".$stmt->errorCode().")");
351
352 else
353 Message::Success("Successfully updated the $valuestr for $user->username");
5a7f0cde
VP
354 }
355 }
ce9cf366
VP
356}
357
358
359function security_check()
360{
361 $ip = $_SERVER['REMOTE_ADDR'];
362 if (dnsbl_check($ip))
363 return true;
364
365 else if (fail2ban_check($ip))
366 {
367
368 }
369}
370
371function dnsbl_check($ip)
372{
5a7f0cde
VP
373
374 if (!defined('DNSBL'))
375 return;
ce9cf366
VP
376 $dnsbl_lookup = DNSBL;
377
378 // clear variable just in case
379 $listed = NULL;
380
381 // if the IP was not given because you're an idiot, stop processing
382 if (!$ip) { return; }
383
384 // get the first two segments of the IPv4
385 $because = split($ip, "."); // why you
386 $you = $because[1]; // gotta play
387 $want = $because[2]; // that song
388 $to = $you.".".$want."."; // so loud?
389
390 // exempt local connections because sometimes they get a false positive
391 if ($to == "192.168." || $to == "127.0.") { return NULL; }
392
393 // you spin my IP right round, right round, to check the records baby, right round-round-round
394 $reverse_ip = glue(array_reverse(split($ip, ".")), ".");
395
396 // checkem
397 foreach ($dnsbl_lookup as $host) {
398
399 //if it was listed
400 if (checkdnsrr($reverse_ip . "." . $host . ".", "A")) {
401
402 //take note
403 $listed = $host;
404 }
405 }
406
407 // if it was safe, return NOTHING
408 if (!$listed) {
409 return NULL;
410 }
411
412 // else, you guessed it, return where it was listed
413 else {
414 return $listed;
415 }
416}
417
418function fail2ban_check($ip)
33f512fa
VP
419{
420
421}