diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md index 2a719ed..93cd53e 100644 --- a/CHANGELOG-7.0.md +++ b/CHANGELOG-7.0.md @@ -16,6 +16,28 @@ to fix the user id conversion in `UserPropertiesRepository` (see Bug Fixes). ## Breaking Changes +### Passwords are hashed with bcrypt + +`UserModel` hashes passwords with the new `PasswordBcryptMapper` instead of `PasswordSha1Mapper` +(unsalted SHA-1). + +- **Widen the password column** to `VARCHAR(255)`: a bcrypt hash has 60 characters, and a new user + or a changed password does not fit in the `CHAR(40)` of a SHA-1 column. +- **Existing users keep logging in.** The bcrypt mapper verifies a 40-character SHA-1 hash too, and + the new `UsersService::rehashPasswordIfNeeded()` replaces it with a bcrypt hash at that user's next + login: `createAuthToken()` calls it; a login of your own calls it after `isValidUser()`, which only + checks the password. It reads the new hash back and keeps the old one when the column is too short + (rejected or truncated), so nobody is locked out before the column is widened. +- **To keep SHA-1**, select `PasswordSha1Mapper` on the password field of your user model: + `#[FieldAttribute(updateFunction: PasswordSha1Mapper::class)]`. +- `UsersServiceInterface` has the new `rehashPasswordIfNeeded()`. +- **Custom password mappers** implement two new methods of `PasswordMapperInterface`: + `verifyPassword(string $password, string $hash): bool` and `needsRehash(string $hash): bool`. + `isValidUser()` uses them instead of comparing the hash of the password with `===`; a SHA-1 or + MD5 mapper verifies with `hash_equals()` and returns `false` from `needsRehash()`. +- `UserModel::setPassword()` asks the password mapper whether a value is already a hash (it skipped + the password definition for any 40-character value). + ### Dependencies | Package | 6.x | 7.0 | diff --git a/docs/authentication.md b/docs/authentication.md index 8123fd7..f9053b3 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -28,7 +28,8 @@ The `isValidUser()` method uses the login field configured in your `UsersService ## Password Hashing -By default, passwords are automatically hashed using SHA-1 when saved. The library uses the `PasswordSha1Mapper` for this purpose. +By default, passwords are hashed with bcrypt when saved, by the `PasswordBcryptMapper` of +`UserModel`. The password column needs 60 characters; `VARCHAR(255)` leaves room for other algorithms. ```php setPassword('plaintext password'); $users->save($user); -// The password is stored as SHA-1 hash in the database +// The password is stored as a bcrypt hash ($2y$...) in the database ``` -:::warning SHA-1 Deprecation -SHA-1 is used for backward compatibility. For new projects, consider implementing a custom password hasher using bcrypt or Argon2. See [Mappers](mappers.md) for details. +The bcrypt mapper also reads the SHA-1 hashes of `PasswordSha1Mapper`, the default before 7.0: a +stored 40-character hash still logs in. At login, `createAuthToken()` replaces it with a bcrypt hash, +so users move to bcrypt as they log in, without a password reset. A bcrypt hash with a lower cost than +PHP's current one is replaced the same way. `isValidUser()` only checks the password and never writes. + +A login of your own (without `createAuthToken()`) upgrades the hash with `rehashPasswordIfNeeded()`: + +```php +isValidUser($login, $password); +if ($user !== null) { + $users->rehashPasswordIfNeeded($user, $password); +} +``` + +`rehashPasswordIfNeeded()` reads the new hash back. If the password column is too short for it (the +`CHAR(40)` of a SHA-1 schema), the new hash is rejected or truncated by the database; the method then +keeps the old hash and returns `false`, so the user can still log in. Widen the column to upgrade. + +To keep SHA-1, select its mapper in your user model: + +```php +isPasswordEncrypted($value)) { + return $value; + } + + // Leave null + if (empty($value)) { + return null; + } + + return password_hash((string)$value, PASSWORD_BCRYPT); + } + + #[\Override] + public function isPasswordEncrypted(mixed $password): bool + { + return is_string($password) && ($this->isBcrypt($password) || $this->isSha1($password)); + } + + #[\Override] + public function verifyPassword(string $password, string $hash): bool + { + if ($this->isBcrypt($hash)) { + return password_verify($password, $hash); + } + if ($this->isSha1($hash)) { + return hash_equals(strtolower($hash), sha1($password)); + } + return false; + } + + #[\Override] + public function needsRehash(string $hash): bool + { + return !$this->isBcrypt($hash) || password_needs_rehash($hash, PASSWORD_BCRYPT); + } + + private function isBcrypt(string $hash): bool + { + return strlen($hash) === 60 && password_get_info($hash)['algo'] === PASSWORD_BCRYPT; + } + + private function isSha1(string $hash): bool + { + return strlen($hash) === 40 && ctype_xdigit($hash); + } +} diff --git a/src/MapperFunctions/PasswordSha1Mapper.php b/src/MapperFunctions/PasswordSha1Mapper.php index db3b79d..7558e4e 100644 --- a/src/MapperFunctions/PasswordSha1Mapper.php +++ b/src/MapperFunctions/PasswordSha1Mapper.php @@ -6,7 +6,8 @@ use ByJG\Authenticate\Interfaces\PasswordMapperInterface; /** - * Mapper function to hash passwords using SHA1 + * Mapper function to hash passwords using SHA1 (unsalted). PasswordBcryptMapper, the default, + * also reads these hashes and upgrades them; select this mapper only to keep SHA-1. */ class PasswordSha1Mapper implements PasswordMapperInterface { @@ -32,4 +33,16 @@ public function isPasswordEncrypted(mixed $password): bool { return (is_string($password) && strlen($password) === 40); } + + #[\Override] + public function verifyPassword(string $password, string $hash): bool + { + return hash_equals(strtolower($hash), sha1($password)); + } + + #[\Override] + public function needsRehash(string $hash): bool + { + return false; + } } diff --git a/src/Model/UserModel.php b/src/Model/UserModel.php index 85ccdc8..cd5ffc3 100644 --- a/src/Model/UserModel.php +++ b/src/Model/UserModel.php @@ -3,7 +3,7 @@ namespace ByJG\Authenticate\Model; use ByJG\Authenticate\Definition\PasswordDefinition; -use ByJG\Authenticate\MapperFunctions\PasswordSha1Mapper; +use ByJG\Authenticate\MapperFunctions\PasswordBcryptMapper; use ByJG\MicroOrm\Attributes\FieldAttribute; use ByJG\MicroOrm\Attributes\TableAttribute; use ByJG\MicroOrm\Literal\Literal; @@ -30,7 +30,7 @@ class UserModel #[FieldAttribute] protected ?string $username = null; - #[FieldAttribute(updateFunction: PasswordSha1Mapper::class)] + #[FieldAttribute(updateFunction: PasswordBcryptMapper::class)] protected ?string $password = null; #[FieldAttribute] @@ -136,8 +136,8 @@ public function getPassword(): ?string */ public function setPassword(?string $password): void { - // Password len equals to 40 means that the password is already encrypted with sha1 - if (!empty($this->passwordDefinition) && !empty($password) && strlen($password) != 40) { + // A hash (read from the database) is not checked against the password definition + if (!empty($this->passwordDefinition) && !empty($password) && !$this->isPasswordHash($password)) { $match = $this->passwordDefinition->matchPassword($password); if ($match != PasswordDefinition::SUCCESS) { throw new InvalidArgumentException("Password does not match the password definition [$match]"); @@ -147,6 +147,19 @@ public function setPassword(?string $password): void $this->password = $password; } + /** + * Whether the value is a hash, by the password mapper UsersService registers on the + * password definition; the default mapper when there is none. + */ + protected function isPasswordHash(string $password): bool + { + $mapper = $this->passwordDefinition?->getPasswordMapper() ?? PasswordBcryptMapper::class; + if (is_string($mapper)) { + $mapper = new $mapper(); + } + return $mapper->isPasswordEncrypted($password); + } + /** * @return string|null */ diff --git a/src/Service/UsersService.php b/src/Service/UsersService.php index c706e5e..d0afc4e 100644 --- a/src/Service/UsersService.php +++ b/src/Service/UsersService.php @@ -22,6 +22,7 @@ use ByJG\MicroOrm\Query; use Exception; use InvalidArgumentException; +use Throwable; /** * Service for User operations - Business Logic Layer @@ -348,18 +349,59 @@ public function isValidUser(string $login, string $password): ?UserModel return null; } - // Hash the password for comparison using the model's configured password mapper + // The model's password mapper verifies the password against the stored hash + if (!$this->passwordMapper()->verifyPassword($password, (string)$user->getPassword())) { + return null; + } + + return $user; + } + + /** + * @inheritDoc + */ + #[\Override] + public function rehashPasswordIfNeeded(UserModel $user, string $password): bool + { + $mapper = $this->passwordMapper(); + $oldHash = (string)$user->getPassword(); + if (!$mapper->needsRehash($oldHash)) { + return false; + } + + // Set as a hash: an existing password is not checked against the password definition + $user->setPassword((string)$mapper->processedValue($password, $user)); + try { + $this->usersRepository->save($user); + $stored = $this->usersRepository->getById($user->getUserid() ?? '')?->getPassword(); + if ($mapper->verifyPassword($password, (string)$stored)) { + return true; + } + } catch (Throwable) { + // A column too short for the new hash, in strict mode: nothing was written + } + + // Not stored, or stored truncated (a column too short, without strict mode): keep the old hash + $user->setPassword($oldHash); + $this->usersRepository->save($user); + return false; + } + + /** + * The password mapper of the user model (the constructor checks it is a PasswordMapperInterface) + */ + protected function passwordMapper(): PasswordMapperInterface + { $passwordFieldMapping = $this->usersRepository->getMapper()->getFieldMap(UserField::Password->value); if ($passwordFieldMapping === null) { throw new InvalidArgumentException('Password field mapping not found'); } - $hashedPassword = $passwordFieldMapping->getUpdateFunctionValue($password, null); - - if ($user->getPassword() === $hashedPassword) { - return $user; + $mapper = $passwordFieldMapping->getUpdateFunction(); + if (is_string($mapper)) { + $mapper = new $mapper(); } - - return null; + /** @var PasswordMapperInterface $mapper */ + return $mapper; } /** @@ -638,6 +680,7 @@ public function createAuthToken( if (is_null($user)) { throw new UserNotFoundException('User not found'); } + $this->rehashPasswordIfNeeded($user, $password); return $this->createInsecureAuthToken( $user, diff --git a/tests/Fixture/PasswordMd5Mapper.php b/tests/Fixture/PasswordMd5Mapper.php index e845549..3c6709e 100644 --- a/tests/Fixture/PasswordMd5Mapper.php +++ b/tests/Fixture/PasswordMd5Mapper.php @@ -32,4 +32,16 @@ public function isPasswordEncrypted(mixed $password): bool { return is_string($password) && strlen($password) === 32 && ctype_xdigit($password); } + + #[\Override] + public function verifyPassword(string $password, string $hash): bool + { + return hash_equals(strtolower($hash), md5($password)); + } + + #[\Override] + public function needsRehash(string $hash): bool + { + return false; + } } diff --git a/tests/PasswordBcryptMapperTest.php b/tests/PasswordBcryptMapperTest.php new file mode 100644 index 0000000..c3c0fcc --- /dev/null +++ b/tests/PasswordBcryptMapperTest.php @@ -0,0 +1,70 @@ +mapper = new PasswordBcryptMapper(); + } + + public function testHashesWithBcrypt(): void + { + $hash = (string)$this->mapper->processedValue('mySecret1', null); + + $this->assertSame(PASSWORD_BCRYPT, password_get_info($hash)['algo']); + $this->assertSame(60, strlen($hash)); + $this->assertNotSame($hash, $this->mapper->processedValue('mySecret1', null), 'bcrypt salts every hash'); + } + + public function testKeepsAHashAsIs(): void + { + $bcrypt = password_hash('mySecret1', PASSWORD_BCRYPT); + $sha1 = sha1('mySecret1'); + + $this->assertSame($bcrypt, $this->mapper->processedValue($bcrypt, null)); + $this->assertSame($sha1, $this->mapper->processedValue($sha1, null)); + $this->assertNull($this->mapper->processedValue('', null)); + } + + public function testRecognizesHashes(): void + { + $this->assertTrue($this->mapper->isPasswordEncrypted(password_hash('x', PASSWORD_BCRYPT))); + $this->assertTrue($this->mapper->isPasswordEncrypted(sha1('x'))); + $this->assertFalse($this->mapper->isPasswordEncrypted('mySecret1')); + $this->assertFalse($this->mapper->isPasswordEncrypted(str_repeat('z', 40)), '40 characters but not hexadecimal'); + $this->assertFalse($this->mapper->isPasswordEncrypted(str_repeat('z', 60)), '60 characters but not bcrypt'); + } + + public function testVerifiesBcrypt(): void + { + $hash = password_hash('mySecret1', PASSWORD_BCRYPT); + + $this->assertTrue($this->mapper->verifyPassword('mySecret1', $hash)); + $this->assertFalse($this->mapper->verifyPassword('wrong', $hash)); + } + + public function testVerifiesSha1(): void + { + $hash = sha1('mySecret1'); + + $this->assertTrue($this->mapper->verifyPassword('mySecret1', $hash)); + $this->assertTrue($this->mapper->verifyPassword('mySecret1', strtoupper($hash))); + $this->assertFalse($this->mapper->verifyPassword('wrong', $hash)); + $this->assertFalse($this->mapper->verifyPassword('mySecret1', 'not a hash')); + } + + public function testNeedsRehash(): void + { + $this->assertTrue($this->mapper->needsRehash(sha1('mySecret1')), 'SHA-1 is upgraded'); + $this->assertTrue($this->mapper->needsRehash(password_hash('mySecret1', PASSWORD_BCRYPT, ['cost' => 4])), 'a lower cost is upgraded'); + $this->assertFalse($this->mapper->needsRehash(password_hash('mySecret1', PASSWORD_BCRYPT))); + } +} diff --git a/tests/PasswordUpgradeTest.php b/tests/PasswordUpgradeTest.php new file mode 100644 index 0000000..5e14860 --- /dev/null +++ b/tests/PasswordUpgradeTest.php @@ -0,0 +1,182 @@ +executor = DatabaseExecutor::using(Factory::getDbInstance('sqlite://' . self::DATABASE)); + $this->executor->execute("create table users ( + userid integer primary key autoincrement, + name varchar(45), + email varchar(200), + username varchar(20), + $passwordColumn, + created_at datetime default (datetime('2017-12-04')), + updated_at datetime, + deleted_at datetime, + role varchar(20));" + ); + $this->executor->execute('create table users_property ( + id integer primary key autoincrement, + userid integer, + name varchar(45), + value varchar(45));' + ); + if ($trigger !== null) { + $this->executor->execute($trigger); + } + + // A user saved by an older version: SHA-1, and a password weaker than today's definition + $this->executor->execute( + "insert into users (name, email, username, password, role) values ('Old User', 'old@example.com', 'old', '" . sha1('old') . "', 'user')" + ); + + $this->service = new UsersService( + new UsersRepository($this->executor, UserModel::class), + new UserPropertiesRepository($this->executor, UserPropertiesModel::class), + LoginField::Username, + new PasswordDefinition() + ); + } + + #[\Override] + protected function tearDown(): void + { + if (file_exists(self::DATABASE)) { + unlink(self::DATABASE); + } + } + + private function storedPassword(): string + { + return (string)$this->executor->getScalar("select password from users where username = 'old'"); + } + + private function login(): void + { + $jwt = new JwtWrapper('api.test.com', new JwtHashHmacSecret(base64_encode(str_repeat('s', 64)))); + $this->service->createAuthToken('old', 'old', $jwt); + } + + public function testIsValidUserDoesNotWrite(): void + { + $this->createDatabase(); + + $this->assertNotNull($this->service->isValidUser('old', 'old')); + $this->assertSame(sha1('old'), $this->storedPassword()); + } + + public function testRehashReplacesASha1Hash(): void + { + $this->createDatabase(); + $user = $this->service->isValidUser('old', 'old'); + + $this->assertTrue($this->service->rehashPasswordIfNeeded($user, 'old')); + $this->assertSame(PASSWORD_BCRYPT, password_get_info($this->storedPassword())['algo']); + $this->assertTrue(password_verify('old', $this->storedPassword())); + $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the next login uses the bcrypt hash'); + } + + public function testRehashKeepsACurrentBcryptHash(): void + { + $this->createDatabase(); + $this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old'); + $hash = $this->storedPassword(); + + $this->assertFalse($this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old')); + $this->assertSame($hash, $this->storedPassword()); + } + + public function testLoginUpgradesTheHash(): void + { + $this->createDatabase(); + + $this->login(); + + $this->assertSame(PASSWORD_BCRYPT, password_get_info($this->storedPassword())['algo']); + } + + public function testWrongPasswordIsNotUpgraded(): void + { + $this->createDatabase(); + + $this->assertNull($this->service->isValidUser('old', 'wrong')); + try { + $jwt = new JwtWrapper('api.test.com', new JwtHashHmacSecret(base64_encode(str_repeat('s', 64)))); + $this->service->createAuthToken('old', 'wrong', $jwt); + $this->fail('A wrong password logged in'); + } catch (UserNotFoundException) { + } + $this->assertSame(sha1('old'), $this->storedPassword()); + } + + /** + * A column that rejects the longer hash (as MySQL does in strict mode): the user keeps SHA-1 + */ + public function testColumnTooShortRejectingTheHash(): void + { + $this->createDatabase('password varchar(40) check (length(password) <= 40)'); + + $this->assertFalse($this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old')); + $this->assertSame(sha1('old'), $this->storedPassword()); + $this->login(); + $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the user can still log in'); + } + + /** + * A column that truncates the longer hash (as MySQL does without strict mode): the SHA-1 hash + * is restored instead of leaving a truncated bcrypt hash nobody can log in with + */ + public function testColumnTooShortTruncatingTheHash(): void + { + $this->createDatabase('password varchar(40)', "create trigger truncate_password after update of password on users + begin update users set password = substr(new.password, 1, 40) where userid = new.userid; end"); + + $this->assertFalse($this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old')); + $this->assertSame(sha1('old'), $this->storedPassword()); + $this->login(); + $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the user can still log in'); + } + + /** + * A model with a password definition (as Gluo's BaseUser sets in its constructor) is given the + * stored hash when it is loaded: a hash is not checked against the definition + */ + public function testAStoredHashIsNotCheckedAgainstTheDefinition(): void + { + $definition = new PasswordDefinition([PasswordDefinition::MINIMUM_CHARS => 100]); + foreach ([password_hash('old', PASSWORD_BCRYPT), sha1('old')] as $hash) { + $user = (new UserModel())->withPasswordDefinition($definition); + $user->setPassword($hash); + $this->assertSame($hash, $user->getPassword()); + } + } +} diff --git a/tests/TestUsersBase.php b/tests/TestUsersBase.php index 9d47b70..d0c4d54 100644 --- a/tests/TestUsersBase.php +++ b/tests/TestUsersBase.php @@ -470,7 +470,9 @@ public function testGetByUsername(): void $this->assertEquals('User 2', $user->getName()); $this->assertEquals('user2', $user->getUsername()); $this->assertEquals('user2@gmail.com', $user->getEmail()); - $this->assertEquals('c88b5c841897dafe75cdd9f8ba98b32f007d6bc3', $user->getPassword()); + // The stored hash is the one of pwd2, whatever the model's password mapper + $this->assertNotEquals('pwd2', $user->getPassword()); + $this->assertEquals($user->getUserid(), $this->object->isValidUser($this->__chooseValue('user2', 'user2@gmail.com'), 'pwd2')?->getUserid()); } public function testGetByUserProperty(): void @@ -706,7 +708,7 @@ public function testPasswordHashRemainsUnchangedOnSave(): void // Store the original password hash $originalHash = $user->getPassword(); - $this->assertEquals($originalHash, sha1($originalPassword)); + $this->assertNotEquals($originalPassword, $originalHash); // Verify the user can authenticate with the original password $login = $this->__chooseValue('testuser', 'test@example.com'); diff --git a/tests/UsersDBDatasetByUsernameTestUsersBase.php b/tests/UsersDBDatasetByUsernameTestUsersBase.php index 3c9f2e1..f70cf19 100644 --- a/tests/UsersDBDatasetByUsernameTestUsersBase.php +++ b/tests/UsersDBDatasetByUsernameTestUsersBase.php @@ -58,7 +58,8 @@ public function __setUp($loginField) $this->assertEquals(1, $user->getUserid()); $this->assertEquals('User 1', $user->getName()); $this->assertEquals('user1', $user->getUsername()); - $this->assertEquals('a63d4b132a9a1d3430f9ae507825f572449e0d17', $user->getPassword()); + // UserModel hashes with bcrypt by default + $this->assertSame(PASSWORD_BCRYPT, password_get_info((string)$user->getPassword())['algo']); $this->assertEquals('', $user->getRole()); $this->assertNotNull($user->getCreatedAt()); $this->assertMatchesRegularExpression('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $user->getCreatedAt()); @@ -96,7 +97,7 @@ public function testAddUser() $this->assertEquals('John Doe', $user->getName()); $this->assertEquals('john', $user->getUsername()); $this->assertEquals('johndoe@gmail.com', $user->getEmail()); - $this->assertEquals('91dfd9ddb4198affc5c194cd8ce6d338fde470e2', $user->getPassword()); + $this->assertSame(PASSWORD_BCRYPT, password_get_info((string)$user->getPassword())['algo']); $this->assertEquals('', $user->getRole()); $this->assertNotNull($user->getCreatedAt()); $this->assertMatchesRegularExpression('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $user->getCreatedAt());