Skip to content

BigInteger PHP engine: don't return the divisor as the common residue - #2165

Closed
dngr2 wants to merge 3 commits into
phpseclib:masterfrom
dngr2:fix/php-engine-negative-exact-division
Closed

dngr2 wants to merge 3 commits into
phpseclib:masterfrom
dngr2:fix/php-engine-negative-exact-division

Conversation

@dngr2

@dngr2 dngr2 commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Two fixes to the PHP BigInteger engine, one commit each.

I judged neither of these to be a vulnerability, so they are here rather than at the Tidelift contact: both are wrong-result/notice bugs in a public math API, neither is reachable with attacker-controlled input in the protocol code as far as I can see, and the engines used in almost every production install (GMP, BCMath) are unaffected by the first and not affected at all by the second. Happy to move the discussion if you read it differently.

1. divide() hands back the divisor as the common residue

BigInteger::setEngine('PHP64');
[$q, $r] = (new BigInteger('-256'))->divide(new BigInteger('256'));
// $q = -1, $r = 256      expected 0

The docblock defines the second element as the common residue — the first positive modulo — so it is only a negative remainder that has the divisor added. When the division is exact the remainder is already 0, and adding the divisor returns the modulus itself, which is never a valid residue.

GMP and BCMath return 0, so the same call gives a different answer depending on which extension happens to be installed, and the PHP engines are the fallback when neither is.

Both branches of divideHelper() are affected:

  • the single-digit divisor path, $r = $y->value[0] - $r
  • the long-division path, if ($x_sign) { $y->rshift($shift); $x = $y->subtract($x); }

The equal-magnitude case returns early with a zero remainder, which is probably why exact division has looked correct. testDivide() covers exact division only with a positive dividend, so it passes either way.

I checked a cross-engine sweep of 1278 operations over add, subtract, multiply and divide: 32 results differed between BCMath and the two PHP engines before this change and none after, and BCMath matched the documented rule in all 32.

This applies to 3.0 as well. Both code paths are identical there (PHP.php lines 536-538 and 670-674 on the 3.0 branch); I have only prepared the master patch, so say the word if you would like the backport.

2. toString() raises "Undefined array key 0"

(string) $mod->value[0] ?? ''

The cast binds tighter than ??, so this is ((string) $mod->value[0]) ?? '': the array access is evaluated first, and a cast cannot produce null, so the coalesce is unreachable. Every intermediate modulus of 0 therefore raises a warning. 3.0 has this as isset($mod->value[0]) ? $mod->value[0] : '' and does not warn, so it looks like it came in with the ?? modernisation.

The returned string is correct either way. It matters because an error handler that promotes warnings — Symfony, Laravel, PHPUnit in strict mode — turns a plain string cast into a thrown ErrorException:

BigInteger::setEngine('PHP32');
(string) new BigInteger('10000000');   // ErrorException: Undefined array key 0

Reproduces on PHP32 for values divisible by 10^7 and on PHP64 for 10^13.

Tests

The new case lives in the shared TestCase, so every engine is held to it. Reverting either divideHelper() branch fails it for PHP32 and PHP64 and leaves BCMath passing, which is the intended asymmetry — BCMath was never wrong here.

BCMathTest, BCMath64Test, PHP64Test and PHP32Test are green at 48 tests / 117 assertions.

One thing I could not check: the GMP engine. The static PHP builds available to me abort with SIGILL inside libgmp on this machine, so GMP's behaviour here is inferred from BCMath agreeing with the documented rule rather than measured. Worth a second pair of eyes on GMPTest before merging.

dngr2 added 3 commits August 16, 2026 19:36
The cast binds tighter than ??, so

    (string) $mod->value[0] ?? ''

is ((string) $mod->value[0]) ?? '' -- the array access happens first, and the
cast can never produce null, so the coalesce is unreachable. Every intermediate
modulus of 0 therefore raises "Undefined array key 0".

3.0 has this as isset($mod->value[0]) ? $mod->value[0] : '' and does not warn.

The returned string is right either way, but under an error handler that
promotes warnings -- Symfony, Laravel, PHPUnit in strict mode -- casting such a
BigInteger to string throws ErrorException instead:

    BigInteger::setEngine('PHP32');
    (string) new BigInteger('10000000');   // ErrorException: Undefined array key 0
divide() returns the "common residue" -- the first positive modulo -- so only a
negative remainder has the divisor added to it. When the division is exact the
remainder is already 0, but the PHP engines added the divisor anyway and handed
back the modulus itself:

    BigInteger::setEngine('PHP64');
    [$q, $r] = (new BigInteger('-256'))->divide(new BigInteger('256'));
    // $q = -1, $r = 256   -- expected 0

A residue is never equal to its modulus. GMP and BCMath return 0 here, so the
answer depends on which extension happens to be installed; the PHP engines are
the fallback when neither is.

Both branches of divideHelper() were affected: the single-digit divisor path
(`$r = $y->value[0] - $r`) and the long-division path at the end. The
equal-magnitude case returns early with a zero remainder, which is why exact
division looked correct.

Covered in the shared TestCase, so every engine is held to it. Reverting either
branch fails the new test for PHP32/PHP64 and leaves BCMath passing.
Psalm flagged $q as an unused variable; the loop only asserts on the
remainder, so skip the quotient with [, $r].
@terrafrost

Copy link
Copy Markdown
Member

Nice finds!

Interestingly, these issues do not appear to impact 1.0 / 2.0:

define('MATH_BIGINTEGER_MODE', 1); // MATH_BIGINTEGER_MODE_INTERNAL
[$q, $r] = (new Math_BigInteger('-256'))->divide(new Math_BigInteger('256'));
// $q = -1, $r = 256      expected 0
define('MATH_BIGINTEGER_MODE', 1); // MATH_BIGINTEGER_MODE_INTERNAL
(string) new Math_BigInteger('10000000');

(I guess the latter isn't all that surprising, tho, since, as you noted, the underlying issue was introduced with the ?? modernization)

This applies to 3.0 as well. Both code paths are identical there (PHP.php lines 536-538 and 670-674 on the 3.0 branch); I have only prepared the master patch, so say the word if you would like the backport.

Yah - that'd be great - thanks! I'll hold off on merging, for now, until you do that. Then if you could merge that into the 4.0 branch (this PR currently targets the master branch) that contains the secondary fix as well that'd be great. Like I expect the 3.0 changes could very well have some small merge conflicts with the 4.0 changes and if you do the merge then you can resolve them and that's less work for me!

Thanks!

@dngr2

dngr2 commented Aug 18, 2026

Copy link
Copy Markdown
Contributor Author

Done:

Both check against the GMP engine with no disagreements. Whatever's easiest for you on merge order.

terrafrost referenced this pull request Aug 18, 2026
An exact negative division left the remainder at 0, but divideHelper still added
the divisor to it -- returning the modulus itself, which is never a valid common
residue. Both the single-digit and long-division branches did this. Guard on a
non-zero remainder, matching the GMP and BCMath engines. (toString's separate
?? fix from master does not apply here; 3.0 predates that modernization.)
@terrafrost

Copy link
Copy Markdown
Member

Closing as the other PRs have been merged.

Thanks!

@terrafrost terrafrost closed this Aug 18, 2026
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