Saturday, August 6, 2011

PHP Security: Automatic Integer Conversion

Hello All


This time I would like to cover security bug that I have seen today while doing some tests with our security scanner. We have added special signatures to our ZeroDayScan web security scanner to check for such bugs. In brief PHP has another method that can be used to perform SQL injections. This is not widely known bug for PHP community.

PHP is very popular language used in a lot of websites. PHP uses variables that can store numbers and integers at once.

If you compare PHP variable with a constant number, PHP will automatically performs conversion of that variable to an integer.

So when the following code is executed:

$my_var = $_GET['my_var'];
if ($my_var == 1)
{
}

$my_var variable is automatically converted to an integer. This is indeed very useful. It is probably because in the background PHP uses atoi() C library function. This atoi() function has very interesting feature. If after the number you will have some text like "1abc", this function will return just 1 without generating any error message.

So, in brief, if you compare "1abc" to 1 it will be true and the code will continue to the nested block of code.

So if we will get back to our code

if ("1abc" == 1)
{
// this code will be executed now
}

So, here comes the security issue. In the nested block the $my_var will still has the old value "1abc". As a result it is unsafe to use it for example when executing SQL query because it can contain SQL injection.


$pageid = $_GET['pageid'];
if ($pageid == 1)
{
$result = mysql_query("SELECT title, content from pages where page_id = $pageid");
}

Because $pageid can contain SQL query starting with number 1 it will be glued with a legitimate query.

$pageid can contain the following code: "1 union select user, password from accounts".

As a result the following code will be executed:
$result = mysql_query("SELECT title, content from pages where page_id = 1 union select user, password from accounts");


Countermeasures


1. Scan your code with our security scanner to find such bugs. It is better to scan your code in every step of your coding. Here is a link:
http://www.zerodayscan.com/

2. Instead of $pageid = $_GET['pageid'] use the following code:

$pageid = intval($_GET['pageid']);

3. You can use GreenSQL database firewall to protect your database from not legit queries. You can get GreenSQL Express for free. You can get it from here:
http://portal.greensql.com/products/buy-now


Best regards,
Yuli Stremovsky

No comments:

Post a Comment