From 8e0c1ce08b1cad9f6e8c3b1ecb2c3421e256c02c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=91cze=20Bence?= Date: Sat, 13 Jun 2020 22:38:30 +0200 Subject: [PATCH] MAPG-133 add basic CSRF protection to server side --- public/index.php | 6 ++++++ web.php | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/public/index.php b/public/index.php index ed4e391..e4b5722 100644 --- a/public/index.php +++ b/public/index.php @@ -26,6 +26,12 @@ if ($match !== null) { $authorized = true; } + if ($method === 'post' && $request->post('anti_csrf_token') !== $request->session()->get('anti_csrf_token')) { + header('Content-Type: text/html; charset=UTF-8', true, 403); + echo json_encode(['error' => 'no_valid_anti_csrf_token']); + return; + } + if ($authorized) { $response = call_user_func([$controller, $handler[1]]); diff --git a/web.php b/web.php index 34eb015..27aa54b 100644 --- a/web.php +++ b/web.php @@ -38,3 +38,7 @@ session_start([ 'cookie_httponly' => true, 'cookie_samesite' => 'Lax' ]); + +if (!isset($_SESSION['anti_csrf_token'])) { + $_SESSION['anti_csrf_token'] = hash('sha256', random_bytes(10) . microtime()); +}