Skip to content
Merged
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
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,13 +192,40 @@ following OpenBSD bcrypt. Passwords up to 1,024 bytes are accepted; longer
inputs return `{error, invalid_password_length}`. Malformed salts return
`{error, invalid_salt}`. These rules apply to both the NIF and port backends.

`$2b$` rejects embedded NUL bytes with `{error, invalid_password}`. Pass text
`$2b$` and `$2y$` reject embedded NUL bytes with `{error, invalid_password}`. Pass text
passwords as encoded bytes; do not pass raw binary prehashes containing NULs.
Existing `$2a$` hashes retain historical password-length wraparound and NUL
termination semantics for verification. After a successful legacy verification,
generate a fresh salt and rehash with `$2b$`; do not just change the prefix.
Legacy hashes affected by those behaviors may warrant a password reset.

PHP `$2y$` hashes are supported by both backends with the same hashing
semantics as `$2b$`. Pass the stored hash directly to `bcrypt:hashpw/2`;
the returned hash retains `$2y$`, so the usual verification pattern works
without rewriting stored prefixes:

```erlang
%% StoredHash is the PHP hash as a byte list; Password contains the same
%% encoded bytes used in PHP (for example, a UTF-8 binary).
{ok, StoredHash} =:= bcrypt:hashpw(Password, StoredHash).
```

`gen_salt/0` and `gen_salt/1` generate `$2b$` salts. To generate a PHP
`$2y$` hash directly, select the version with `gen_salt(Rounds, Version)`:

```erlang
{ok, Salt} = bcrypt:gen_salt(12, '2y'),
{ok, PhpHash} = bcrypt:hashpw(<<"password">>, Salt).
```

The version must be the atom `'2b'` or `'2y'`, and the cost must be an integer
from 4 to 31. Invalid options raise `function_clause`, as with `gen_salt/1`.
The option works with both backends. `PhpHash` retains `$2y$` and can be
verified using PHP's `password_verify()`.

The same 1,024-byte input limit and NUL-byte rejection apply to `$2y$`;
`$2x$` remains unsupported.

The NIF uses OTP dirty CPU schedulers. Its asynchronous `hashpw/5` interface
uses an Erlang helper process and an opaque reference from `create_ctx/0`;
there are no custom native threads, task queues, or blocking destructors.
Expand Down
3 changes: 2 additions & 1 deletion c_src/bcrypt.c
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ bcrypt_hashpass(const char *key, const char *salt, char *encrypted,
key_len = (u_int8_t)(strlen(key) + 1);
break;
case 'b':
case 'y': /* PHP/crypt_blowfish: identical to $2b$. */
/* strlen() returns a size_t, but the function calls
* below result in implicit casts to a narrower integer
* type, so cap key_len at the actual maximum supported
Expand Down Expand Up @@ -271,7 +272,7 @@ int bcrypt_hash(char *out, size_t outlen, const unsigned char *password,
memchr(salt, 0, salt_len) != NULL)
return BCRYPT_INVALID_SALT;
/* Preserve historical C-string behavior only for legacy verification. */
if (salt[2] == 'b' && password_len &&
if ((salt[2] == 'b' || salt[2] == 'y') && password_len &&
memchr(password, 0, password_len) != NULL)
return BCRYPT_INVALID_PASSWORD;
if (password_len)
Expand Down
2 changes: 1 addition & 1 deletion src/bcrypt.app.src
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
{exclude_files, [
"priv/bcrypt"
]},
{maintainers, ["Hunter Morris", "Mrinal Wadhwa", "ErlangPack"]},
{maintainers, ["ErlangPack"]},
{licenses, ["MIT"]},
{links, [{"Github", "https://github.com/erlangpack/bcrypt"}]}
]}.
16 changes: 14 additions & 2 deletions src/bcrypt.erl
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@
%% API
-export([start/0, stop/0]).
-export([mechanism/0]).
-export([gen_salt/0, gen_salt/1, hashpw/2, is_worker_available/0]).
-export([gen_salt/0, gen_salt/1, gen_salt/2, hashpw/2, is_worker_available/0]).

-type mechanism() :: nif | port.
-type rounds() :: 4..31.
-type version() :: '2b' | '2y'.
-type pwerr() :: invalid_salt | invalid_salt_length | invalid_rounds
| invalid_password | invalid_password_length.

