diff --git a/ext/mri/bcrypt_pbkdf_ext.c b/ext/mri/bcrypt_pbkdf_ext.c index 3aa628d..75c11a9 100644 --- a/ext/mri/bcrypt_pbkdf_ext.c +++ b/ext/mri/bcrypt_pbkdf_ext.c @@ -11,7 +11,10 @@ static VALUE bc_crypt_pbkdf(VALUE self, VALUE pass, VALUE salt, VALUE keylen, VA StringValue(salt); size_t okeylen = NUM2ULONG(keylen); - if (okeylen == 0 || okeylen > 1024) + LONG_LONG rounds_value = NUM2LL(rounds); + if (rounds_value > UINT_MAX) + rb_raise(rb_eRangeError, "rounds %lld too big to convert to 'unsigned int'", rounds_value); + if (rounds_value < 1 || okeylen == 0 || okeylen > 1024) return Qnil; u_int8_t* okey = xmalloc(okeylen); VALUE out; @@ -20,7 +23,7 @@ static VALUE bc_crypt_pbkdf(VALUE self, VALUE pass, VALUE salt, VALUE keylen, VA RSTRING_PTR(pass), RSTRING_LEN(pass), (const u_int8_t*)RSTRING_PTR(salt), RSTRING_LEN(salt), okey, okeylen, - NUM2ULONG(rounds)); + (unsigned int)rounds_value); if (ret < 0) { xfree(okey); return Qnil; diff --git a/test/bcrypt_pnkdf/engine_test.rb b/test/bcrypt_pnkdf/engine_test.rb index b78c8a9..32d171f 100644 --- a/test/bcrypt_pnkdf/engine_test.rb +++ b/test/bcrypt_pnkdf/engine_test.rb @@ -74,6 +74,20 @@ def test_invalid_pbkdf_arguments_return_nil assert_nil BCryptPbkdf::Engine.__bc_crypt_pbkdf('pass', 'salt', 1025, 1) end + def test_negative_rounds_return_nil + assert_nil BCryptPbkdf::Engine.__bc_crypt_pbkdf('pass', 'salt', 32, -1) + assert_nil BCryptPbkdf::Engine.__bc_crypt_pbkdf('pass', 'salt', 32, -(1 << 31)) + end + + def test_rounds_must_fit_the_native_range + assert_raises(RangeError) do + BCryptPbkdf::Engine.__bc_crypt_pbkdf('pass', 'salt', 32, (1 << 32) + 1) + end + assert_raises(TypeError) do + BCryptPbkdf::Engine.__bc_crypt_pbkdf('pass', 'salt', 32, Object.new) + end + end + def test_hash_argument_lengths sha2pass = OpenSSL::Digest.digest('SHA512', 'pass') sha2salt = OpenSSL::Digest.digest('SHA512', 'salt')