Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Security] Add BCrypt password encoder #5974

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

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
-----

* Added PBKDF2 Password encoder
* Added BCrypt password encoder

2.1.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,11 @@ private function addEncodersSection(ArrayNodeDefinition $rootNode)
->booleanNode('ignore_case')->defaultFalse()->end()
->booleanNode('encode_as_base64')->defaultTrue()->end()
->scalarNode('iterations')->defaultValue(5000)->end()
->integerNode('cost')
->min(4)
->max(31)
->defaultValue(13)
->end()
->scalarNode('id')->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
Expand Down Expand Up @@ -464,6 +465,18 @@ private function createEncoder($config, ContainerBuilder $container)
);
}

// bcrypt encoder
if ('bcrypt' === $config['algorithm']) {
$container->setDefinition('security.encoder.bcrypt', new Definition(
$container->getParameter('security.encoder.bcrypt.class'), array(
Copy link
Member

Choose a reason for hiding this comment

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

you should not get the value of the parameter here. The definition should use the parameter for its class, not the value of the param. The resolution should be done only later when optimizing the container

new Reference('security.secure_random'),
$config['cost'],
)
));

return new Reference('security.encoder.bcrypt');
}
Copy link
Member

Choose a reason for hiding this comment

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

This will not work if you define several encoders using bcrypt (for different classes) as you are forcing the id.

You should return the data needed to build the encoder instead, like done for other encoders

Copy link

Choose a reason for hiding this comment

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

How do you return the reference to the service "security.secure_random" then, that the bcrypt encoder needs in its constructor?
Symfony\Component\Security\Core\Encoder\EncoderFactory->createEncoder($config) only allows a plain array with no references to the DI container to be passed in $config['arguments'].

Copy link
Member

Choose a reason for hiding this comment

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

Well, you may need to refactor some stuff. But the way you do it currently is broken as soon as you have several classes using bcrypt (they would all use the config of the last one, thus not respecting the cost)

Copy link

Choose a reason for hiding this comment

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

I guess @elnur could take a look at how it is done in the method Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory->createAuthProvider()

There a new definition is created in the DI container for each instance. I guess that the same thing needs to be done here.

Copy link

Choose a reason for hiding this comment

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

Another (and more clean solution) is to rewrite the class Symfony\Component\Security\Core\Encoder\EncoderFactory so that it does not try to create the Encoder objects on its own (using $reflection->newInstanceArgs()), but instead makes use of the DI to create a new service. In that way the created encoder service may depend on other services in a clean way. But that is a major rewrite of that class, so I guess it would have to be approved by @fabpot first.

Copy link

Choose a reason for hiding this comment

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

Anyone got any more input on how to resolve this?


// message digest encoder
$arguments = array(
$config['algorithm'],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<parameter key="security.encoder.digest.class">Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder</parameter>
<parameter key="security.encoder.plain.class">Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder</parameter>
<parameter key="security.encoder.pbkdf2.class">Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder</parameter>
<parameter key="security.encoder.bcrypt.class">Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder</parameter>

<parameter key="security.user.provider.in_memory.class">Symfony\Component\Security\Core\User\InMemoryUserProvider</parameter>
<parameter key="security.user.provider.in_memory.user.class">Symfony\Component\Security\Core\User\User</parameter>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@
'iterations' => 5,
'key_length' => 30,
),
'JMS\FooBundle\Entity\User6' => array(
'algorithm' => 'bcrypt',
'cost' => 15,
),
),
'providers' => array(
'default' => array(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

<encoder class="JMS\FooBundle\Entity\User5" algorithm="pbkdf2" hash-algorithm="sha1" encode-as-base64="false" iterations="5" key-length="30" />

<encoder class="JMS\FooBundle\Entity\User6" algorithm="bcrypt" cost="15" />

<provider name="default">
<memory>
<user name="foo" password="foo" roles="ROLE_USER" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ security:
encode_as_base64: false
iterations: 5
key_length: 30
JMS\FooBundle\Entity\User6:
algorithm: bcrypt
cost: 15

providers:
default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ public function testEncoders()
'class' => new Parameter('security.encoder.pbkdf2.class'),
'arguments' => array('sha1', false, 5, 30),
),
'JMS\FooBundle\Entity\User6' => new Reference('security.encoder.bcrypt'),
)), $container->getDefinition('security.encoder_factory.generic')->getArguments());
}

Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
implements EventSubscriberInterface
* added secure random number generator
* added PBKDF2 Password encoder
* added BCrypt password encoder

2.1.0
-----
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Core\Encoder;

use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;
use Symfony\Component\Security\Core\Util\SecureRandomInterface;

