Skip to content

fix: reject negative salt rounds in hash()#1221

Open
abhu85 wants to merge 1 commit intokelektiv:masterfrom
abhu85:fix-negative-salt-rounds
Open

fix: reject negative salt rounds in hash()#1221
abhu85 wants to merge 1 commit intokelektiv:masterfrom
abhu85:fix-negative-salt-rounds

Conversation

@abhu85
Copy link
Copy Markdown

@abhu85 abhu85 commented Mar 18, 2026

Summary

  • Add validation to reject negative salt rounds with a clear error message
  • Fix error propagation from genSalt to hash() callback
  • Add test coverage for negative rounds across sync, async, and promise APIs

Problem

Passing a negative value for salt rounds (e.g., bcrypt.hash('password', -5, cb)) causes the library to hang indefinitely. This happens because:

  1. Negative values pass JavaScript's type validation
  2. In the native C++ code, the negative value is cast to u_int8_t, causing integer underflow (e.g., -5 becomes 251)
  3. This results in 1 << 251 rounds, an astronomically large iteration count that causes the hang

Solution

Add early validation in the JavaScript layer to reject negative rounds with a clear error message "rounds must be a positive number", matching the existing pattern for type validation.

Also fixes a related issue where genSalt errors were not properly propagated through the hash() callback when salt rounds were invalid.

Test plan

  • Added salt_rounds_is_negative test for sync API
  • Added salt_rounds_is_negative test for async API
  • Added salt_rounds_is_negative test for promise API
  • Added hash_rounds_is_negative test for sync/async/promise APIs
  • All 81 tests pass
  • Verified manually that negative rounds now throw instead of hanging

Fixes #1218

Previously, passing a negative value for salt rounds (e.g., `bcrypt.hash('password', -5, cb)`)
would cause the library to hang indefinitely. This occurred because:

1. Negative values passed JavaScript's validation (checking only for type)
2. In the native C++ code, the negative value was cast to u_int8_t, causing
   integer underflow (e.g., -5 becomes 251)
3. This resulted in `1 << 251` rounds, an astronomically large iteration count

This fix adds early validation in the JavaScript layer to reject negative
rounds with a clear error message "rounds must be a positive number", matching
the existing pattern for type validation.

Also fixes a related issue where genSalt errors were not properly propagated
through the hash() callback when salt rounds were invalid.

Fixes kelektiv#1218
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bcrypt.hash(): negative salt rounds cause indefinite hang

1 participant