diff options
| -rw-r--r-- | backend.php | 1 | ||||
| -rw-r--r-- | classes/Handler/DefineHandler.php | 6 | ||||
| -rw-r--r-- | classes/Handler/LoginHandler.php | 32 | ||||
| -rw-r--r-- | classes/RateLimitMiddleware.php | 119 | ||||
| -rw-r--r-- | classes/Router.php | 2 | ||||
| -rw-r--r-- | login.php | 204 | ||||
| -rw-r--r-- | tests/RouterTest.php | 1 | ||||
| -rw-r--r-- | tests/bootstrap.php | 8 |
8 files changed, 266 insertions, 107 deletions
diff --git a/backend.php b/backend.php index 07405de..2c43dad 100644 --- a/backend.php +++ b/backend.php @@ -13,6 +13,7 @@ $router = new Router(); $router->addMiddleware(new CsrfMiddleware()); + $router->addMiddleware(new RateLimitMiddleware()); $router->addRoute("perform-login", new \Handler\LoginHandler()); $router->addRoute("perform-oidc-login", new \Handler\LoginHandler()); diff --git a/classes/Handler/DefineHandler.php b/classes/Handler/DefineHandler.php index f15885f..3da21da 100644 --- a/classes/Handler/DefineHandler.php +++ b/classes/Handler/DefineHandler.php @@ -53,7 +53,11 @@ class DefineHandler implements RequestHandlerInterface, AuthRequired $word = mb_substr($word, 0, mb_strlen($word) - 1); } } else { - array_push($result, curl_error($ch)); + $curlErr = curl_error($ch); + if ($curlErr) { + user_error("dictd define lookup failed for '$word': $curlErr", E_USER_WARNING); + } + array_push($result, "Dictionary lookup failed. Please try again later."); } curl_close($ch); diff --git a/classes/Handler/LoginHandler.php b/classes/Handler/LoginHandler.php index 7fb1449..e317054 100644 --- a/classes/Handler/LoginHandler.php +++ b/classes/Handler/LoginHandler.php @@ -11,20 +11,33 @@ use Response; class LoginHandler implements RequestHandlerInterface { - /** @return array<string, string>|null */ + /** @return array{result: string, user: string, csrf_token: string}|null */ private function doLocalLogin(string $username, string $password): ?array { - $pass_hash = 'SHA256:' . hash('sha256', "$username:" . $password); - $user = ORM::for_table('epube_users') ->where('username', $username) - ->where('pass', $pass_hash) ->find_one(); if (!$user) { return null; } + // Verify password against stored hash (legacy or modern) + $legacy = str_starts_with($user->pass, 'SHA256:'); + $valid = $legacy + ? hash_equals($user->pass, 'SHA256:' . hash('sha256', "$username:$password")) + : password_verify($password, $user->pass); + + if (!$valid) { + return null; + } + + // Upgrade legacy hash to bcrypt + if ($legacy) { + $this->upgradePassword($user, $password); + } + + // Set up session if (session_status() != PHP_SESSION_ACTIVE) { session_start(); } @@ -41,6 +54,17 @@ class LoginHandler implements RequestHandlerInterface return ["result" => "ok", "user" => $username, "csrf_token" => $_SESSION["csrf_token"]]; } + /** + * Upgrade a legacy SHA256 password hash to bcrypt. + * Called after successful verification — the plaintext password is already known. + */ + private function upgradePassword(object $user, string $password): void + { + $newHash = password_hash($password, PASSWORD_BCRYPT); + $user->pass = $newHash; + $user->save(); + } + private function doOidcLogin(): void { $oidc = new OpenIDConnectClient( diff --git a/classes/RateLimitMiddleware.php b/classes/RateLimitMiddleware.php new file mode 100644 index 0000000..564fc50 --- /dev/null +++ b/classes/RateLimitMiddleware.php @@ -0,0 +1,119 @@ +<?php + +class RateLimitMiddleware implements MiddlewareInterface +{ + /** @var list<string> */ + private array $loginOps; + + private int $maxAttempts; + private int $windowSeconds; + private int $lockoutBase; + private int $lockoutMax; + private string $ip; + private bool $enabled; + + /** + * @param list<string> $loginOps Operations to protect (default: ['perform-login']) + * @param int $maxAttempts Max attempts within the window + * @param int $windowSeconds Sliding window size in seconds + * @param int $lockoutBase Initial lockout duration in seconds + * @param int $lockoutMax Maximum lockout duration (cap) in seconds + */ + public function __construct( + array $loginOps = ['perform-login'], + int $maxAttempts = 5, + int $windowSeconds = 300, + int $lockoutBase = 60, + int $lockoutMax = 1800 + ) { + $this->loginOps = $loginOps; + $this->maxAttempts = $maxAttempts; + $this->windowSeconds = $windowSeconds; + $this->lockoutBase = $lockoutBase; + $this->lockoutMax = $lockoutMax; + $this->ip = $this->getClientIp(); + $this->enabled = $this->isApcuAvailable(); + } + + public function process(Request $request, callable $next): Response + { + $op = $request->getString('op', ''); + + // Only apply to login endpoints + if (!in_array($op, $this->loginOps, true)) { + return $next($request); + } + + // Graceful degradation — never block legitimate users + if (!$this->enabled) { + return $next($request); + } + + // Check for active lockout + $lockKey = "epube_rl_lock_{$this->ip}"; + $remaining = apcu_fetch($lockKey, $lockSuccess); + if ($lockSuccess && is_int($remaining) && $remaining > 0) { + return $this->lockedOutResponse($remaining); + } + if ($lockSuccess) { + apcu_delete($lockKey); + } + + // Check sliding window of attempts + $windowKey = "epube_rl_win_{$this->ip}"; + $now = time(); + $cutoff = $now - $this->windowSeconds; + + $attempts = apcu_fetch($windowKey, $winSuccess); + if (!$winSuccess || !is_array($attempts)) { + $attempts = []; + } + + // Prune expired entries + $attempts = array_values(array_filter( + $attempts, + static fn($t): bool => is_int($t) && $t > $cutoff + )); + + if (count($attempts) >= $this->maxAttempts) { + $excess = count($attempts) - $this->maxAttempts; + $lockoutDur = min( + $this->lockoutBase * pow(2, $excess), + $this->lockoutMax + ); + apcu_store($lockKey, $lockoutDur, $lockoutDur); + return $this->lockedOutResponse($lockoutDur); + } + + // Record this attempt + $attempts[] = $now; + apcu_store($windowKey, $attempts, $this->windowSeconds); + + return $next($request); + } + + private function lockedOutResponse(int $remaining): Response + { + return (new Response()) + ->withStatus(429) + ->withHeader('Retry-After', (string) $remaining) + ->withBody(json_encode([ + 'error' => "Too many login attempts. Try again in {$remaining}s.", + ])); + } + + private function getClientIp(): string + { + if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ips = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])); + return $ips[0]; + } + + return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; + } + + private function isApcuAvailable(): bool + { + return function_exists('apcu_enabled') && apcu_enabled(); + } +} diff --git a/classes/Router.php b/classes/Router.php index 34e0bde..13e967e 100644 --- a/classes/Router.php +++ b/classes/Router.php @@ -45,7 +45,7 @@ class Router } // Check auth for handlers that require it - if ($handler instanceof AuthRequired && empty($_SESSION["owner"])) { + if ($handler instanceof AuthRequired && !validate_session()) { return (new Response()) ->withStatus(401) ->withBody(json_encode(["error" => "Unauthorized"])); diff --git a/login.php b/login.php index 5b0f10a..f73f67e 100644 --- a/login.php +++ b/login.php @@ -1,109 +1,111 @@ <?php - set_include_path(__DIR__ . "/include" . PATH_SEPARATOR . get_include_path()); + set_include_path(__DIR__ . "/include" . PATH_SEPARATOR . get_include_path()); - require_once __DIR__ . "/include/common.php"; - require_once __DIR__ . "/include/sessions.php"; + require_once __DIR__ . "/include/common.php"; + require_once __DIR__ . "/include/sessions.php"; - Config::sanity_check(); + Config::sanity_check(); - logout_user(); + logout_user(); ?> <!DOCTYPE html> <html> - <head> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <link href="lib/bootstrap/v3/css/bootstrap.min.css" rel="stylesheet" media="screen"> - <link id="theme_css" href="lib/bootstrap/v3/css/theme-dark.min.css" rel="stylesheet" media="screen"> - <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> - <script src="dist/app-libs.min.js"></script> - <title>The Epube</title> - <link type="text/css" rel="stylesheet" media="screen" href="dist/app.min.css" /> - <link rel="shortcut icon" type="image/png" href="img/favicon.png" /> - <link rel="manifest" href="manifest.json"> - <meta name="mobile-web-app-capable" content="yes"> - <script type="text/javascript"> - - function apply_night_mode(is_night) { - console.log("night mode changed to", is_night); - - $("#theme_css").attr("href", - "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css")); - } - - if (window.matchMedia) { - const mql = window.matchMedia('(prefers-color-scheme: dark)'); - - mql.addEventListener("change", () => { - apply_night_mode(mql.matches); - }); - - apply_night_mode(mql.matches); - } - - $(document).ready(function() { - /* global EpubeApp */ - - $("#login_form").on("submit", (e) => { - e.preventDefault(); - - $.ajax({ - url: "backend.php", - type: "POST", - data: $("#login_form").serialize(), - dataType: "json", - success: (response) => { - if (response.result === "ok") { - window.location.href = "index.html"; - } else { - $("#login_notice").text(response.error || "Login failed.").show(); - } - }, - error: () => { - $("#login_notice").text("Server error. Please try again.").show(); - } - }); - }); - - $(".oidc_login_btn").on("click", (e) => { - e.preventDefault(); - window.location.href = "backend.php?op=perform-oidc-login"; - }); - - if (typeof EpubeApp != "undefined") { - EpubeApp.setPage("PAGE_LOGIN"); - $("body").addClass("is-epube-app"); - } - }); - </script> - </head> - <body class="epube-login"> - <div class="navbar navbar-default navbar-static-top"> - <div class="container"> - <div class="navbar-header"> - <span class="navbar-brand"><a href="?">The Epube</a></span> - </div> - </div> - </div> - - <div class="container"> - <div id="login_notice" class="alert alert-danger" style="display:none"></div> - - <form id="login_form"> - <input type="hidden" name="op" value="perform-login"> - - <div class="form-group"> - <label>User</label> - <input class="form-control" required="true" name="user"> - </div> - <div class="form-group"> - <label>Password</label> - <input type="password" class="form-control" name="password" required="true"> - </div> - <button type="submit" class="btn btn-primary">Log in</button> - <?php if (Config::get(Config::OIDC_URL) != "") { ?> - <button type="button" class="oidc_login_btn btn btn-default">Log in with <?= Config::get(Config::OIDC_NAME) ?></button> - <?php } ?> - </form> - </div> - </body> + <head> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <link href="lib/bootstrap/v3/css/bootstrap.min.css" rel="stylesheet" media="screen"> + <link id="theme_css" href="lib/bootstrap/v3/css/theme-dark.min.css" rel="stylesheet" media="screen"> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <script src="dist/app-libs.min.js"></script> + <title>The Epube</title> + <link type="text/css" rel="stylesheet" media="screen" href="dist/app.min.css" /> + <link rel="shortcut icon" type="image/png" href="img/favicon.png" /> + <link rel="manifest" href="manifest.json"> + <meta name="mobile-web-app-capable" content="yes"> + <script type="text/javascript"> + + function apply_night_mode(is_night) { + console.log("night mode changed to", is_night); + + $("#theme_css").attr("href", + "lib/bootstrap/v3/css/" + (is_night ? "theme-dark.min.css" : "bootstrap-theme.min.css")); + } + + if (window.matchMedia) { + const mql = window.matchMedia('(prefers-color-scheme: dark)'); + + mql.addEventListener("change", () => { + apply_night_mode(mql.matches); + }); + + apply_night_mode(mql.matches); + } + + $(document).ready(function() { + /* global EpubeApp */ + + $("#login_form").on("submit", (e) => { + e.preventDefault(); + + $.ajax({ + url: "backend.php", + type: "POST", + data: $("#login_form").serialize(), + dataType: "json", + success: (response) => { + if (response.result === "ok") { + window.location.href = "index.html"; + } else { + $("#login_notice").text(response.error || "Login failed.").show(); + } + }, + error: (response) => { + console.log(response); + + $("#login_notice").text(response.responseJSON?.error ?? `Server error ${response.status}. Please try again.`).show(); + } + }); + }); + + $(".oidc_login_btn").on("click", (e) => { + e.preventDefault(); + window.location.href = "backend.php?op=perform-oidc-login"; + }); + + if (typeof EpubeApp != "undefined") { + EpubeApp.setPage("PAGE_LOGIN"); + $("body").addClass("is-epube-app"); + } + }); + </script> + </head> + <body class="epube-login"> + <div class="navbar navbar-default navbar-static-top"> + <div class="container"> + <div class="navbar-header"> + <span class="navbar-brand"><a href="?">The Epube</a></span> + </div> + </div> + </div> + + <div class="container"> + <div id="login_notice" class="alert alert-danger" style="display:none"></div> + + <form id="login_form"> + <input type="hidden" name="op" value="perform-login"> + + <div class="form-group"> + <label>User</label> + <input class="form-control" required="true" name="user"> + </div> + <div class="form-group"> + <label>Password</label> + <input type="password" class="form-control" name="password" required="true"> + </div> + <button type="submit" class="btn btn-primary">Log in</button> + <?php if (Config::get(Config::OIDC_URL) != "") { ?> + <button type="button" class="oidc_login_btn btn btn-default">Log in with <?= Config::get(Config::OIDC_NAME) ?></button> + <?php } ?> + </form> + </div> + </body> </html> diff --git a/tests/RouterTest.php b/tests/RouterTest.php index 1c2197c..58887c3 100644 --- a/tests/RouterTest.php +++ b/tests/RouterTest.php @@ -132,6 +132,7 @@ final class RouterTest extends TestCase }; $this->router->addRoute('protected', $handler); $_SESSION['owner'] = 'testuser'; + $_SESSION['pass_hash'] = 'dummy'; $response = $this->router->dispatchResponse('protected'); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 8cae8e1..a484982 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -5,3 +5,11 @@ putenv("IS_TESTING=true"); require_once "common.php"; + + // Stub validate_session() for unit tests (no DB needed). + // Integration tests load sessions.php which defines the real function. + if (!function_exists('validate_session')) { + function validate_session() : bool { + return !empty($_SESSION["owner"]) && !empty($_SESSION["pass_hash"]); + } + } |
