Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Encryption #49962

Merged
merged 5 commits into from
Feb 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion config-stubs/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,13 @@
|
*/

'cipher' => 'AES-256-CBC',

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',
'previous_keys' => [
// Previous encryption keys to be used for decryption...
],

/*
|--------------------------------------------------------------------------
Expand Down
6 changes: 5 additions & 1 deletion config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,13 @@
|
*/

'cipher' => 'AES-256-CBC',

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',
'previous_keys' => [
// Previous encryption keys to be used for decryption...
],

/*
|--------------------------------------------------------------------------
Expand Down
12 changes: 8 additions & 4 deletions src/Illuminate/Cookie/CookieValuePrefix.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ public static function remove($cookieValue)
*
* @param string $cookieName
* @param string $cookieValue
* @param string $key
* @param array $keys
* @return string|null
*/
public static function validate($cookieName, $cookieValue, $key)
public static function validate($cookieName, $cookieValue, array $keys)
{
$hasValidPrefix = str_starts_with($cookieValue, static::create($cookieName, $key));
foreach ($keys as $key) {
$hasValidPrefix = str_starts_with($cookieValue, static::create($cookieName, $key));

return $hasValidPrefix ? static::remove($cookieValue) : null;
if ($hasValidPrefix) {
return static::remove($cookieValue);
}
}
}
}
2 changes: 1 addition & 1 deletion src/Illuminate/Cookie/Middleware/EncryptCookies.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ protected function validateValue(string $key, $value)
{
return is_array($value)
? $this->validateArray($key, $value)
: CookieValuePrefix::validate($key, $value, $this->encrypter->getKey());
: CookieValuePrefix::validate($key, $value, $this->encrypter->getAllKeys());
}

/**
Expand Down
71 changes: 62 additions & 9 deletions src/Illuminate/Encryption/Encrypter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ class Encrypter implements EncrypterContract, StringEncrypter
*/
protected $key;

/**
* The previous / legacy encryption keys.
*
* @var array
*/
protected $previousKeys = [];

/**
* The algorithm used for encryption.
*
Expand Down Expand Up @@ -113,7 +120,7 @@ public function encrypt($value, $serialize = true)

$mac = self::$supportedCiphers[strtolower($this->cipher)]['aead']
? '' // For AEAD-algorithms, the tag / MAC is returned by openssl_encrypt...
: $this->hash($iv, $value);
: $this->hash($iv, $value, $this->key);

$json = json_encode(compact('iv', 'value', 'mac', 'tag'), JSON_UNESCAPED_SLASHES);

Expand Down Expand Up @@ -159,9 +166,15 @@ public function decrypt($payload, $unserialize = true)
// Here we will decrypt the value. If we are able to successfully decrypt it
// we will then unserialize it and return it out to the caller. If we are
// unable to decrypt this value we will throw out an exception message.
$decrypted = \openssl_decrypt(
$payload['value'], strtolower($this->cipher), $this->key, 0, $iv, $tag ?? ''
);
foreach ($this->getAllKeys() as $key) {
$decrypted = \openssl_decrypt(
$payload['value'], strtolower($this->cipher), $key, 0, $iv, $tag ?? ''
);

if ($decrypted !== false) {
break;
}
}

if ($decrypted === false) {
throw new DecryptException('Could not decrypt the data.');
Expand All @@ -188,11 +201,12 @@ public function decryptString($payload)
*
* @param string $iv
* @param mixed $value
* @param string $key
* @return string
*/
protected function hash($iv, $value)
protected function hash($iv, $value, $key)
{
return hash_hmac('sha256', $iv.$value, $this->key);
return hash_hmac('sha256', $iv.$value, $key);
}

/**
Expand Down Expand Up @@ -258,9 +272,17 @@ protected function validPayload($payload)
*/
protected function validMac(array $payload)
{
return hash_equals(
$this->hash($payload['iv'], $payload['value']), $payload['mac']
);
foreach ($this->getAllKeys() as $key) {
$valid = hash_equals(
$this->hash($payload['iv'], $payload['value'], $key), $payload['mac']
);

if ($valid === true) {
return true;
}
}

return false;
}

/**
Expand Down Expand Up @@ -289,4 +311,35 @@ public function getKey()
{
return $this->key;
}

/**
* Get the current encryption key and all previous encryption keys.
*
* @return array
*/
public function getAllKeys()
{
return [$this->key, ...$this->previousKeys];
}

/**
* Set the previous / legacy encryption keys that should be utilized if decryption fails.
*
* @param array $key
* @return $this
*/
public function previousKeys(array $keys)
{
foreach ($keys as $key) {
if (! static::supported($key, $this->cipher)) {
$ciphers = implode(', ', array_keys(self::$supportedCiphers));

throw new RuntimeException("Unsupported cipher or incorrect key length. Supported ciphers are: {$ciphers}.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This exception will be ambiguous, as it doesn't indicate which key is invalid.

It can't return the actual key though - that'd be horribly insecure - however it could return the index in the previous keys array, which would point in the right direction.

Something like this might work:

foreach ($keys as $index => $key) {
    if (! static::supported($key, $this->cipher)) {
        $ciphers = implode(', ', array_keys(self::$supportedCiphers));

        throw new RuntimeException("Unsupported cipher or incorrect key length of previous key {$index}. Supported ciphers are: {$ciphers}.");

}
}

$this->previousKeys = $keys;

return $this;
}
}
6 changes: 5 additions & 1 deletion src/Illuminate/Encryption/EncryptionServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ protected function registerEncrypter()
$this->app->singleton('encrypter', function ($app) {
$config = $app->make('config')->get('app');

return new Encrypter($this->parseKey($config), $config['cipher']);
return (new Encrypter($this->parseKey($config), $config['cipher']))
->previousKeys(array_map(
fn ($key) => $this->parseKey(['key' => $key]),
$config['previous_keys'] ?? []
));
});
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Encryption/EncrypterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ public function testRawStringEncryption()
$this->assertSame('foo', $e->decryptString($encrypted));
}

public function testRawStringEncryptionWithPreviousKeys()
{
$previous = new Encrypter(str_repeat('b', 16));
$previousValue = $previous->encryptString('foo');

$new = new Encrypter(str_repeat('a', 16));
$new->previousKeys([str_repeat('b', 16)]);

$decrypted = $new->decryptString($previousValue);
$this->assertSame('foo', $decrypted);
}

public function testEncryptionUsingBase64EncodedKey()
{
$e = new Encrypter(random_bytes(16));
Expand Down
Loading