From d31cf9d1566d6b671933716cb73cd6c5cc9ab802 Mon Sep 17 00:00:00 2001 From: 4n4nk3 <4n4nk3@users.noreply.github> Date: Mon, 16 Jan 2023 11:25:48 +0100 Subject: [PATCH] Fix insecure persistent login token Signed-off-by: 4n4nk3 <47717886+4n4nk3@users.noreply.github.com> --- logout.php | 8 +- scripts/pi-hole/php/password.php | 14 ++-- scripts/pi-hole/php/persistentlogin_token.php | 83 +++++++++++++++++++ 3 files changed, 98 insertions(+), 7 deletions(-) create mode 100644 scripts/pi-hole/php/persistentlogin_token.php diff --git a/logout.php b/logout.php index baac04c12..cfeaf168d 100644 --- a/logout.php +++ b/logout.php @@ -1,9 +1,15 @@ 0) { // Check for and authorize from persistent cookie if (isset($_COOKIE['persistentlogin'])) { - if (hash_equals($pwhash, $_COOKIE['persistentlogin'])) { + if (checkValidityPersistentLoginToken($_COOKIE['persistentlogin'])) { $_SESSION['auth'] = true; - // Refresh cookie with new expiry - // setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) - setcookie('persistentlogin', $pwhash, time() + 60 * 60 * 24 * 7, null, null, null, true); } else { // Invalid cookie $_SESSION['auth'] = false; @@ -61,8 +59,12 @@ function verifyPassword($pwhash, $use_api = false) // Set persistent cookie if selected if (isset($_POST['persistentlogin'])) { - // setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) - setcookie('persistentlogin', $pwhash, time() + 60 * 60 * 24 * 7, null, null, null, true); + // Generate cookie with new expiry + $token = genPersistentLoginToken(); + $time = time() + 60 * 60 * 24 * 7; // 7 days + writePersistentLoginToken($token, $time); + // setcookie($name, $value, $expire, $path, $domain, $secure, $httponly) + setcookie('persistentlogin', $token, $time, null, null, null, true); } $_SESSION['auth'] = true; diff --git a/scripts/pi-hole/php/persistentlogin_token.php b/scripts/pi-hole/php/persistentlogin_token.php new file mode 100644 index 000000000..71d75d8ef --- /dev/null +++ b/scripts/pi-hole/php/persistentlogin_token.php @@ -0,0 +1,83 @@ += time()) { + return true; + } + } + } + return false; +} + +function writePersistentLoginToken($token, $time) +{ + $token_file = getPathPersistentLoginToken($token); + + if ($token_file and !file_exists($token_file)) { + $t_file = fopen($token_file, "w"); + if ($t_file) { + // make sure persistent login token file is not readable by other users + chmod($token_file, 0600); + + fwrite($t_file, $time); + fclose($t_file); + return true; + } + } + return false; +} + +function logoutPersistentLoginToken($token) +{ + setcookie('persistentlogin', '', 1); + + $token_file = getPathPersistentLoginToken($token); + if ($token_file and file_exists($token_file) and is_writable($token_file)) { + unlink($token_file); + } +}