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