Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this query safe from sql injection?

The script is in PHP and as DB I use MySQL. Here is the script itself.

$unsafe_variable = $_GET["user-input"];
$sql=sprintf("INSERT INTO table (column) VALUES('%s')",$unsafe_variable);
mysql_query($sql);

Some people say that if user assigns ;DROP TABLE blah; string to the variable $unsafe_variable it deletes the table.

But I tried this example,

http://localhost/test.php?user-input=DROP%20TABLE%20my_table 

But it didn't delete the table but instead inserted a new row (;DROP TABLE blah;) in the table.

Could anybody explain me how it is possible to attack this script with sql injections?

like image 535
Bakhtiyor Avatar asked Jun 14 '10 19:06

Bakhtiyor


People also ask

Is SQL safe from SQL injection?

While SQL Injection can affect any data-driven application that uses a SQL database, it is most often used to attack web sites. SQL Injection is a code injection technique that hackers can use to insert malicious SQL statements into input fields for execution by the underlying SQL database.

Can SQL injections be detected?

SQL Injection has become a common issue with database-driven web sites. The flaw is easily detected, and easily exploited, and as such, any site or software package with even a minimal user base is likely to be subject to an attempted attack of this kind.

Is SQL injection a risk?

The impact SQL injection can have on a business is far-reaching. A successful attack may result in the unauthorized viewing of user lists, the deletion of entire tables and, in certain cases, the attacker gaining administrative rights to a database, all of which are highly detrimental to a business.

Is JPA query safe from SQL injection?

This is a common misconception. JPA and other ORMs relieves us from creating hand-coded SQL statements, but they won't prevent us from writing vulnerable code.


2 Answers

That particular injection wouldn't work since PHP's mysql_query function only allows one query per call. However, the following may work if column has a primary or unique key:

$unsafe_variable = "admin') ON DUPLICATE KEY UPDATE password=MD5(CONCAT('knownsalt', 'newpassword'))#";

Better to use the long-winded mysql_real_escape_string function:

$sql=sprintf("INSERT INTO table (column) VALUES(%s)",
             mysql_real_escape_string($unsafe_variable));
mysql_query($sql);
like image 176
Richard Simões Avatar answered Sep 30 '22 12:09

Richard Simões


mysql_query() doesn't allow the execution of multiple queries in one function. So you can't INSERT and then DROP the table. But you shouldn't rely on this as 'security'. Use parametrized queries instead. Check out PHP's PDO library.

However, they could change just about anything else, like possibly SELECTing a password field from another table as a subquery to place into that table so they can view the hash.

like image 32
Lotus Notes Avatar answered Sep 30 '22 12:09

Lotus Notes