From fcebaa0db74dc822877128e57a79dcfda2a2dc4f Mon Sep 17 00:00:00 2001 From: Alex Gaynor Date: Sun, 2 Oct 2016 21:20:13 -0400 Subject: [PATCH] Correctly handle invalid hashed passwords in bcrypt.checkpw. (#95) Previously it would silently accept extra data, and overread a buffer on truncated data. Reported by Matthew Russell --- src/bcrypt/__init__.py | 3 +++ tests/test_bcrypt.py | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/bcrypt/__init__.py b/src/bcrypt/__init__.py index cd779a6..301ccb6 100644 --- a/src/bcrypt/__init__.py +++ b/src/bcrypt/__init__.py @@ -106,6 +106,9 @@ def checkpw(password, hashed_password): ret = hashpw(password, hashed_password) + if len(ret) != len(hashed_password): + return False + return _bcrypt.lib.timingsafe_bcmp(ret, hashed_password, len(ret)) == 0 diff --git a/tests/test_bcrypt.py b/tests/test_bcrypt.py index d9bde72..fa9a410 100644 --- a/tests/test_bcrypt.py +++ b/tests/test_bcrypt.py @@ -308,6 +308,15 @@ def test_hashpw_nul_byte(): bcrypt.hashpw(b"abc\0def", salt) +def test_checkpw_extra_data(): + salt = bcrypt.gensalt(4) + hashed = bcrypt.hashpw(b"abc", salt) + + assert bcrypt.checkpw(b"abc", hashed) + assert bcrypt.checkpw(b"abc", hashed + b"extra") is False + assert bcrypt.checkpw(b"abc", hashed[:-10]) is False + + @pytest.mark.parametrize( ("rounds", "password", "salt", "expected"), [[