diff --git a/API/index.php b/API/index.php index 706d4ce..e45c86f 100644 --- a/API/index.php +++ b/API/index.php @@ -1,21 +1,50 @@ true, + 'secure' => true, // Ensure HTTPS is used in production + 'samesite' => 'Strict' +]); session_start(); -// === Login & Authentication === -// Only proceed if the current session is authenticated. -// If not, show a login form. -if (!isset($_SESSION['logged_in'])) { - if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'])) { - $user_env = getenv('user'); // environment variable "user" - $pass_env = getenv('pass'); // environment variable "pass" - if ($_POST['username'] === $user_env && $_POST['password'] === $pass_env) { - $_SESSION['logged_in'] = true; - header("Location: index.php"); - exit; +// --- CSRF Utility Functions --- +function getCsrfToken() { + if (empty($_SESSION['csrf_token'])) { + $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); + } + return $_SESSION['csrf_token']; +} + +function validateCsrfToken($token) { + return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token); +} + +// --- Login and Authentication --- +if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) { + if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['username'], $_POST['password'], $_POST['csrf_token'])) { + if (!validateCsrfToken($_POST['csrf_token'])) { + $error = "Invalid CSRF token."; } else { - $error = "Invalid credentials."; + $envUser = getenv('user'); + $envPass = getenv('pass'); + // Using hash_equals for timing attack prevention + if (hash_equals($_POST['username'], $envUser) && hash_equals($_POST['password'], $envPass)) { + $_SESSION['logged_in'] = true; + session_regenerate_id(true); + header("Location: " . $_SERVER['PHP_SELF']); + exit; + } else { + $error = "Invalid credentials."; + } } } + $loginToken = getCsrfToken(); ?> @@ -64,8 +93,9 @@ if (!isset($_SESSION['logged_in'])) {