From a7dd362bdbc507e805ec4ec74ce15becb5204b27 Mon Sep 17 00:00:00 2001 From: Pierre du Plessis Date: Wed, 23 Sep 2015 22:58:55 +0200 Subject: [PATCH] Removed Symfony\Component\Security\Core\Util\SecureRandom class in favour of the random_bytes function --- composer.json | 3 +- .../FrameworkExtension.php | 2 - .../Resources/config/security.xml | 15 -- .../Resources/config/security_csrf.xml | 1 - .../FrameworkExtensionTest.php | 7 - .../Command/UserPasswordEncoderCommand.php | 2 +- .../Resources/config/security_rememberme.xml | 1 - .../Core/Tests/Util/SecureRandomTest.php | 201 ------------------ .../Security/Core/Util/SecureRandom.php | 112 ---------- .../Core/Util/SecureRandomInterface.php | 29 --- .../UriSafeTokenGeneratorTest.php | 8 +- .../TokenGenerator/UriSafeTokenGenerator.php | 20 +- ...PersistentTokenBasedRememberMeServices.php | 23 +- ...istentTokenBasedRememberMeServicesTest.php | 3 +- src/Symfony/Component/Security/composer.json | 3 +- 15 files changed, 19 insertions(+), 411 deletions(-) delete mode 100644 src/Symfony/Bundle/FrameworkBundle/Resources/config/security.xml delete mode 100644 src/Symfony/Component/Security/Core/Tests/Util/SecureRandomTest.php delete mode 100644 src/Symfony/Component/Security/Core/Util/SecureRandom.php delete mode 100644 src/Symfony/Component/Security/Core/Util/SecureRandomInterface.php diff --git a/composer.json b/composer.json index 198321be08ab6..b8a0b64f0170b 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,8 @@ "php": ">=5.5.9", "doctrine/common": "~2.4", "twig/twig": "~1.20|~2.0", - "psr/log": "~1.0" + "psr/log": "~1.0", + "paragonie/random_compat": "~1.0" }, "replace": { "symfony/asset": "self.version", diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index e7f8ea49c0497..6f70f58d36884 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -87,8 +87,6 @@ public function load(array $configs, ContainerBuilder $container) $this->registerRequestConfiguration($config['request'], $container, $loader); } - $loader->load('security.xml'); - if ($this->isConfigEnabled($container, $config['form'])) { $this->formConfigEnabled = true; $this->registerFormConfiguration($config, $container, $loader); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/security.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/security.xml deleted file mode 100644 index 89637369256e9..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/security.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - %kernel.cache_dir%/secure_random.seed - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml index fa8a46d9aafe8..0795263b823b7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/security_csrf.xml @@ -6,7 +6,6 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 5b1fa8c30e04e..fa3f3467666ae 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -69,13 +69,6 @@ public function testCsrfProtectionForFormsEnablesCsrfProtectionAutomatically() $this->assertTrue($container->hasDefinition('security.csrf.token_manager')); } - public function testSecureRandomIsAvailableIfCsrfIsDisabled() - { - $container = $this->createContainerFromFile('csrf_disabled'); - - $this->assertTrue($container->hasDefinition('security.secure_random')); - } - public function testProxies() { $container = $this->createContainerFromFile('full'); diff --git a/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php b/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php index 5dbd830a39da5..0938b90db2c39 100644 --- a/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php +++ b/src/Symfony/Bundle/SecurityBundle/Command/UserPasswordEncoderCommand.php @@ -164,6 +164,6 @@ private function createPasswordQuestion() private function generateSalt() { - return base64_encode($this->getContainer()->get('security.secure_random')->nextBytes(30)); + return base64_encode(random_bytes(30)); } } diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml index 083dbcc3c0b57..36f2353620f2e 100644 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml +++ b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_rememberme.xml @@ -34,7 +34,6 @@ class="Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices" parent="security.authentication.rememberme.services.abstract" abstract="true"> - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Security\Core\Tests\Util; - -use Symfony\Component\Security\Core\Util\SecureRandom; - -class SecureRandomTest extends \PHPUnit_Framework_TestCase -{ - /** - * T1: Monobit test. - * - * @dataProvider getSecureRandoms - */ - public function testMonobit($secureRandom) - { - $nbOnBits = substr_count($this->getBitSequence($secureRandom, 20000), '1'); - $this->assertTrue($nbOnBits > 9654 && $nbOnBits < 10346, 'Monobit test failed, number of turned on bits: '.$nbOnBits); - } - - /** - * T2: Chi-square test with 15 degrees of freedom (chi-Quadrat-Anpassungstest). - * - * @dataProvider getSecureRandoms - */ - public function testPoker($secureRandom) - { - $b = $this->getBitSequence($secureRandom, 20000); - $c = array(); - for ($i = 0; $i <= 15; ++$i) { - $c[$i] = 0; - } - - for ($j = 1; $j <= 5000; ++$j) { - $k = 4 * $j - 1; - ++$c[8 * $b[$k - 3] + 4 * $b[$k - 2] + 2 * $b[$k - 1] + $b[$k]]; - } - - $f = 0; - for ($i = 0; $i <= 15; ++$i) { - $f += $c[$i] * $c[$i]; - } - - $Y = 16 / 5000 * $f - 5000; - - $this->assertTrue($Y > 1.03 && $Y < 57.4, 'Poker test failed, Y = '.$Y); - } - - /** - * Run test. - * - * @dataProvider getSecureRandoms - */ - public function testRun($secureRandom) - { - $b = $this->getBitSequence($secureRandom, 20000); - - $runs = array(); - for ($i = 1; $i <= 6; ++$i) { - $runs[$i] = 0; - } - - $addRun = function ($run) use (&$runs) { - if ($run > 6) { - $run = 6; - } - - ++$runs[$run]; - }; - - $currentRun = 0; - $lastBit = null; - for ($i = 0; $i < 20000; ++$i) { - if ($lastBit === $b[$i]) { - ++$currentRun; - } else { - if ($currentRun > 0) { - $addRun($currentRun); - } - - $lastBit = $b[$i]; - $currentRun = 0; - } - } - if ($currentRun > 0) { - $addRun($currentRun); - } - - $this->assertTrue($runs[1] > 2267 && $runs[1] < 2733, 'Runs of length 1 outside of defined interval: '.$runs[1]); - $this->assertTrue($runs[2] > 1079 && $runs[2] < 1421, 'Runs of length 2 outside of defined interval: '.$runs[2]); - $this->assertTrue($runs[3] > 502 && $runs[3] < 748, 'Runs of length 3 outside of defined interval: '.$runs[3]); - $this->assertTrue($runs[4] > 233 && $runs[4] < 402, 'Runs of length 4 outside of defined interval: '.$runs[4]); - $this->assertTrue($runs[5] > 90 && $runs[5] < 223, 'Runs of length 5 outside of defined interval: '.$runs[5]); - $this->assertTrue($runs[6] > 90 && $runs[6] < 233, 'Runs of length 6 outside of defined interval: '.$runs[6]); - } - - /** - * Long-run test. - * - * @dataProvider getSecureRandoms - */ - public function testLongRun($secureRandom) - { - $b = $this->getBitSequence($secureRandom, 20000); - - $longestRun = $currentRun = 0; - $lastBit = null; - for ($i = 0; $i < 20000; ++$i) { - if ($lastBit === $b[$i]) { - ++$currentRun; - } else { - if ($currentRun > $longestRun) { - $longestRun = $currentRun; - } - $lastBit = $b[$i]; - $currentRun = 0; - } - } - if ($currentRun > $longestRun) { - $longestRun = $currentRun; - } - - $this->assertTrue($longestRun < 34, 'Failed longest run test: '.$longestRun); - } - - /** - * Serial Correlation (Autokorrelationstest). - * - * @dataProvider getSecureRandoms - */ - public function testSerialCorrelation($secureRandom) - { - $shift = mt_rand(1, 5000); - $b = $this->getBitSequence($secureRandom, 20000); - - $Z = 0; - for ($i = 0; $i < 5000; ++$i) { - $Z += $b[$i] === $b[$i + $shift] ? 1 : 0; - } - - $this->assertTrue($Z > 2326 && $Z < 2674, 'Failed serial correlation test: '.$Z); - } - - public function getSecureRandoms() - { - $secureRandoms = array(); - - // only add if openssl is indeed present - $secureRandom = new SecureRandom(); - if ($this->hasOpenSsl($secureRandom)) { - $secureRandoms[] = array($secureRandom); - } - - // no-openssl with custom seed provider - $secureRandom = new SecureRandom(sys_get_temp_dir().'/_sf2.seed'); - $this->disableOpenSsl($secureRandom); - $secureRandoms[] = array($secureRandom); - - return $secureRandoms; - } - - protected function disableOpenSsl($secureRandom) - { - $ref = new \ReflectionProperty($secureRandom, 'useOpenSsl'); - $ref->setAccessible(true); - $ref->setValue($secureRandom, false); - $ref->setAccessible(false); - } - - protected function hasOpenSsl($secureRandom) - { - $ref = new \ReflectionProperty($secureRandom, 'useOpenSsl'); - $ref->setAccessible(true); - - $ret = $ref->getValue($secureRandom); - - $ref->setAccessible(false); - - return $ret; - } - - private function getBitSequence($secureRandom, $length) - { - $bitSequence = ''; - for ($i = 0; $i < $length; $i += 40) { - $value = unpack('H*', $secureRandom->nextBytes(5)); - $value = str_pad(base_convert($value[1], 16, 2), 40, '0', STR_PAD_LEFT); - $bitSequence .= $value; - } - - return substr($bitSequence, 0, $length); - } -} diff --git a/src/Symfony/Component/Security/Core/Util/SecureRandom.php b/src/Symfony/Component/Security/Core/Util/SecureRandom.php deleted file mode 100644 index f4167e4d2f41b..0000000000000 --- a/src/Symfony/Component/Security/Core/Util/SecureRandom.php +++ /dev/null @@ -1,112 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Security\Core\Util; - -use Psr\Log\LoggerInterface; - -/** - * A secure random number generator implementation. - * - * @author Fabien Potencier - * @author Johannes M. Schmitt - */ -final class SecureRandom implements SecureRandomInterface -{ - private $logger; - private $useOpenSsl; - private $seed; - private $seedUpdated; - private $seedLastUpdatedAt; - private $seedFile; - - /** - * Constructor. - * - * Be aware that a guessable seed will severely compromise the PRNG - * algorithm that is employed. - * - * @param string $seedFile - * @param LoggerInterface $logger - */ - public function __construct($seedFile = null, LoggerInterface $logger = null) - { - $this->seedFile = $seedFile; - $this->logger = $logger; - - // determine whether to use OpenSSL - if (!function_exists('openssl_random_pseudo_bytes')) { - if (null !== $this->logger) { - $this->logger->notice('It is recommended that you enable the "openssl" extension for random number generation.'); - } - $this->useOpenSsl = false; - } else { - $this->useOpenSsl = true; - } - } - - /** - * {@inheritdoc} - */ - public function nextBytes($nbBytes) - { - // try OpenSSL - if ($this->useOpenSsl) { - $bytes = openssl_random_pseudo_bytes($nbBytes, $strong); - - if (false !== $bytes && true === $strong) { - return $bytes; - } - - if (null !== $this->logger) { - $this->logger->info('OpenSSL did not produce a secure random number.'); - } - } - - // initialize seed - if (null === $this->seed) { - if (null === $this->seedFile) { - throw new \RuntimeException('You need to specify a file path to store the seed.'); - } - - if (is_file($this->seedFile)) { - list($this->seed, $this->seedLastUpdatedAt) = $this->readSeed(); - } else { - $this->seed = uniqid(mt_rand(), true); - $this->updateSeed(); - } - } - - $bytes = ''; - while (strlen($bytes) < $nbBytes) { - static $incr = 1; - $bytes .= hash('sha512', $incr++.$this->seed.uniqid(mt_rand(), true).$nbBytes, true); - $this->seed = base64_encode(hash('sha512', $this->seed.$bytes.$nbBytes, true)); - $this->updateSeed(); - } - - return substr($bytes, 0, $nbBytes); - } - - private function readSeed() - { - return json_decode(file_get_contents($this->seedFile)); - } - - private function updateSeed() - { - if (!$this->seedUpdated && $this->seedLastUpdatedAt < time() - mt_rand(1, 10)) { - file_put_contents($this->seedFile, json_encode(array($this->seed, microtime(true)))); - } - - $this->seedUpdated = true; - } -} diff --git a/src/Symfony/Component/Security/Core/Util/SecureRandomInterface.php b/src/Symfony/Component/Security/Core/Util/SecureRandomInterface.php deleted file mode 100644 index 87d3aceeebf39..0000000000000 --- a/src/Symfony/Component/Security/Core/Util/SecureRandomInterface.php +++ /dev/null @@ -1,29 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Component\Security\Core\Util; - -/** - * Interface that needs to be implemented by all secure random number generators. - * - * @author Fabien Potencier - */ -interface SecureRandomInterface -{ - /** - * Generates the specified number of secure random bytes. - * - * @param int $nbBytes - * - * @return string - */ - public function nextBytes($nbBytes); -} diff --git a/src/Symfony/Component/Security/Csrf/Tests/TokenGenerator/UriSafeTokenGeneratorTest.php b/src/Symfony/Component/Security/Csrf/Tests/TokenGenerator/UriSafeTokenGeneratorTest.php index 1b325e5d1e8c0..e4ea80c50788c 100644 --- a/src/Symfony/Component/Security/Csrf/Tests/TokenGenerator/UriSafeTokenGeneratorTest.php +++ b/src/Symfony/Component/Security/Csrf/Tests/TokenGenerator/UriSafeTokenGeneratorTest.php @@ -44,8 +44,7 @@ public static function setUpBeforeClass() protected function setUp() { - $this->random = $this->getMock('Symfony\Component\Security\Core\Util\SecureRandomInterface'); - $this->generator = new UriSafeTokenGenerator($this->random, self::ENTROPY); + $this->generator = new UriSafeTokenGenerator(self::ENTROPY); } protected function tearDown() @@ -56,11 +55,6 @@ protected function tearDown() public function testGenerateToken() { - $this->random->expects($this->once()) - ->method('nextBytes') - ->with(self::ENTROPY / 8) - ->will($this->returnValue(self::$bytes)); - $token = $this->generator->generateToken(); $this->assertTrue(ctype_print($token), 'is printable'); diff --git a/src/Symfony/Component/Security/Csrf/TokenGenerator/UriSafeTokenGenerator.php b/src/Symfony/Component/Security/Csrf/TokenGenerator/UriSafeTokenGenerator.php index edeb435138f21..f331803bd6c83 100644 --- a/src/Symfony/Component/Security/Csrf/TokenGenerator/UriSafeTokenGenerator.php +++ b/src/Symfony/Component/Security/Csrf/TokenGenerator/UriSafeTokenGenerator.php @@ -11,9 +11,6 @@ namespace Symfony\Component\Security\Csrf\TokenGenerator; -use Symfony\Component\Security\Core\Util\SecureRandomInterface; -use Symfony\Component\Security\Core\Util\SecureRandom; - /** * Generates CSRF tokens. * @@ -23,13 +20,6 @@ */ class UriSafeTokenGenerator implements TokenGeneratorInterface { - /** - * The generator for random values. - * - * @var SecureRandomInterface - */ - private $random; - /** * The amount of entropy collected for each token (in bits). * @@ -40,14 +30,10 @@ class UriSafeTokenGenerator implements TokenGeneratorInterface /** * Generates URI-safe CSRF tokens. * - * @param SecureRandomInterface|null $random The random value generator used for - * generating entropy - * @param int $entropy The amount of entropy collected for - * each token (in bits) + * @param int $entropy The amount of entropy collected for each token (in bits) */ - public function __construct(SecureRandomInterface $random = null, $entropy = 256) + public function __construct($entropy = 256) { - $this->random = $random ?: new SecureRandom(); $this->entropy = $entropy; } @@ -59,7 +45,7 @@ public function generateToken() // Generate an URI safe base64 encoded string that does not contain "+", // "/" or "=" which need to be URL encoded and make URLs unnecessarily // longer. - $bytes = $this->random->nextBytes($this->entropy / 8); + $bytes = random_bytes($this->entropy / 8); return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='); } diff --git a/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php b/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php index 3e465d68704d0..53666a0006fc2 100644 --- a/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php +++ b/src/Symfony/Component/Security/Http/RememberMe/PersistentTokenBasedRememberMeServices.php @@ -19,7 +19,6 @@ use Symfony\Component\Security\Core\Exception\CookieTheftException; use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; -use Symfony\Component\Security\Core\Util\SecureRandomInterface; use Psr\Log\LoggerInterface; /** @@ -32,23 +31,19 @@ class PersistentTokenBasedRememberMeServices extends AbstractRememberMeServices { private $tokenProvider; - private $secureRandom; /** * Constructor. * - * @param array $userProviders - * @param string $secret - * @param string $providerKey - * @param array $options - * @param LoggerInterface $logger - * @param SecureRandomInterface $secureRandom + * @param array $userProviders + * @param string $secret + * @param string $providerKey + * @param array $options + * @param LoggerInterface $logger */ - public function __construct(array $userProviders, $secret, $providerKey, array $options = array(), LoggerInterface $logger = null, SecureRandomInterface $secureRandom) + public function __construct(array $userProviders, $secret, $providerKey, array $options = array(), LoggerInterface $logger = null) { parent::__construct($userProviders, $secret, $providerKey, $options, $logger); - - $this->secureRandom = $secureRandom; } /** @@ -98,7 +93,7 @@ protected function processAutoLoginCookie(array $cookieParts, Request $request) throw new AuthenticationException('The cookie has expired.'); } - $tokenValue = base64_encode($this->secureRandom->nextBytes(64)); + $tokenValue = base64_encode(random_bytes(64)); $this->tokenProvider->updateToken($series, $tokenValue, new \DateTime()); $request->attributes->set(self::COOKIE_ATTR_NAME, new Cookie( @@ -120,8 +115,8 @@ protected function processAutoLoginCookie(array $cookieParts, Request $request) */ protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token) { - $series = base64_encode($this->secureRandom->nextBytes(64)); - $tokenValue = base64_encode($this->secureRandom->nextBytes(64)); + $series = base64_encode(random_bytes(64)); + $tokenValue = base64_encode(random_bytes(64)); $this->tokenProvider->createNewToken( new PersistentToken( diff --git a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php index 889211c96d7d7..e565f82d6c485 100644 --- a/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php +++ b/src/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.php @@ -20,7 +20,6 @@ use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices; use Symfony\Component\Security\Core\Exception\TokenNotFoundException; use Symfony\Component\Security\Core\Exception\CookieTheftException; -use Symfony\Component\Security\Core\Util\SecureRandom; class PersistentTokenBasedRememberMeServicesTest extends \PHPUnit_Framework_TestCase { @@ -311,7 +310,7 @@ protected function getService($userProvider = null, $options = array(), $logger $userProvider = $this->getProvider(); } - return new PersistentTokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger, new SecureRandom(sys_get_temp_dir().'/_sf2.seed')); + return new PersistentTokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger); } protected function getProvider() diff --git a/src/Symfony/Component/Security/composer.json b/src/Symfony/Component/Security/composer.json index 3bea5b8a4c483..4ec8b2a6a6241 100644 --- a/src/Symfony/Component/Security/composer.json +++ b/src/Symfony/Component/Security/composer.json @@ -19,7 +19,8 @@ "php": ">=5.5.9", "symfony/event-dispatcher": "~2.8|~3.0", "symfony/http-foundation": "~2.8|~3.0", - "symfony/http-kernel": "~2.8|~3.0" + "symfony/http-kernel": "~2.8|~3.0", + "paragonie/random_compat" : "~1.0" }, "replace": { "symfony/security-core": "self.version",