Does user input enter an integer sufficient to sanitize it?

Quote from this SO answer :

All sent messages are initially processed as a string, so forcing known numeric data as an integer or float makes sanitation quick and painless.

It was a sanitation method that I myself came up with for a quick and dirty query (finding a name in a table from a numerical identifier); the only variable that connects to the request is the identifier, and I know that the identifier must be greater than zero and less than 255, so my disinfection looks like this (with a small number of validations):

$id = (int)$_REQUEST['id'];
if ($id < 1 || $id > 255) errmsg("Invalid ID specified!");
$name = $DB->query("SELECT name FROM items WHERE id=${id}")->fetch_all()[0][0];

Is this enough to prevent SQL injection attacks or any other malicious attacks based on a user-specified value, $idor can it be used?

NOTE. The identifier / name is not "sensitive", so if any input inadvertently leads to "1" or another valid identifier value, I don't care. I just want to avoid the tricks in the rows of Small Bobby Tables .

+4
source share
8 answers

The answer is TL, DR - yes. By clicking on (int)you can’t get anything but an integer.

The trick can take place where it can lead to unwanted behavior. Take your code

$id = (int)$_REQUEST['id'];

Now if we call it

page.php?id=lolsqlinjection

$id 0 ( 0). . , 0 - . , , , ( MySQLi, PDO)

$prep = $DB->prepare("SELECT name FROM items WHERE id=?");
$prep->bind_param('i', $_REQUEST['id']);
$prep->execute();

, , , . , SQL- MySQL "lolsqlinjection". . , , 0 .

+5

, int, , somephrase , int 0, .

( - ), , , , , , . , int .

, :

<?php


$id = (int) $_GET['id'];

if($id === 0 || !in_array($id,range(1,255)) 
{
   if($id === 0 && (string) $_GET['id'] !== '0') {
      // sql injection attempt ! ( or not ? )
   } else {
      // maybe an error  
   }
} else {
  $result = $DB->query(...);
  echo $result;
}
+1

, , : ", " . PHP , filter_input():

filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, [ 
     "options" => [
        "min_range" => 1,
        "max_range" => 255
    ]    
]);

if ( isset), , , , ​​ .

SQL-, .

+1

, , SQL-.

, .

+1

, , , , .

PDO:

$stmt = $DB->prepare("SELECT name FROM items WHERE id=?");
$stmt->execute([$_REQUEST['id']);
$name = $stmt->fetchColumn();

, ? . .

, int SQL. , . , , , . , (int) SQL.

.

.

.

.

+1

, PHP . http://php.net/manual/en/filter.filters.php.

:

$options = [
    'options' => [
        'default'   => null,
        'min_range' => 1,
        'max_range' => 255,
    ]
];

if (isset($_REQUEST['id'])) {
    $id = filter_var($_REQUEST['id'], FILTER_VALIDATE_INT, $options);
    if ($id) {
        // TODO:
    }
}

SQL , .

0

- .

, .

, , . ,

$name = $DB->run("SELECT name FROM items WHERE id=?", [$_REQUEST['id']])->fetchColumn();

, , , , .

0

Source: https://habr.com/ru/post/1694009/


All Articles