Skip to content

fix: Catch ValueError from hex2bin() in Security::derandomize() on PHP 8#10320

Open
gr8man wants to merge 2 commits into
codeigniter4:developfrom
gr8man:fix-security-hex2bin-valueerror
Open

fix: Catch ValueError from hex2bin() in Security::derandomize() on PHP 8#10320
gr8man wants to merge 2 commits into
codeigniter4:developfrom
gr8man:fix-security-hex2bin-valueerror

Conversation

@gr8man

@gr8man gr8man commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Description
This PR fixes an issue where providing a malformed CSRF token crashes the application on newer PHP versions (particularly PHP 8.4+) instead of gracefully rejecting it.

Inside Security::derandomize(), the hex2bin() function is used to decode the randomized token. If the provided hex string is invalid (e.g., contains non-hexadecimal characters or has an odd length), older PHP versions emitted an E_WARNING which the framework's error handler converted to an ErrorException.

However, in newer PHP 8 releases, hex2bin() natively throws a ValueError for invalid input strings. Because the try/catch block was only capturing ErrorException, the ValueError escaped unhandled, resulting in a fatal crash.

Changes:

  • Updated the try/catch block in Security::derandomize() to catch ValueError alongside ErrorException.
  • Added testDerandomizeThrowsInvalidArgumentExceptionOnInvalidHex() to the test suite, which intentionally passes a strictly invalid hexadecimal string to verify that the InvalidArgumentException is correctly re-thrown without a fatal error.

Checklist:

  • Securely signed commits
  • Component(s) with PHPdoc fully completed
  • Unit testing, with >80% coverage
  • User guide updated (if applicable)

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.

1 participant