]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - Classes/class-paneluser.php
Security: check passwords against Have I Been Pwned
[irc/unrealircd/unrealircd-webpanel.git] / Classes / class-paneluser.php
1 <?php
2 /** Relating to Panel Access: Can add, delete and edit users. Big boss. */
3 define('PERMISSION_MANAGE_USERS', 'manage_users');
4 /** Relating to Users tab: Can ban users connected to IRC */
5 define('PERMISSION_BAN_USERS', 'ban_users');
6 /** Change properties of a user, i.e. vhost, modes and more */
7 define('PERMISSION_EDIT_USER', 'edit_user');
8 /** Change properties of a channel, i.e. topic, modes and more */
9 define('PERMISSION_EDIT_CHANNEL', 'edit_channel');
10 /** Change properties of a user on a channel i.e give/remove voice or ops and more */
11 define('PERMISSION_EDIT_CHANNEL_USER', 'edit_channel_user');
12 /** Can add manual bans, including G-Lines, Z-Lines and more */
13 define('PERMISSION_SERVER_BAN_ADD', 'tkl_add');
14 /** Can remove set bans, including G-Lines, Z-Lines and more */
15 define('PERMISSION_SERVER_BAN_DEL', 'tkl_del');
16 /** Can add Name Bans (Q-Lines) */
17 define('PERMISSION_NAME_BAN_ADD', 'nb_add');
18 /** Can delete Name Bans (Q-Lines) */
19 define('PERMISSION_NAME_BAN_DEL', 'nb_del');
20 /** Can add ban exceptions (E-Lines) */
21 define('PERMISSION_BAN_EXCEPTION_ADD', 'be_add');
22 /** Can delete ban exceptions (E-Lines) */
23 define('PERMISSION_BAN_EXCEPTION_DEL', 'be_del');
24 /** Can add spamfilter entries */
25 define('PERMISSION_SPAMFILTER_ADD', 'sf_add');
26 /** Can delete spamfilter entries */
27 define('PERMISSION_SPAMFILTER_DEL', 'sf_del');
28 /** Can rehash servers */
29 define('PERMISSION_REHASH', 'rhs');
30 /** Can install and uninstall plugins */
31 define('PERMISSION_MANAGE_PLUGINS', 'mng_plg');
32 /**
33 * PanelUser
34 * This is the User class for the SQL_Auth plugin
35 */
36 class PanelUser
37 {
38 public $id = NULL;
39 public $username = NULL;
40 private $passhash = NULL;
41 public $first_name = NULL;
42 public $last_name = NULL;
43 public $created = NULL;
44 public $user_meta = [];
45 public $bio = NULL;
46 public $email = NULL;
47
48 /**
49 * Find a user in the database by name or ID
50 * @param string $name
51 * @param mixed $id
52 */
53 function __construct(string $name = NULL, int $id = NULL)
54 {
55 $user["name"] = $name;
56 $user["id"] = $id;
57 $user["object"] = NULL;
58 Hook::run(HOOKTYPE_USER_LOOKUP, $user);
59 if ($user['object'] === null)
60 return; /* no auth module loaded? */
61 foreach ($user['object'] as $key => $value)
62 $this->$key = $value;
63 }
64
65 /**
66 * Verify a user's password
67 * @param string $input
68 * @return bool
69 */
70 function password_verify(string $password, bool &$hash_needs_updating = false) : bool
71 {
72 GLOBAL $config;
73 $hash_needs_updating = false;
74 $p2 = $password;
75 if (str_starts_with($this->passhash, "peppered:"))
76 {
77 /* Argon2 with pepper */
78 $password = hash_hmac("sha256", $password, $config['secrets']['pepper']);
79 if (password_verify($password, substr($this->passhash,9)))
80 {
81 $this->HIBP(sha1($p2));
82 return true;
83 }
84 }
85 else
86 {
87 /* Old standard argon2 */
88 if (password_verify($password, $this->passhash))
89 {
90 $this->HIBP(sha1($p2));
91 $hash_needs_updating = true;
92 return true;
93 }
94 }
95 return false;
96 }
97
98 /**
99 * Generate hash of user's password
100 * @param string $password
101 * @return string
102 */
103 public static function password_hash(string $password) : string
104 {
105 GLOBAL $config;
106 $input = hash_hmac("sha256", $password, $config['secrets']['pepper']);
107 return "peppered:".password_hash($input, PASSWORD_ARGON2ID);
108 }
109
110 /**
111 * Add user meta data
112 * If using an array for the first param then you
113 * must also use an array for the second param
114 * @param array|string $key
115 * @param array|string|int|bool|null $value
116 */
117 function add_meta(array|string $key, array|string|int|bool|null $value)
118 {
119
120 if (!$key)
121 return false;
122
123 if (is_array($key))
124 {
125 foreach ($key as $i => $k)
126 $arr[$k] = $value[$i];
127 } else {
128 $arr[$key] = $value;
129 }
130
131 foreach($arr as $k => $v)
132 {
133 $meta = [
134 "id" => $this->id,
135 "key" => $k,
136 "value" => $v
137 ];
138
139 $array['meta'] = $meta;
140 $array['user'] = $this;
141 Hook::run(HOOKTYPE_USERMETA_ADD, $array);
142 }
143
144 }
145
146 /**
147 * Delete user meta data by key
148 * @param string $key
149 */
150 function delete_meta(string $key)
151 {
152 if (!$key )
153 return false;
154
155 $meta = [
156 "id" => $this->id,
157 "key" => $key,
158 ];
159 $array['meta'] = $meta;
160 $array['user'] = $this;
161 Hook::run(HOOKTYPE_USERMETA_DEL, $array);
162
163 }
164
165 /** PERMISSIONS */
166
167 function add_permission($permission)
168 {
169 $meta = (isset($this->user_meta['permissions'])) ? unserialize($this->user_meta['permissions']) : [];
170 if (!in_array($permission,$meta))
171 $meta[] = $permission;
172 $this->add_meta("permissions", serialize($meta)); // updet de dettabess
173 $this->user_meta['permissions'] = serialize($meta); // put it back in our object in case it still needs to be used
174 }
175 function delete_permission($permission)
176 {
177 $meta = (isset($this->user_meta['permissions'])) ? unserialize($this->user_meta['permissions']) : [];
178 foreach($meta as $key => $value)
179 {
180 if (!strcmp($permission, $value))
181 unset($meta[$key]);
182 }
183 $this->add_meta("permissions", serialize($meta));
184 $this->user_meta['permissions'] = serialize($meta);
185 }
186
187 /** Updates core user info.
188 * CAUTION: Updating a non-existent column will crash
189 * your shit
190 */
191 function update_core_info($array)
192 {
193 $arr = ['info' => $array, 'user' => $this];
194 Hook::run(HOOKTYPE_EDIT_USER, $arr);
195 }
196
197 /** Have I Been Pwned
198 * Check password against HIBP to let them know about their
199 * leaked password.
200 * @param string $password_hash This should be a pre-hashed sha1 password
201 */
202 function HIBP($password_hash)
203 {
204 $url = "https://api.pwnedpasswords.com/range/".substr($password_hash,0,5);
205 $end = substr($password_hash,5);
206 $ch = curl_init($url);
207
208 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
209
210 $response = curl_exec($ch);
211
212 if (curl_errno($ch))
213 {
214 error_log("[error] Could not check against Have I Been Pwned API");
215 return;
216 }
217 $data = explode("\r\n",$response);
218 curl_close($ch);
219 $count = count($data);
220 $i = 1;
221 foreach($data as $dat)
222 {
223 $result = explode(":",$dat);
224 error_log("Checking $i of $count: ".substr($result[0],0,5)." => ".substr(strtoupper($end), 0,5));
225 if ($result[0] == strtoupper($end))
226 {
227 error_log("FOUND");
228 $this->add_meta("hibp", $result[1]);
229 return;
230 }
231 $i++;
232 }
233 }
234 }
235
236
237 /**
238 * This class looks up and returns any user meta.
239 * This is used by PanelUser, so you won't need to
240 * call it separately from PanelUser.
241 */
242 class PanelUser_Meta
243 {
244 public $list = [];
245 function __construct($id)
246 {
247 $array = [];
248 $arr["id"] = $id;
249 $arr['meta'] = &$array;
250 Hook::run(HOOKTYPE_USERMETA_GET, $arr);
251 $this->list = $arr['meta'];
252
253 }
254 }
255
256 /**
257 * Array of user
258 *
259 * Required:
260 * user_name
261 * user_pass
262 *
263 * Optional:
264 * user_fname
265 * user_lname
266 *
267 * @param array $user
268 * @throws Exception
269 * @return bool
270 */
271 function create_new_user(array &$user) : bool
272 {
273 if (!isset($user['user_name']) || !isset($user['user_pass']))
274 throw new Exception("Attempted to add user without specifying user_name or user_pass");
275
276 $user['user_name'] = htmlspecialchars($user['user_name']);
277 $user['user_pass'] = PanelUser::password_hash($user['user_pass']);
278 $user['fname'] = (isset($user['fname'])) ? htmlspecialchars($user['fname']) : NULL;
279 $last['lname'] = (isset($user['lname'])) ? htmlspecialchars($user['lname']) : NULL;
280 $user['user_bio'] = (isset($user['user_bio'])) ? htmlspecialchars($user['user_bio']) : NULL;
281 $user['email'] = (isset($user['user_email'])) ? htmlspecialchars($user['user_email']) : NULL;
282
283 if (($u = new PanelUser($user['user_name']))->id)
284 {
285 $user['err'] = "User already exists";
286 return false;
287 }
288 // internal use
289 $user['success'] = false;
290 $user['errmsg'] = [];
291
292 Hook::run(HOOKTYPE_USER_CREATE, $user);
293 if (!$user['success'])
294 return false;
295
296 return true;
297 }
298
299 /**
300 * Gets the user object for the current session
301 * @return PanelUser|bool
302 */
303 function unreal_get_current_user() : PanelUser|bool
304 {
305 if (isset($_SESSION) && isset($_SESSION['id']))
306 {
307 $user = new PanelUser(NULL, $_SESSION['id']);
308 if ($user->id)
309 return $user;
310 }
311 return false;
312 }
313
314 /**
315 * Checks if a user can do something
316 * @param string $permission
317 * @return bool
318 */
319 function current_user_can($permission) : bool
320 {
321 $user = unreal_get_current_user();
322 if (!$user)
323 return false;
324 return user_can($user, $permission);
325 }
326
327 /**
328 * Checks if a user can do something
329 * @param string $permission
330 * @return bool
331 */
332 function user_can(PanelUser $user, $permission) : bool
333 {
334 global $config;
335 if (!$user)
336 return false;
337
338 if (isset($user->user_meta['role']))
339 {
340 if ($user->user_meta['role'] == "Super-Admin")
341 return true;
342
343 else if ($user->user_meta['role'] == "Read-Only")
344 return false;
345
346 else if (in_array($permission, $config['user_roles'][$user->user_meta['role']]))
347 return true;
348
349 return false;
350 }
351
352 /* compatibility fallback */
353 if (isset($user->user_meta['permissions']))
354 {
355 $perms = unserialize($user->user_meta['permissions']);
356 if (in_array($permission, $perms))
357 return true;
358 }
359 return false;
360 }
361
362 /**
363 * Delete a user and related meta
364 * @param int $id The ID of the user in the SQL database.
365 * @param array $info This will fill with a response.
366 * @return int
367 *
368 * Return values:
369 * 1 The user was successfully deleted.
370 * 0 The user was not found
371 * -1 The admin does not have permission to delete users [TODO]
372 */
373 function delete_user(int $id, &$info = []) : int
374 {
375 $user = new PanelUser(NULL, $id);
376 if (!$user->id) {
377 $info[] = "Could not find user";
378 return 0;
379 }
380 $arr = ["user" => $user, "info" => &$info, "boolint" => 0];
381 Hook::run(HOOKTYPE_USER_DELETE, $arr);
382 return $arr["boolint"];
383 }
384
385 function get_panel_user_permission_list()
386 {
387 $list = [
388 "Can add/delete/edit Admin Panel users" => PERMISSION_MANAGE_USERS,
389 "Can add/delete/manage plugins" => PERMISSION_MANAGE_PLUGINS,
390 "Can ban/kill IRC users" => PERMISSION_BAN_USERS,
391 "Can change properties of a user, i.e. vhost, modes and more" => PERMISSION_EDIT_USER,
392 "Can change properties of a channel, i.e. topic, modes and more" => PERMISSION_EDIT_CHANNEL,
393 "Can change properties of a user on a channel i.e give/remove voice or ops and more" => PERMISSION_EDIT_CHANNEL_USER,
394 "Can add manual bans, including G-Lines, Z-Lines and more" => PERMISSION_SERVER_BAN_ADD,
395 "Can remove set bans, including G-Lines, Z-Lines and more" => PERMISSION_SERVER_BAN_DEL,
396 "Can forbid usernames and channels" => PERMISSION_NAME_BAN_ADD,
397 "Can unforbid usernames and channels" => PERMISSION_NAME_BAN_DEL,
398 "Can add server ban exceptions" => PERMISSION_BAN_EXCEPTION_ADD,
399 "Can remove server ban exceptions" => PERMISSION_BAN_EXCEPTION_DEL,
400 "Can add Spamfilter entries" => PERMISSION_SPAMFILTER_ADD,
401 "Can remove Spamfilter entries" => PERMISSION_SPAMFILTER_DEL
402
403 ];
404 Hook::run(HOOKTYPE_USER_PERMISSION_LIST, $list); // so plugin writers can add their own permissions
405 return $list;
406 }
407
408 function generate_panel_user_permission_table($user)
409 {
410
411 $list = get_panel_user_permission_list();
412 foreach($list as $desc => $slug)
413 {
414 $attributes = "";
415 $attributes .= (current_user_can(PERMISSION_MANAGE_USERS)) ? "" : "disabled ";
416 ?>
417 <div class="input-group">
418 <div class="input-group-prepend">
419 <div class="input-group-text">
420 <input <?php
421 $attributes .= (user_can($user, $slug)) ? "checked" : "";
422 echo $attributes;
423 ?> name="permissions[]" value="<?php echo $slug; ?>" type="checkbox">
424 </div>
425 </div>
426 <input type="text" readonly class="form-control" value="<?php echo "$desc ($slug)"; ?>">
427 </div>
428
429 <?php
430 }
431 }
432
433 function get_panel_user_roles_list()
434 {
435 GLOBAL $config;
436
437 /* Defaults */
438 $list = [
439 "Super-Admin" => get_panel_user_permission_list(), // SuperAdmin can do everything
440 "Read-Only" => [], // Read Only can do nothing
441 ];
442
443 if (isset($config["user_roles"]))
444 foreach($config['user_roles'] as $r => $role)
445 $list[$r] = $role;
446
447 return $list;
448 }
449
450 function generate_role_list($list)
451 {
452 $list2 = get_panel_user_permission_list();
453 ?>
454 <h5>Roles List:</h5>
455 <div id="permlist">
456 <div class="container-xxl" style="max-width: 1430px;">
457 <div class="accordion" id="roles_accord">
458
459 <?php foreach($list as $role => $slug) {?>
460 <div class="card">
461 <div class="card-header" id="<?php echo to_slug($role); ?>_heading">
462 <div class="btn-header-link btn-block text-left collapsed" type="button" data-toggle="collapse" data-target="#collapse_<?php echo to_slug($role); ?>" aria-expanded="true" aria-controls="collapse_<?php echo to_slug($role); ?>">
463 <?php echo $role ?>
464
465 </div>
466 </div>
467
468 <div id="collapse_<?php echo to_slug($role); ?>" class="collapse" aria-labelledby="<?php echo to_slug($role); ?>_heading" data-parent="#roles_accord">
469 <div id="results_rpc" class="card-body">
470 <form method="post">
471 <?php if ($role !== "Super-Admin" && $role !== "Read-Only") { ?>
472 <div class="container row mb-2">
473 <button id="update_role" name="update_role" value="<?php echo $role ?>" class="btn btn-primary ml-1 mr-2" >Update</button>
474 <button id="delete_role" name="del_role_name" value="<?php echo $role ?>" class="btn btn-danger"><i class="fa fa-trash fa-1" aria-hidden="true"></i></button>
475 </div>
476
477 <?php } ?>
478 <div id="<?php echo $role; ?>_input_area"><?php
479 foreach($list2 as $desc => $slug)
480 {
481 $attributes = "";
482 $attributes .= ($role == "Super-Admin" || $role == "Read-Only") ? "disabled " : "";
483
484 ?>
485 <div class="input-group">
486 <div class="input-group-prepend">
487 <div class="input-group-text">
488 <input <?php
489 $attributes .= (in_array($slug, $list[$role])) ? "checked" : "";
490 echo $attributes;
491 ?> name="permissions[]" value="<?php echo $slug; ?>" type="checkbox">
492 </div>
493 </div>
494 <input type="text" readonly class="form-control" value="<?php echo "$desc ($slug)"; ?>">
495 </div>
496
497 <?php
498 }
499 ?> </div>
500 </form>
501 </div>
502 </div>
503 </div>
504 <?php }?>
505
506 </div></div><br>
507
508 </div><?php
509
510 }