1.2.578. Insecure Integer Validation

Comparing incoming variables to integer may lead to injection.

When comparing a variable to an integer, PHP applies type juggling, and transform the variable in an integer too. When the value converts smoothly to an integer, this means the validation may pass and yet, the value may carry an injection. This analysis spots situations where an incoming value is compared to an integer. The usage of the validated value is not analyzed further.

<?php

// This is safe :
if ($_GET['x'] === "2") {
    echo $_GET['x'];
}

// Using (int) for validation and for display
if ((int) $_GET['x'] === 2) {
    echo (int) $_GET['x'];
}

// This is an injection
// '2 <script>' == 2, then echo will make the injection
if ($_GET['x'] == 2) {
    echo $_GET['x'];
}

// This is unsafe, as $_GET['x']  is tested as an integer, but echo'ed raw
if ((int) $_GET['x'] === 2) {
    echo $_GET['x'];
}

?>

See also Type Juggling Authentication Bypass Vulnerability in CMS Made Simple, PHP STRING COMPARISON VULNERABILITIES and PHP Magic Tricks: Type Juggling.

1.2.578.1. Suggestions

  • Add the typecasting to all read access to the incoming variable

  • Add the typecasting when writing the incoming value to a local variable

1.2.578.2. Specs

Short name

Security/IntegerConversion

Rulesets

All, Changed Behavior, Security

Exakat since

1.7.7

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

High

Features

validation

Available in

Entreprise Edition, Exakat Cloud