Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signs that a SQL statement is dangerous

I want to develop a function in PHP that checks how dangerous a SQL statement is. When i say dangerous i mean, certain symbols, characters or strings that are used to get data from a database that the user shouldnt see.

For example:

SELECT * FROM users WHERE userId = '1'

can be injected in several ways. Although i clean the params, i also want to monitor how safe the query is to run.

Thanks in advance

like image 448
phpNutt Avatar asked May 07 '10 22:05

phpNutt


2 Answers

You're trying to find a fix for a problem that shouldn't exist. You should use prepared (precompiled) queries, then you don't ever have to worry about SQL injection and escaping as the query itself is fixed and only the arguments are variable.

See here for an example on using them in PHP: http://mattbango.com/notebook/web-development/prepared-statements-in-php-and-mysqli/

Another advantage is that it's faster too, at least for MySQL, as the server doesn't have to parse the query every time.

like image 94
wump Avatar answered Sep 22 '22 12:09

wump


I agree that Parametrized Queries is the best way to go. However most php/mysql applications use mysql_query(), and most web applications also vulnerable to some form of sql injection.

Suhosin Hardened PHP is installed by default on many LAMP systems and it has a feature called "experimental SQL injection heuristics", but it doesn't break any exploits that I know of. A better solutions is a Web Application Firewalls(WAF) which is looking for attacks like sql injection in the raw HTTP query. WAFs are required by the PCI-DSS are a commonly used on the internet today because they work.

There is an application called GreenSQL which is betting on the fact that injected queries look different. For the most part this is a safe bet, but an SQL is a free formed Declarative language and there are many ways that an attacker can rewrite a query to perform the same attack. In short this type of secuirty will stop some attacks, but it is flawed when compared to Parametrized Queries. WAF's suffer from the same problem as GreenSQL, its possible to encode or obfuscate an attack such that it slips past the massive library of regular expressions used to detect the attacks. Bobince's answer to this question cracks me up, his point is also true for the exploitation process.

like image 22
rook Avatar answered Sep 22 '22 12:09

rook