-2

Without any protection, I have the line:

$check = mysql_query("SELECT * FROM school_users WHERE username = '".$_POST['username']."'")or die(mysql_error());

In my php. How would I inject this code? I've tried many other things, but nothing seems to work on injection. does mysql_query have an automatic catch for this?

user1973551
  • 29
  • 1
  • 8
  • 5
    What input are you testing with? – j08691 Feb 09 '13 at 22:03
  • 1
    If you happen to have `magic_quotes` on, it might accidentally protect you from it. You shouldn't have them on anyways. – Waleed Khan Feb 09 '13 at 22:03
  • You would put some SQL code in the username field that you are getting with `$_POST`. See [here](http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php). – Piccolo Feb 09 '13 at 22:04
  • You shouldn't be trying to do this. You also [**should not be using ext/mysql**](http://bit.ly/phpmsql). Use MySQLi/PDO instead. – Amelia Feb 09 '13 at 22:06
  • 1
    @Hiroto He's wondering *how it could be exploited*, not how to secure it. It's important knowledge. – Waleed Khan Feb 09 '13 at 22:07
  • Thank you @WaleedKhan. I find that learning every which way I can be exploited is VERY important. Helps me to make all my code secure. – user1973551 Feb 09 '13 at 22:10
  • @user1973551 but manual escaping and preventing is not needed if you use the `Prepare` API method in an SQL engine. Never escape manually, and use something that isnt about to be removed from PHP. – Amelia Feb 09 '13 at 22:11

2 Answers2

2

Check in your php.ini option magic_quotes_gpc, you should set it to 0 to easily inject SQL. Then you can try to inject your code, you can use some REST plugin in your browser to achieve that. As value for username in the body use e.g. this:

username: "' OR 1=1; --"

That will generate query like this:

SELECT * FROM school_users WHERE username = '' OR 1=1; --

Which will always be true and will return all rows from school_users table.

Peter Krejci
  • 3,182
  • 6
  • 31
  • 49
2

See SQL Injection Attacks by Example. It's not PHP-specific, but provides and explains examples of various common attacks ..

"SQL Injection" is subset of the an unverified/unsanitized user input vulnerability ("buffer overflows" are a different subset), and the idea is to convince the application to run SQL code that was not intended. If the application is creating SQL strings naively on the fly and then running them, it's straightforward to create some real surprises.

While, as others have pointed out, environmental factors such as "magic quotes" can play a factor, the only reliable way to mitigate SQL injection is to use proven coding practices. Refer to How can I prevent SQL injection in PHP? for approaches that mitigate such attacks.

Community
  • 1
  • 1