Skip to content

fix: harden verifyCode with strict length and digit validation - #13

Merged
francislavoie merged 2 commits into
Vectorface:masterfrom
Rodots:fix/code-length-verify
Aug 5, 2026
Merged

fix: harden verifyCode with strict length and digit validation#13
francislavoie merged 2 commits into
Vectorface:masterfrom
Rodots:fix/code-length-verify

Conversation

@Rodots

@Rodots Rodots commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

📋 Summary

This PR hardens GoogleAuthenticator::verifyCode() by adding strict length checking and digit-only validation. Invalid inputs are now rejected before entering the time-window comparison loop, eliminating potential timing attack surfaces and preventing malformed codes from reaching hash_equals.


🔧 Key Changes

1. src/GoogleAuthenticator.php — Input Validation Guard

Added a pre-check at the beginning of verifyCode() (lines 147–149):

if (strlen($code) !== $this->_codeLength || !ctype_digit($code)) {
    return false;
}
  • Length check: Ensures the code length exactly matches the configured _codeLength (default 6, configurable 6–8).
  • Digit whitelist: Rejects any non-numeric characters (letters, special chars, control characters like \n).
  • Early return: Invalid inputs bypass the time-window loop and hash_equals entirely.

Security Benefits:

  • Prevents variable-length strings from entering hash_equals, mitigating timing side-channel risks.
  • Blocks non-numeric payloads (e.g., abcdef, 12345\n, zero-padded 7-digit strings).
  • Minor performance improvement by skipping unnecessary iterations.

2. tests/GoogleAuthenticatorTest.php — 3 New Security Test Cases

Test Method Scenario Covered
testVerifyCodeWithLeadingZero() 7-digit string (0 + valid 6-digit code) is rejected
testVerifyCodeWithEightDigits() 6-digit code is rejected when 8-digit length is configured
testVerifyCodeRejectsNonNumericCode() Non-numeric inputs (alpha, mixed, control chars) are all rejected

All existing tests continue to pass with no regressions.


📁 Scope of Impact

File Change Type Notes
src/GoogleAuthenticator.php Modified Added input validation guard in verifyCode()
tests/GoogleAuthenticatorTest.php Tests Added 3 new security-focused test cases
  • Breaking Changes: None. Only previously invalid/malformed inputs that may have passed are now explicitly rejected.
  • Backward Compatibility: Fully compatible. All legitimate numeric TOTP codes continue to work as expected.

@francislavoie
francislavoie merged commit 5c072cd into Vectorface:master Aug 5, 2026
3 checks passed
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.

2 participants