Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

My server gives me a syntax error when I attempt SQL injection


ghost's Avatar
0 0

Hi, I have Apache 2.2.8, PHP 5.2.4, and MySQL 5.0.45. I've been testing various security holes on my server and I have been wanting to take a look at SQL injection. I made a script in PHP that includes this vulnerable code:

$query = "SELECT password FROM moderators WHERE username = '$username2'";
$result = mysql_query($query);
$result = mysql_fetch_array($result);
foreach($result as $printResult)
{
	print $printResult . '<br />';
}

$username2 is a $_GET variable. So I run my script and set user2 accordingly.

http://localhost/scripts/sql.php?user2=';SELECT * FROM moderators--

However, instead of it displaying the contents of my table, I get an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; SELECT * FROM moderators--'' at line 1
Your Query: SELECT password FROM moderators WHERE username = ''; SELECT * FROM moderators--'

It seems that whenever I put a ' in the query, it gives me a syntax error?


ghost's Avatar
0 0

In the latest PHP, SQL injection has been made impossible. When you put ' into your url, it gets escaped into \'. So your SQL query looks like this:

SELECT password FROM moderators WHERE username = '\';SELECT * FROM moderators–

Which is syntactically wrong. You need to change server options in php.ini. Look for magic_quotes_gpc and set it to Off and it should works.

– Henux


ghost's Avatar
0 0

Disabling magic quotes was the first thing I did when I installed PHP.

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

When I enable magic quotes and run my script, I an "Invalid Argument supplied for foreach()" error message, rather than the "You have an error in your SQL syntax" error. So I'm not sure that magic quotes has anything to do with it…


ghost's Avatar
0 0

Ok. This is the problem.

This works:

mysql_query("SELECT * FROM moderators;"****);

But this doesn't:

mysql_query("SELECT * FROM moderators; SELECT username FROM moderators;"****);

Apparently mysql_connect() has to be called with special flags, or else mysql_query() cannot do multiple queries at once. I did not know this as I am used to using MDB2 for my PHP and SQL needs. Got it figured out;)