-export_type([ mechanism/0, rounds/0, pwerr/0 ]).
-export_type([ mechanism/0, rounds/0, version/0, pwerr/0 ]).

%% @doc Starts `Application' `bcrypt'.
%% <b>See also:</b>
Expand Down Expand Up @@ -52,6 +53,17 @@ gen_salt() ->
gen_salt(Rounds) when is_integer(Rounds), Rounds < 32, Rounds > 3 ->
do_gen_salt(mechanism(), Rounds).

%% @doc Generate a random salt with an explicit version. Use '2y' for PHP;
%% gen_salt/0 and gen_salt/1 default to '2b'.
-spec gen_salt(rounds(), version()) -> {ok, [byte()]}.
gen_salt(Rounds, '2b') ->
gen_salt(Rounds);
gen_salt(Rounds, '2y') ->
%% Both versions have identical salt encoding. Reuse the backend's secure
%% random generation and select the prefix before any password is hashed.
{ok, "$2b$" ++ Salt} = gen_salt(Rounds),
{ok, "$2y$" ++ Salt}.

%% @doc Make hash string based on `Password' and `Salt'.

-spec hashpw( Password, Salt ) -> Result when
Expand Down
6 changes: 6 additions & 0 deletions test/bcrypt_native_tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ int main(void)
unsigned char password[1025];
unsigned char salt[1024];
const unsigned char valid[] = "$2b$04$......................";
const unsigned char php_salt[] = "$2y$04$......................";
char output[BCRYPT_HASHSIZE];
memset(password, 'A', sizeof(password));
memset(salt, '.', sizeof(salt));
Expand All @@ -31,9 +32,14 @@ int main(void)
assert(bcrypt_hash(output, sizeof(output), password, 72,
salt, 29) == BCRYPT_INVALID_SALT);
}
assert(bcrypt_hash(output, sizeof(output), password, 1024,
php_salt, 29) == BCRYPT_OK);
assert(strlen(output) == 60 && strncmp(output, "$2y$", 4) == 0);
password[0] = 0;
assert(bcrypt_hash(output, sizeof(output), password, 72,
valid, 29) == BCRYPT_INVALID_PASSWORD);
assert(bcrypt_hash(output, sizeof(output), password, 72,
php_salt, 29) == BCRYPT_INVALID_PASSWORD);
bcrypt_clear(password, sizeof(password));
for (size_t i = 0; i < sizeof(password); i++)
assert(password[i] == 0);
Expand Down
79 changes: 79 additions & 0 deletions test/bcrypt_security_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
-include_lib("eunit/include/eunit.hrl").

-define(SALT, <<"$2b$04$......................">>).
-define(PHP_SALT, <<"$2y$04$......................">>).
-define(LEGACY_SALT, <<"$2a$04$......................">>).

security_test_() ->
Expand All @@ -10,7 +11,12 @@ security_test_() ->
fun(_) -> application:stop(bcrypt) end,
fun(_) -> [
?_test(default_version()),
?_test(explicit_salt_version()),
?_test(invalid_salt_options()),
?_test(known_vectors()),
?_test(php_vectors()),
?_test(php_length_boundaries()),
?_test(php_invalid_inputs()),
?_test(length_boundaries()),
?_test(legacy_verification()),
?_test(nul_passwords()),
Expand All @@ -33,6 +39,30 @@ default_version() ->
{ok, "$2b$04$" ++ Encoded} = bcrypt:gen_salt(4),
?assertEqual(22, length(Encoded)).

explicit_salt_version() ->
lists:foreach(fun({Version, Prefix}) ->
%% Check cost boundaries without attempting an expensive cost-31 hash.
lists:foreach(fun(Rounds) ->
{ok, Salt} = bcrypt:gen_salt(Rounds, Version),
ExpectedPrefix = lists:flatten(io_lib:format("~s~2..0B$", [Prefix, Rounds])),
?assert(lists:prefix(ExpectedPrefix, Salt)),
?assertEqual(29, length(Salt))
end, [4, 12, 31]),
{ok, Salt} = bcrypt:gen_salt(4, Version),
{ok, Hash} = bcrypt:hashpw(<<"password">>, Salt),
?assert(lists:prefix(Prefix, Hash)),
?assertEqual({ok, Hash}, bcrypt:hashpw(<<"password">>, Hash)),
?assertNotEqual({ok, Hash}, bcrypt:hashpw(<<"wrong">>, Hash))
end, [{'2b', "$2b$"}, {'2y', "$2y$"}]).

invalid_salt_options() ->
%% Invalid options follow gen_salt/1's existing function_clause behavior.
lists:foreach(fun(Args) ->
?assertError(function_clause, apply(bcrypt, gen_salt, Args))
end, [[4, '2a'], [4, '2x'], [4, "2y"], [4, <<"2y">>],
[3, '2b'], [32, '2b'], [3, '2y'], [32, '2y'], [4.0, '2y']]),
?assertMatch({ok, "$2b$04$" ++ _}, bcrypt:gen_salt(4)).

known_vectors() ->
%% Published Openwall vectors; $2b$ agrees with $2a$ for these inputs.
Salt = "$2b$05$CCCCCCCCCCCCCCCCCCCCC.",
Expand All @@ -42,6 +72,55 @@ known_vectors() ->
{"U*U", "E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"},
{"U*U*", "VGOzA784oUp/Z0DY336zx7pLYAy0lwK"}]).

