blob: 8c2214daa4c0976678dfab0f33ba95754e1b2631 [file] [log] [blame]
Copybara botbe50d492023-11-30 00:16:42 +01001<?php
Adrià Vilanova Martínez5af86512023-12-02 20:44:16 +01002/*
3 * hores
4 * Copyright (c) 2023 Adrià Vilanova Martínez
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 *
16 * You should have received a copy of the GNU Affero General Public
17 * License along with this program.
18 * If not, see http://www.gnu.org/licenses/.
19 */
20
Copybara botbe50d492023-11-30 00:16:42 +010021class security {
22 const HYPERADMIN = 0;
23 const ADMIN = 2;
24 /*const SYSTEM_REVIEWER = 5;
25 const LOG_REVIEWER = 7;*/
26 const WORKER = 10;
27 const UNKNOWN = 1000;
28
29 const METHOD_UNSPECIFICED = -1;
30 const METHOD_REDIRECT = 0;
31 const METHOD_NOTFOUND = 1;
32
33 const PARAM_ISSET = 1;
34 const PARAM_NEMPTY = 2;
35 const PARAM_ISEMAIL = 4;
36 const PARAM_ISDATE = 8;
37 const PARAM_ISINT = 16;
38 const PARAM_ISTIME = 32;
39 const PARAM_ISARRAY = 64;
40 const PARAM_ISEMAILOREMPTY = 128;
41
42 const SIGNIN_STATE_SIGNED_IN = 0;
43 const SIGNIN_STATE_NEEDS_SECOND_FACTOR = 1;
44 const SIGNIN_STATE_SIGNED_OUT = 2;
45 const SIGNIN_STATE_THROTTLED = 3;
46
47 public static $types = [
48 10 => "Trabajador",
49 /*7 => "Revisor de logs",
50 5 => "Revisor del sistema",*/
51 2 => "Administrador",
52 0 => "Hiperadministrador"
53 ];
54
55 public static $automatedChecks = [self::PARAM_ISSET, self::PARAM_NEMPTY, self::PARAM_ISEMAIL, self::PARAM_ISDATE, self::PARAM_ISINT, self::PARAM_ISTIME, self::PARAM_ISARRAY, self::PARAM_ISEMAILOREMPTY];
56
57 public static $passwordHelperText = "La contraseña debe tener como mínimo 8 caracteres y una letra mayúscula.";
58
59 public static function go($page) {
60 global $conf;
61
62 if ($conf["superdebug"]) {
63 echo "Redirects are not enabled. We would like to redirect you here: <a href='".self::htmlsafe($page)."'>".self::htmlsafe($page)."</a>";
64 } else {
65 header("Location: ".$page);
66 }
67
68 exit();
69 }
70
71 public static function goHome() {
72 self::go("index.php");
73 }
74
75 public static function notFound() {
76 header('HTTP/1.0 404 Not Found');
77 exit();
78 }
79
80 public static function isSignedIn() {
81 global $_SESSION;
82
83 return isset($_SESSION["id"]);
84 }
85
86 public static function check() {
87 if (!self::isSignedIn()) {
88 self::goHome();
89 }
90 }
91
92 public static function userType() {
93 global $_SESSION, $con;
94
95 if (!isset($_SESSION["id"])) {
96 return self::UNKNOWN;
97 }
98
99 $query = mysqli_query($con, "SELECT type FROM people WHERE id = ".(int)$_SESSION["id"]);
100
101 if (!mysqli_num_rows($query)) {
102 return self::UNKNOWN;
103 }
104
105 $row = mysqli_fetch_assoc($query);
106
107 return $row["type"];
108 }
109
110 public static function isAllowed($type) {
111 $userType = (self::isSignedIn() ? self::userType() : self::UNKNOWN);
112
113 return $userType <= $type;
114 }
115
116 public static function denyUseMethod($method = self::METHOD_REDIRECT) {
117 if ($method === self::METHOD_NOTFOUND) {
118 self::notFound();
119 } else { // self::METHOD_REDIRECT or anything else
120 self::goHome();
121 }
122 }
123
124 public static function checkType($type, $method = self::METHOD_REDIRECT) {
125 if (!self::isAllowed($type)) {
126 self::denyUseMethod($method);
127 }
128 }
129
130 public static function checkWorkerUIEnabled() {
131 global $conf;
132
133 if (self::userType() >= self::WORKER && !$conf["enableWorkerUI"]) {
134 self::go("index.php?msg=unsupported");
135 }
136 }
137
138 // Code from https://timoh6.github.io/2015/05/07/Rate-limiting-web-application-login-attempts.html
139 private static function getIpAddresses() {
140 $ips = [];
141 $ips["remoteIp"] = inet_pton($_SERVER['REMOTE_ADDR']); // inet_pton can handle both IPv4 and IPv6 addresses, treat IPv6 addresses as /64 or /56 blocks.
142 $ips["remoteIpBlock"] = long2ip(ip2long($_SERVER['REMOTE_ADDR']) & 0xFFFFFF00); // Something like this to turn the last octet of IPv4 address into a 0.
143 return $ips;
144 }
145
146 public static function recordLoginAttempt($username) {
147 global $con;
148
149 $susername = db::sanitize($username);
150
151 $ips = self::getIpAddresses();
152 $sremoteIp = db::sanitize($ips["remoteIp"]);
153 $sremoteIpBlock = db::sanitize($ips["remoteIpBlock"]);
154
155 return mysqli_query($con, "INSERT INTO signinattempts (username, remoteip, remoteipblock, signinattempttime) VALUES ('$susername', '$sremoteIp', '$sremoteIpBlock', NOW())");
156 }
157
158 public static function getRateLimitingCounts($username) {
159 global $con, $conf;
160
161 $susername = db::sanitize($username);
162
163 $ips = self::getIpAddresses();
164 $sremoteIp = db::sanitize($ips["remoteIp"]);
165 $sremoteIpBlock = db::sanitize($ips["remoteIpBlock"]);
166
167 $query = mysqli_query($con, "SELECT
168 COUNT(*) AS global_attempt_count,
169 IFNULL(SUM(CASE WHEN remoteip = '$sremoteIp' THEN 1 ELSE 0 END), 0) AS ip_attempt_count,
170 IFNULL(SUM(CASE WHEN (remoteipblock = '$sremoteIpBlock') THEN 1 ELSE 0 END), 0) AS ip_block_attempt_count,
171 (SELECT COUNT(DISTINCT remoteipblock) FROM signinattempts WHERE username = '$susername' AND signinattempttime >= (NOW() - INTERVAL 10 SECOND )) AS ip_blocks_per_username_attempt_count,
172 (SELECT COUNT(*) FROM signinattempts WHERE username = '$susername' AND signinattempttime >= (NOW() - INTERVAL 10 SECOND )) AS username_attempt_count
173 FROM signinattempts
174 WHERE signinattempttime >= (NOW() - INTERVAL 10 second)");
175
176 if ($query === false) return false;
177
178 return mysqli_fetch_assoc($query);
179 }
180
181 public static function isSignInThrottled($username) {
182 global $conf;
183
184 $count = self::getRateLimitingCounts($username);
185
186 if ($count["global_attempt_count"] >= $conf["signinThrottling"]["attemptCountLimit"]["global"] ||
187 $count["ip_attempt_count"] >= $conf["signinThrottling"]["attemptCountLimit"]["ip"] ||
188 $count["ip_block_attempt_count"] >= $conf["signinThrottling"]["attemptCountLimit"]["ipBlock"] ||
189 $count["ip_blocks_per_username_attempt_count"] >= $conf["signinThrottling"]["attemptCountLimit"]["ipBlocksPerUsername"] ||
190 $count["username_attempt_count"] >= $conf["signinThrottling"]["attemptCountLimit"]["username"]) {
191 return true;
192 }
193
194 if (!self::recordLoginAttempt($username)) {
195 echo "There was an unexpected error, so you could not be authenticated. Please contact me@avm99963.com and let them know of the error. (2)";
196 exit();
197 }
198
199 return false;
200 }
201
202 public static function isUserPassword($username, $password) {
203 global $con, $_SESSION;
204
205 $susername = db::sanitize($username);
206 $query = mysqli_query($con, "SELECT id, password FROM people WHERE ".($username === false ? "id = ".(int)$_SESSION["id"] : "username = '".$susername."'"));
207
208 if (!mysqli_num_rows($query)) {
209 return false;
210 }
211
212 $row = mysqli_fetch_assoc($query);
213
214 if (!password_verify($password, $row["password"])) {
215 return false;
216 }
217
218 return $row["id"];
219 }
220
221 public static function signIn($username, $password) {
222 global $_SESSION;
223
224 if (self::isSignInThrottled($username)) return self::SIGNIN_STATE_THROTTLED;
225
226 $id = self::isUserPassword($username, $password);
227
228 if ($id !== false) {
229 if (secondFactor::isEnabled($id)) {
230 $_SESSION["firstfactorid"] = $id;
231 return self::SIGNIN_STATE_NEEDS_SECOND_FACTOR;
232 } else {
233 $_SESSION["id"] = $id;
234 return self::SIGNIN_STATE_SIGNED_IN;
235 }
236 }
237
238 return self::SIGNIN_STATE_SIGNED_OUT;
239 }
240
241 public static function redirectAfterSignIn() {
242 global $conf;
243
244 if (self::isAllowed(self::ADMIN)) {
245 self::changeActiveView(visual::VIEW_ADMIN);
246 self::go("home.php");
247 } else {
248 self::changeActiveView(visual::VIEW_WORKER);
249 self::go(($conf["enableWorkerUI"] ? "workerhome.php" : "index.php?msg=unsupported"));
250 }
251 }
252
253 public static function logout() {
254 global $_SESSION;
255
256 session_destroy();
257 }
258
259 public static function htmlsafe($string) {
260 if ($string === null) return '';
261 return htmlspecialchars((string)$string);
262 }
263
264 private static function failedCheckParams($parameter, $method, $check) {
265 global $conf;
266
267 if ($conf["superdebug"]) {
268 echo "Failed check ".(int)$check." using parameter '".self::htmlsafe($parameter)."' with method ".self::htmlsafe($method).".<br>";
269 }
270 }
271
272 public static function checkParam($param, $check) {
273 if ($check == self::PARAM_NEMPTY && empty($param)) {
274 return false;
275 }
276
277 if ($check == self::PARAM_ISEMAIL && filter_var($param, FILTER_VALIDATE_EMAIL) === false) {
278 return false;
279 }
280
281 if ($check == self::PARAM_ISDATE && preg_match("/^[0-9]+-[0-9]+-[0-9]+$/", $param) !== 1) {
282 return false;
283 }
284
285 if ($check == self::PARAM_ISINT && filter_var($param, FILTER_VALIDATE_INT) === false) {
286 return false;
287 }
288
289 if ($check == self::PARAM_ISTIME) {
290 if (preg_match("/^[0-9]+:[0-9]+$/", $param) !== 1) return false;
291
292 $time = explode(":", $param);
293 if ((int)$time[0] >= 24 || (int)$time[1] >= 60) return false;
294 }
295
296 if ($check == self::PARAM_ISARRAY) {
297 // Check whether the parameter is an array
298 if (is_array($param) === false) return false;
299
300 // Check that it is not a multidimensional array (we don't want that for any parameter!)
301 foreach ($param as &$el) {
302 if (is_array($el)) return false;
303 }
304 }
305
306 if ($check == self::PARAM_ISEMAILOREMPTY && $param !== "" && filter_var($param, FILTER_VALIDATE_EMAIL) === false) {
307 return false;
308 }
309
310 return true;
311 }
312
313 public static function checkParams($method, $parameters, $forceDisableDebug = false) {
314 global $_POST, $_GET;
315
316 if (!in_array($method, ["GET", "POST"])) {
317 return false;
318 }
319
320 foreach ($parameters as $p) {
321 if (!$p[1]) {
322 continue;
323 }
324
325 if (($method == "POST" && !isset($_POST[$p[0]])) || ($method == "GET" && !isset($_GET[$p[0]]))) {
326 if (!$forceDisableDebug) self::failedCheckParams($p[0], $method, self::PARAM_ISSET);
327 return false;
328 }
329
330 $value = ($method == "POST" ? $_POST[$p[0]] : $_GET[$p[0]]);
331
332 foreach (self::$automatedChecks as $check) {
333 if (($p[1] & $check) && !self::checkParam($value, $check)) {
334 if (!$forceDisableDebug) self::failedCheckParams($p[0], $method, $check);
335 return false;
336 }
337 }
338 }
339
340 return true;
341 }
342
343 public static function existsType($type) {
344 $types = array_keys(self::$types);
345
346 return in_array($type, $types);
347 }
348
349 public static function getActiveView() {
350 global $_SESSION;
351
352 if (!self::isAllowed(self::ADMIN)) {
353 return visual::VIEW_WORKER;
354 }
355
356 return (!isset($_SESSION["activeView"]) ? visual::VIEW_ADMIN : $_SESSION["activeView"]);
357 }
358
359 public static function isAdminView() {
360 return (self::getActiveView() === visual::VIEW_ADMIN);
361 }
362
363 public static function changeActiveView($view) {
364 $_SESSION["activeView"] = $view;
365 }
366
367 public static function passwordIsGoodEnough($password) {
368 return (strlen($password) >= 8 && preg_match('/[A-Z]/', $password));
369 }
370
371 public static function cleanSignInAttempts($retentionDays = "DEFAULT") {
372 global $con, $conf;
373
374 if ($retentionDays === "DEFAULT") $retentionDays = $conf["signinThrottling"]["retentionDays"];
375
376 $sretentionDays = (int)$retentionDays;
377 if ($retentionDays < 0) return false;
378
379 return mysqli_query($con, "DELETE FROM signinattempts WHERE signinattempttime < (NOW() - INTERVAL $sretentionDays DAY)");
380 }
381}