define('BCRYPT_PREFIX', '$' . (version_compare(phpversion(), '5.3.7', '>=') ? '2y' : '2a') . '$');
Copy link
Member

Choose a reason for hiding this comment

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

Do you really need a define call here ? and what if another file already defined BCRYPT_PREFIX ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

What are my other options? I can't define a dynamic class constant.

Copy link
Member

Choose a reason for hiding this comment

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

well, at least using a more specific name to make clashes less likely (SYMFONY_BCRYPT_PREFIX for instance), and wrapping it in a defined check

Copy link

Choose a reason for hiding this comment

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

Why do we need a define. if version_check is really that expensive, then it could be set into a private static inside a class in constructor..


/**
* @author Elnur Abdurrakhimov <[email protected]>
*/
class BCryptPasswordEncoder extends BasePasswordEncoder
{
/**
* @var SecureRandomInterface
*/
private $secureRandom;

/**
* @var string
*/
private $cost;

/**
* @param SecureRandomInterface $secureRandom
* @param int $cost
* @throws \InvalidArgumentException
*/
public function __construct(SecureRandomInterface $secureRandom, $cost)
{
$this->secureRandom = $secureRandom;
$cost = (int) $cost;

if ($cost < 4 || $cost > 31) {
throw new \InvalidArgumentException('Cost must be in the range of 4-31');
}

$this->cost = sprintf("%02d", $cost);
}

/**
* {@inheritdoc}
*/
public function encodePassword($raw, $salt = null)
{
$salt = $this->generateSalt();
Copy link
Member

Choose a reason for hiding this comment

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

The salt can't be generated in this function as it returns only the encoded password.

Copy link

Choose a reason for hiding this comment

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

Sure it can be generated here. The salt will be in the first 29 characters of the returned value, and the actual encoding of the password in the next 31 characters, giving a total of 60 characters in the returned string. (See php's documentation of the function crypt)

Copy link
Member

Choose a reason for hiding this comment

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

Ok. Thanks.


return crypt($raw, BCRYPT_PREFIX . $this->cost . '$' . $salt);
}

/**
* {@inheritdoc}
*/
public function isPasswordValid($encoded, $raw, $salt = null)
{
return $this->comparePasswords($encoded, crypt($raw, $encoded));
}

/**
* @return string
*/
private function generateSalt()
{
$bytes = $this->secureRandom->nextBytes(16);

return str_replace('+', '.', base64_encode($bytes));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Tests\Core\Encoder;

use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;

/**
* @author Elnur Abdurrakhimov <[email protected]>
*/
class BCryptPasswordEncoderTest extends \PHPUnit_Framework_TestCase
{
const PASSWORD = 'password';
const BYTES = '0123456789abcdef';
const VALID_COST = '04';

const SECURE_RANDOM_INTERFACE = 'Symfony\Component\Security\Core\Util\SecureRandomInterface';

/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $secureRandom;

protected function setUp()
{
$this->secureRandom = $this->getMock(self::SECURE_RANDOM_INTERFACE);

$this->secureRandom
->expects($this->any())
->method('nextBytes')
->will($this->returnValue(self::BYTES))
;
}

/**
* @expectedException \InvalidArgumentException
*/
public function testCostBelowRange()
{
new BCryptPasswordEncoder($this->secureRandom, 3);
}

/**
* @expectedException \InvalidArgumentException
*/
public function testCostAboveRange()
{
new BCryptPasswordEncoder($this->secureRandom, 32);
}

public function testCostInRange()
{
for ($cost = 4; $cost <= 31; $cost++) {
new BCryptPasswordEncoder($this->secureRandom, $cost);
}
}

public function testResultLength()
{
$encoder = new BCryptPasswordEncoder($this->secureRandom, self::VALID_COST);
$result = $encoder->encodePassword(self::PASSWORD);
$this->assertEquals(60, strlen($result));
}

public function testValidation()
{
$encoder = new BCryptPasswordEncoder($this->secureRandom, self::VALID_COST);
$result = $encoder->encodePassword(self::PASSWORD);
$this->assertTrue($encoder->isPasswordValid($result, self::PASSWORD));
$this->assertFalse($encoder->isPasswordValid($result, 'anotherPassword'));
}

public function testSecureRandomIsUsed()
{
$this->secureRandom
->expects($this->atLeastOnce())
->method('nextBytes')
;

$salt = str_replace('+', '.', base64_encode(self::BYTES));

$encoder = new BCryptPasswordEncoder($this->secureRandom, self::VALID_COST);
$result = $encoder->encodePassword(self::PASSWORD);
$expected = crypt(self::PASSWORD, BCRYPT_PREFIX . self::VALID_COST . '$' . $salt . '$');

$this->assertEquals($expected, $result);
}
}