From 28bd78682c104d8e63e1ef0d62c5e8fe7c3829e7 Mon Sep 17 00:00:00 2001 From: Viktoras <109661563+vbezaras-leasingmarkt@users.noreply.github.com> Date: Wed, 14 Dec 2022 19:35:05 +0100 Subject: [PATCH] [9.x] Fixed errors occurring when encrypted cookies has been tampered with (#45313) * Fixed errors occurring when encrypted cookies has been tampered with * Corrected code style * Update Encrypter.php Co-authored-by: Taylor Otwell --- src/Illuminate/Encryption/Encrypter.php | 17 +++++++++++++++-- tests/Encryption/EncrypterTest.php | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Encryption/Encrypter.php b/src/Illuminate/Encryption/Encrypter.php index ff9d88f8ca41..9857c983327f 100755 --- a/src/Illuminate/Encryption/Encrypter.php +++ b/src/Illuminate/Encryption/Encrypter.php @@ -229,8 +229,21 @@ protected function getJsonPayload($payload) */ protected function validPayload($payload) { - return is_array($payload) && isset($payload['iv'], $payload['value'], $payload['mac']) && - strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length(strtolower($this->cipher)); + if (! is_array($payload)) { + return false; + } + + foreach (['iv', 'value', 'mac'] as $item) { + if (! isset($payload[$item]) || ! is_string($payload[$item])) { + return false; + } + } + + if (isset($payload['tag']) && ! is_string($payload['tag'])) { + return false; + } + + return strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length(strtolower($this->cipher)); } /** diff --git a/tests/Encryption/EncrypterTest.php b/tests/Encryption/EncrypterTest.php index ee6d5cfdc47c..c989a5d9f18e 100755 --- a/tests/Encryption/EncrypterTest.php +++ b/tests/Encryption/EncrypterTest.php @@ -204,4 +204,27 @@ public function testSupportedMethodAcceptsAnyCasing() $this->assertTrue(Encrypter::supported($key, 'aes-128-CBC')); $this->assertTrue(Encrypter::supported($key, 'aes-128-cbc')); } + + public function provideTamperedData() + { + return [ + [['iv' => ['value_in_array'], 'value' => '', 'mac' => '']], + [['iv' => '', 'value' => '', 'mac' => '']], + [['iv' => '', 'value' => ['value_in_array'], 'mac' => '']], + [['iv' => '', 'value' => '', 'mac' => ['value_in_array']]], + [['iv' => '', 'value' => '', 'mac' => ['value_in_array'], 'tag' => ['value_in_array']]], + ]; + } + + /** + * @dataProvider provideTamperedData + */ + public function testTamperedPayloadWillGetRejected($payload) + { + $this->expectException(DecryptException::class); + $this->expectExceptionMessage('The payload is invalid.'); + + $enc = new Encrypter(str_repeat('x', 16)); + $enc->decrypt(base64_encode(json_encode($payload))); + } }