Skip to content

fix: validate salt rounds to prevent hang on negative values#1222

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

fix: validate salt rounds to prevent hang on negative values#1222
abhu85 wants to merge 1 commit intokelektiv:masterfrom
abhu85:fix/negative-salt-rounds-validation

Conversation

@abhu85
Copy link

@abhu85 abhu85 commented Mar 20, 2026

Summary

  • Add input validation to reject negative salt rounds with clear error message
  • Fix error propagation bug where genSalt errors in hash() were silently ignored
  • Add tests for negative rounds validation (sync, async, and promise APIs)

Problem

Calling bcrypt.hash('password', -1, callback) caused the process to hang indefinitely (issue #1218).

Root cause: Negative rounds values were passed to the C++ layer, which clamped them to 31 (the maximum valid value). This resulted in 2^31 = 2,147,483,648 iterations - effectively infinite computation time.

Solution

Validate that rounds must be non-negative in both genSalt() and genSaltSync(). The error is thrown/returned consistently across all APIs:

  • Sync: throws Error('rounds must be a positive integer')
  • Async callback: passes error to callback
  • Promise: rejects with the error

Also fixed a pre-existing bug where errors from genSalt() inside hash() were not propagated to the callback - the callback was called with undefined salt, causing a TypeError.

Test Plan

  • Added salt_rounds_is_negative test in sync.test.js
  • Added hash_rounds_is_negative test in sync.test.js
  • Added salt_rounds_is_negative test in async.test.js
  • Added hash_rounds_is_negative test in async.test.js
  • Added salt_rounds_is_negative test in promise.test.js
  • Added hash_rounds_is_negative test in promise.test.js
  • All existing tests pass (81 total)

Fixes #1218

Negative salt rounds (e.g., -1) caused bcrypt.hash() to hang indefinitely
because the C++ layer clamped negative values to 31 (the maximum), resulting
in 2^31 iterations that would take hundreds of years to complete.

This commit adds input validation to reject negative rounds early with a
clear error message. Also fixes a pre-existing bug where genSalt errors
in hash() were not properly propagated to the callback.

Fixes kelektiv#1218

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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