php_vectors() ->
%% Generated with PHP 8.5.9 crypt($password, '$2y$04$......................').
%% Fixed fixtures keep PHP out of the test/runtime dependencies.
Vectors = [
{<<>>, "w74bL5gU7LSJClZClCa.Pkz14aTv/XO"},
{<<"password">>, "LAtw7/ohmmBAhnXqmkuIz83Rl5Qdjhm"},
{<<"pässwörd"/utf8>>, "qnB8eqNMuizEQ3mLqW93JYyN8aQz3iO"},
{<<255, 128, 163>>, "Ob6ydY8/tzRw2F.YD8ZfQe6VkpynLsi"}
],
lists:foreach(fun({Password, Suffix}) ->
Expected = binary_to_list(?PHP_SALT) ++ Suffix,
%% Both a salt and a stored hash must preserve the $2y$ prefix.
?assertEqual({ok, Expected}, bcrypt:hashpw(Password, ?PHP_SALT)),
?assertEqual({ok, Expected}, bcrypt:hashpw(Password, Expected)),
?assertEqual({ok, Expected},
bcrypt:hashpw(binary_to_list(Password), list_to_binary(Expected))),
?assertNotEqual({ok, Expected}, bcrypt:hashpw(<<"wrong">>, Expected)),
?assertEqual({ok, binary_to_list(?SALT) ++ Suffix},
bcrypt:hashpw(Password, ?SALT))
end, Vectors).

php_length_boundaries() ->
Password = <<"A", (binary:copy(<<"B">>, 1023))/binary>>,
%% PHP reference outputs for 71 bytes and for 72 or more bytes.
Short = binary_to_list(?PHP_SALT) ++ "HngKtCj1MUdG5WavwdNXo.lTVlWjsba",
Long = binary_to_list(?PHP_SALT) ++ "G0G3HvI30KYH1y5QpphZX4Y4p0vztu6",
?assertEqual({ok, Short},
bcrypt:hashpw(binary:part(Password, 0, 71), ?PHP_SALT)),
lists:foreach(fun(N) ->
P = binary:part(Password, 0, N),
?assertEqual({ok, Long}, bcrypt:hashpw(P, ?PHP_SALT)),
?assertEqual({ok, Long}, bcrypt:hashpw(P, Long))
end, [72, 73, 254, 255, 256, 257, 511, 512, 1023, 1024]).

php_invalid_inputs() ->
lists:foreach(fun(Password) ->
?assertEqual({error, invalid_password},
bcrypt:hashpw(Password, ?PHP_SALT))
end, [<<0>>, <<"abc", 0, "def">>, <<"abc", 0>>,
<<(binary:copy(<<"A">>, 72))/binary, 0>>]),
?assertEqual({error, invalid_password_length},
bcrypt:hashpw(binary:copy(<<"A">>, 1025), ?PHP_SALT)),
lists:foreach(fun(Salt) ->
?assertEqual({error, invalid_salt}, bcrypt:hashpw(<<"test">>, Salt))
end, [<<"$2y$04$">>, <<"$2y$03$......................">>,
<<"$2y$32$......................">>,
<<"$2y$4x$......................">>,
<<"$2y$04$!!!!!!!!!!!!!!!!!!!!!!">>]).

length_boundaries() ->
%% $2b$ consumes the first 72 bytes, without an 8-bit length wrap.
Password = <<"A", (binary:copy(<<"B">>, 1023))/binary>>,
Expand Down
Loading