Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Injection Protection - Cast from string to int

We all know that parameterized SQL is the way to go when dealing with user input and dynamic SQL, but is casting from string to int (or double, or long, or whatever) as effective if the input you are seeking is numeric?

I guess what I am asking is if this technique alone is infallible in regards to SQL injection?

like image 558
personaelit Avatar asked Sep 08 '09 14:09

personaelit


People also ask

Can SQL cast string to int?

CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER. TO_DATE converts a formatted date string to a date integer.

How do you escape a string to prevent SQL injection?

PHP provides mysql_real_escape_string() to escape special characters in a string before sending a query to MySQL. This function was adopted by many to escape single quotes in strings and by the same occasion prevent SQL injection attacks.

What protection could be used to prevent an SQL injection attack?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.


2 Answers

I'm no expert, but I'm reasonably sure that this would be safe.

But why take the chance? Use parameterised SQL and you don't ever need to worry about it.

Besides, parameterising your SQL has other advantages, not just injection-protection.

like image 153
LukeH Avatar answered Dec 16 '22 18:12

LukeH


If the string was a valid number before you casted it to integer yes it is safe. But you must make sure that it is a valid integer before casting it to int.

I don't know what server side language you are using but in PHP you can use is_numeric() function. For instance:

$strYouExpectToBeInt = $_POST['id'];
try {
    if (false === is_numeric($strYouExpectToBeInt)) {
        throw new Exception('id is not a numeric string or a number');
    }
    $strYouExpectToBeInt = (int)$strYouExpectToBeInt;
    if (false === is_int($strYouExpectToBeInt)) {
        throw new Exception('id is not a valid integer');
    }

    // everything is ok, you can use $strYouExpectToBeInt
    // in SQL query now

} catch  (Exception $e) {
    echo $e->getMessage();
}
like image 32
Richard Knop Avatar answered Dec 16 '22 18:12

Richard Knop