Back to the page [you came from]
 
How to fool SQL servers accessing
(When a password is asked and you do not happen to know it... :-)


The following snippet is worth reading especially for those among my visitors that still fail to grasp WHY it is very important, for searchers, to have at least some rudiments of programming (and/or software reversing) knowledge.

Dear fravia+,

Most of what I do is write perl cgi front ends to sql databases.
Lots of sites that require registration (either paid, or just contact details) use a database for authentication rather than the htaccess method you talked about. Typically this is done with a POST method form as follows:

Username :
Password:


Which in html code looks like this:

<FORM METHOD=POST>
Username :<INPUT TYPE=TEXT NAME=username>
Password: <INPUT TYPE=PASSWORD NAME=password>
</FORM>

now the perl script will have some code like this:

my $username=$req?>param("username");	
                #$req is a handle to CGI data
my $password=$req?>param("password");
my $sql="
	SELECT username
	FROM users
	WHERE username='$username'
	AND password='$password'
	";
my $result=$dbh?>query($sql);	
               #$dbh is a handle to a db
	       #connection
	
if ($result?>numrows==O)	{	
               #did nothing match our select?
	&bugger_off_evil_hacker_dude;
} else	(
	&come_on_down_paying_customer;
)
This is a fairly simple example, but you can see how the form variables are translated into an SQL statement. Now, there is a big whole in this code, in that, since I am such a lazy programmer, I have not checked the forms input for bad characters.

The bad character that might cause problems here is a ' character, which is being used in the SQL statement to delimit strings. Say I put in a username of blah' then the sql statement would have WHERE username='blah '' in it, and the SQL parser would treat the two '' as being a single inside the string, and choke with a syntax error.
In this case, the cgi script would return either a generic error message, spit out the full sql error message or just give a web server error.

If I was messing around with such a site and I got an error when I put a ' in my username, i'd know what was going on and the next thing I would try as a username is the following:

blah' OR ' '<>

and in the password:

'blah

this makes the full SQL statement above look something like this:
SELECT username
FROM users
WHERE username='blah' OR ' '<>'
AND password= " blah'
which is a valid sql statement, which the SQL server parses like this:

(username='blah)' OR (is the string " " not equal to the string
"AND password='blah")

clearly the two strings in the second comparision are different, so the select statement will infact return every single username, so the number of rows will not be zero, so the code above will let us in.

Of course you cant actually know what the SQL statement is, although you can make educated guesses.

Jonathan































red 11 November 2001