From d8f84c736687ed0762758d81e6a6d0dff09382a7 Mon Sep 17 00:00:00 2001 From: Peter Potrowl Date: Wed, 4 May 2022 14:44:46 +0200 Subject: [PATCH] [HttpFoundation] [Session] Overwrite invalid session id --- .../Session/Storage/NativeSessionStorage.php | 6 ++++++ .../Tests/Session/Storage/NativeSessionStorageTest.php | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php index 916961f5eed5c..76ebfa08a482d 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php @@ -152,6 +152,12 @@ public function start() throw new \RuntimeException(sprintf('Failed to start the session because headers have already been sent by "%s" at line %d.', $file, $line)); } + $sessionId = $_COOKIE[session_name()] ?? null; + if ($sessionId && !preg_match('/^[a-zA-Z0-9,-]{22,}$/', $sessionId)) { + // the session ID in the header is invalid, create a new one + session_id(session_create_id()); + } + // ok to try and start the session if (!session_start()) { throw new \RuntimeException('Failed to start the session.'); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php index c9aa9a27b527f..776da2adc27f1 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php @@ -293,4 +293,13 @@ public function testGetBagsOnceSessionStartedIsIgnored() $this->assertEquals($storage->getBag('flashes'), $bag); } + + public function testRegenerateInvalidSessionId() + { + $_COOKIE[session_name()] = '&~['; + $started = (new NativeSessionStorage())->start(); + + $this->assertTrue($started); + $this->assertMatchesRegularExpression('/^[a-zA-Z0-9,-]{22,}$/', session_id()); + } }