diff --git a/composer.json b/composer.json index bcad6dc..a71962b 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ "illuminate/container": "~5.4", "illuminate/support": "~5.4", "illuminate/cookie": "~5.4", - "illuminate/encryption": "~5.4", + "illuminate/contracts": "~5.4", "monolog/monolog": "~1.10", "packaged/figlet": "~0", "packaged/config": "~1.0", @@ -42,7 +42,8 @@ "mockery/mockery": "~0.9", "guzzlehttp/guzzle": "~6.3", "geoip2/geoip2": "~2.1", - "phpunit/phpunit": "~6.3" + "phpunit/phpunit": "~6.3", + "illuminate/encryption": "~5.4" }, "autoload": { "psr-4": { diff --git a/src/Encryption/Encrypter.php b/src/Encryption/Encrypter.php new file mode 100644 index 0000000..182d564 --- /dev/null +++ b/src/Encryption/Encrypter.php @@ -0,0 +1,247 @@ +_addKey((string)$key); + return; + } + + $keys = array_map('strval', array_values($key)); + + // An empty first entry is usually an unset environment variable. It is + // rejected rather than replaced by the next entry, which would encrypt + // new data with a key that is being retired. + if(!isset($keys[0]) || $keys[0] === '') + { + throw new \RuntimeException( + 'The first encryption key is the current key and must not be empty.' + ); + } + + foreach($keys as $i => $k) + { + if($i === 0 || $k !== '') + { + $this->_addKey($k); + } + } + } + + protected function _addKey($key) + { + $cipher = static::cipherForKey($key); + if($cipher === null) + { + throw new \RuntimeException( + 'Encryption keys must be 16 bytes (AES-128-CBC) or 32 bytes (AES-256-CBC).' + ); + } + $this->_keys[] = [$key, $cipher]; + } + + /** + * @param string $key + * + * @return string|null the cipher for a key of this length, null if none + */ + public static function cipherForKey($key) + { + switch(mb_strlen($key, '8bit')) + { + case 16: + return 'AES-128-CBC'; + case 32: + return 'AES-256-CBC'; + } + return null; + } + + /** + * The current encryption key + * + * @return string + */ + public function getKey() + { + return $this->_keys[0][0]; + } + + /** + * @param mixed $value + * @param bool $serialize + * + * @return string + * + * @throws EncryptException + */ + public function encrypt($value, $serialize = true) + { + list($key, $cipher) = $this->_keys[0]; + $iv = random_bytes(openssl_cipher_iv_length($cipher)); + + $value = openssl_encrypt( + $serialize ? serialize($value) : $value, + $cipher, + $key, + 0, + $iv + ); + if($value === false) + { + throw new EncryptException('Could not encrypt the data.'); + } + + $iv = base64_encode($iv); + $mac = static::_hash($iv, $value, $key); + $json = json_encode(compact('iv', 'value', 'mac')); + if(json_last_error() !== JSON_ERROR_NONE) + { + throw new EncryptException('Could not encrypt the data.'); + } + return base64_encode($json); + } + + /** + * @param string $value + * + * @return string + */ + public function encryptString($value) + { + return $this->encrypt($value, false); + } + + /** + * With $unserialize, the decrypted value is passed to unserialize() + * unrestricted, as illuminate/encryption does. When the payload may come + * from an untrusted source (e.g. a cookie), pass $unserialize = false and + * unserialize with ['allowed_classes' => false]. + * + * @param string $payload + * @param bool $unserialize + * + * @return mixed + * + * @throws DecryptException when no key can decrypt the payload + */ + public function decrypt($payload, $unserialize = true) + { + $failure = null; + foreach($this->_keys as $keyCipher) + { + try + { + $decrypted = static::_decrypt($payload, $keyCipher[0], $keyCipher[1]); + return $unserialize ? unserialize($decrypted) : $decrypted; + } + catch(DecryptException $e) + { + $failure = $failure ?: $e; + } + } + throw $failure; + } + + /** + * @param string $payload + * + * @return string + */ + public function decryptString($payload) + { + return $this->decrypt($payload, false); + } + + protected static function _decrypt($payload, $key, $cipher) + { + $payload = json_decode(base64_decode($payload), true); + if(!is_array($payload) + || !isset($payload['iv'], $payload['value'], $payload['mac']) + || !is_string($payload['iv']) + || !is_string($payload['value']) + || !is_string($payload['mac']) + || strlen(base64_decode($payload['iv'], true)) + !== openssl_cipher_iv_length($cipher)) + { + throw new DecryptException('The payload is invalid.'); + } + + // Compare HMACs of both MACs under a random key, as illuminate/encryption + // does, so the comparison leaks nothing about the expected MAC. + $bytes = random_bytes(16); + $calculated = hash_hmac( + 'sha256', + static::_hash($payload['iv'], $payload['value'], $key), + $bytes, + true + ); + if(!hash_equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calculated)) + { + throw new DecryptException('The MAC is invalid.'); + } + + $decrypted = openssl_decrypt( + $payload['value'], + $cipher, + $key, + 0, + base64_decode($payload['iv']) + ); + if($decrypted === false) + { + throw new DecryptException('Could not decrypt the data.'); + } + return $decrypted; + } + + protected static function _hash($iv, $value, $key) + { + return hash_hmac('sha256', $iv . $value, $key); + } +} diff --git a/src/ServiceManager/Services/EncryptionService.php b/src/ServiceManager/Services/EncryptionService.php index 61568ed..613ff3a 100644 --- a/src/ServiceManager/Services/EncryptionService.php +++ b/src/ServiceManager/Services/EncryptionService.php @@ -2,13 +2,22 @@ namespace Cubex\ServiceManager\Services; use Cubex\Cubex; -use Illuminate\Encryption\Encrypter; +use Cubex\Encryption\Encrypter; class EncryptionService extends AbstractServiceProvider { + const DEFAULT_KEY = 'mR?u7DP30sj5Djdf'; + /** * Register the service * + * [security] encryption_key is either a single key, or a list of keys for + * rotation. A 16 byte key uses AES-128-CBC, a 32 byte key AES-256-CBC. + * See Encrypter. + * + * encryption_key[] = + * encryption_key[] = + * * @param array $parameters * * @return mixed @@ -19,13 +28,12 @@ public function register(array $parameters = null) 'encrypter', function (Cubex $cubex) { - return new Encrypter( - $cubex->getConfiguration()->getItem( - 'security', - 'encryption_key', - 'mR?u7DP30sj5Djdf' - ) + $key = $cubex->getConfiguration()->getItem( + 'security', + 'encryption_key', + self::DEFAULT_KEY ); + return new Encrypter($key === [] ? self::DEFAULT_KEY : $key); }, true ); diff --git a/tests/Cubex/Encryption/EncrypterTest.php b/tests/Cubex/Encryption/EncrypterTest.php new file mode 100644 index 0000000..0b9e271 --- /dev/null +++ b/tests/Cubex/Encryption/EncrypterTest.php @@ -0,0 +1,233 @@ + [self::CURRENT, 'AES-128-CBC'], + 'AES-256-CBC' => [self::KEY_256, 'AES-256-CBC'], + ]; + } + + public function testImplementsContract() + { + $this->assertInstanceOf( + '\Illuminate\Contracts\Encryption\Encrypter', + new Encrypter(self::CURRENT) + ); + } + + public function testCipherFollowsKeyLength() + { + $this->assertEquals('AES-128-CBC', Encrypter::cipherForKey(self::CURRENT)); + $this->assertEquals('AES-256-CBC', Encrypter::cipherForKey(self::KEY_256)); + $this->assertNull(Encrypter::cipherForKey('too-short')); + } + + /** + * @dataProvider keyProvider + */ + public function testIlluminatePayloadDecrypts($key, $cipher) + { + $illuminate = new IlluminateEncrypter($key, $cipher); + $ours = new Encrypter($key); + $value = ['a' => 1, 'b' => 'two']; + $this->assertEquals($value, $ours->decrypt($illuminate->encrypt($value))); + $this->assertEquals('raw', $ours->decrypt($illuminate->encrypt('raw', false), false)); + $this->assertEquals('raw', $ours->decryptString($illuminate->encryptString('raw'))); + } + + /** + * @dataProvider keyProvider + */ + public function testIlluminateDecryptsOurPayload($key, $cipher) + { + $illuminate = new IlluminateEncrypter($key, $cipher); + $ours = new Encrypter($key); + $value = ['a' => 1, 'b' => 'two']; + $this->assertEquals($value, $illuminate->decrypt($ours->encrypt($value))); + $this->assertEquals('raw', $illuminate->decrypt($ours->encrypt('raw', false), false)); + $this->assertEquals('raw', $illuminate->decryptString($ours->encryptString('raw'))); + } + + public function testPayloadFormat() + { + $payload = json_decode(base64_decode((new Encrypter(self::CURRENT))->encrypt('v')), true); + $this->assertEquals(['iv', 'value', 'mac'], array_keys($payload)); + $this->assertEquals(16, strlen(base64_decode($payload['iv'], true))); + $this->assertEquals( + hash_hmac('sha256', $payload['iv'] . $payload['value'], self::CURRENT), + $payload['mac'] + ); + } + + public function testTamperedMacThrows() + { + $payload = json_decode(base64_decode((new Encrypter(self::CURRENT))->encrypt('v')), true); + $payload['mac'] = hash_hmac('sha256', 'forged', self::CURRENT); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->expectExceptionMessage('MAC is invalid'); + (new Encrypter(self::CURRENT))->decrypt(base64_encode(json_encode($payload))); + } + + public function testTamperedValueThrows() + { + $payload = json_decode(base64_decode((new Encrypter(self::CURRENT))->encrypt('v')), true); + $payload['value'] = base64_encode('forged'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + (new Encrypter(self::CURRENT))->decrypt(base64_encode(json_encode($payload))); + } + + public function invalidPayloadProvider() + { + return [ + 'not base64 json' => ['not a payload'], + 'missing mac' => [base64_encode(json_encode(['iv' => base64_encode(str_repeat('a', 16)), 'value' => 'x']))], + 'short iv' => [base64_encode(json_encode(['iv' => base64_encode('a'), 'value' => 'x', 'mac' => 'y']))], + 'array value' => [base64_encode(json_encode(['iv' => base64_encode(str_repeat('a', 16)), 'value' => [], 'mac' => 'y']))], + ]; + } + + /** + * @dataProvider invalidPayloadProvider + */ + public function testInvalidPayloadThrows($payload) + { + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->expectExceptionMessage('payload is invalid'); + $this->_rotating()->decrypt($payload); + } + + public function testStringKeyUnchanged() + { + $encrypter = new Encrypter(self::CURRENT); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $this->assertEquals('value', $encrypter->decrypt($encrypter->encrypt('value'))); + } + + public function testStringKeyNoMatchThrows() + { + $payload = (new Encrypter(self::OLDER))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + (new Encrypter(self::CURRENT))->decrypt($payload); + } + + public function testFirstEntryEncrypts() + { + $encrypter = $this->_rotating(); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $payload = $encrypter->encrypt('value'); + $this->assertEquals('value', (new IlluminateEncrypter(self::CURRENT))->decrypt($payload)); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + (new IlluminateEncrypter(self::OLDER))->decrypt($payload); + } + + public function testFallbackKeysDecrypt() + { + $encrypter = $this->_rotating(); + $this->assertEquals( + 'older', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('older')) + ); + $this->assertEquals( + 'oldest', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDEST))->encrypt('oldest', false), false) + ); + } + + public function testMixedCipherRotation() + { + $encrypter = new Encrypter([self::KEY_256, self::OLDER]); + $this->assertEquals( + 'new', + (new IlluminateEncrypter(self::KEY_256, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) + ); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER, 'AES-128-CBC'))->encrypt('old')) + ); + } + + public function testNoKeyMatchesThrowsFirstFailure() + { + $payload = (new Encrypter('unknown-key-0004'))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->expectExceptionMessage('MAC is invalid'); + $this->_rotating()->decrypt($payload); + } + + public function testEmptyFallbacksIgnored() + { + $encrypter = new Encrypter([self::CURRENT, '', null, self::OLDER]); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $this->assertEquals( + 'older', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('older')) + ); + } + + public function testSingleEntryArrayMatchesString() + { + $encrypter = new Encrypter([self::CURRENT]); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $payload = (new IlluminateEncrypter(self::OLDER))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $encrypter->decrypt($payload); + } + + public function testEmptyFirstEntryThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('current key'); + new Encrypter(['', self::OLDER]); + } + + public function testAllEmptyThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('current key'); + new Encrypter(['', '']); + } + + public function testEmptyStringKeyThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('16 bytes'); + new Encrypter(''); + } + + public function badKeyProvider() + { + return [ + 'short current' => [['too-short', self::OLDER]], + 'short fallback' => [[self::CURRENT, 'too-short']], + '24 byte key' => [str_repeat('a', 24)], + ]; + } + + /** + * @dataProvider badKeyProvider + */ + public function testBadKeyLengthThrows($key) + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('16 bytes'); + new Encrypter($key); + } +} diff --git a/tests/Cubex/ServiceManager/ServiceManagerTest.php b/tests/Cubex/ServiceManager/ServiceManagerTest.php index 3da0ef4..b47300e 100644 --- a/tests/Cubex/ServiceManager/ServiceManagerTest.php +++ b/tests/Cubex/ServiceManager/ServiceManagerTest.php @@ -137,7 +137,7 @@ public function testServiceAliases() $manager->setCubex($cubex); $manager->boot(); $encrypter = $cubex->make('encrypter'); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertInstanceOf('\Illuminate\Contracts\Encryption\Encrypter', $encrypter); } } diff --git a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php index 7dbaf89..072d6ef 100644 --- a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php +++ b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php @@ -2,29 +2,95 @@ namespace CubexTest\Cubex\ServiceManager\Services; use Cubex\Cubex; +use Cubex\Encryption\Encrypter; use Cubex\ServiceManager\Services\EncryptionService; +use Illuminate\Encryption\Encrypter as IlluminateEncrypter; use Packaged\Config\Provider\ConfigSection; use Packaged\Config\Provider\Test\TestConfigProvider; use PHPUnit\Framework\TestCase; class EncryptionServiceTest extends TestCase { - public function testRegisterCreatesEncrypter() + const CURRENT = 'current-key-0001'; + const OLDER = 'older-key-000002'; + + protected function _encrypter($key = null) { + $config = new TestConfigProvider(); + if($key !== null) + { + $config->addItem('security', 'encryption_key', $key); + } $cubex = new Cubex(); - $cubex->configure(new TestConfigProvider()); + $cubex->configure($config); $encryptionService = new EncryptionService(); + $encryptionService->boot($cubex, new ConfigSection()); + $encryptionService->register(); + return $cubex->make('encrypter'); + } + public function testRegisterCreatesEncrypter() + { $this->assertInstanceOf( '\Cubex\ServiceManager\IServiceProvider', - $encryptionService + new EncryptionService() ); - $encryptionService->boot($cubex, new ConfigSection()); + $encrypter = $this->_encrypter(); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertInstanceOf('\Illuminate\Contracts\Encryption\Encrypter', $encrypter); + $this->assertEquals(EncryptionService::DEFAULT_KEY, $encrypter->getKey()); + } - $encryptionService->register(); + public function testEmptyArrayUsesDefaultKey() + { + $this->assertEquals( + EncryptionService::DEFAULT_KEY, + $this->_encrypter([])->getKey() + ); + } + + public function testStringKey() + { + $encrypter = $this->_encrypter(self::CURRENT); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + } + + public function testArrayKeys() + { + $encrypter = $this->_encrypter([self::CURRENT, self::OLDER]); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); + } + + public function testEmptyFirstEntryThrows() + { + $this->expectException('\RuntimeException'); + $this->_encrypter(['', self::OLDER]); + } - $encrypter = $cubex->make('encrypter'); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + public function test256BitKeys() + { + $key = str_repeat('a', 32); + $encrypter = $this->_encrypter($key); + $this->assertEquals( + 'value', + (new IlluminateEncrypter($key, 'AES-256-CBC'))->decrypt($encrypter->encrypt('value')) + ); + + $encrypter = $this->_encrypter([$key, self::OLDER]); + $this->assertEquals( + 'new', + (new IlluminateEncrypter($key, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) + ); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); } }