so I'm studying up on sql injections and was wondering why in a statement like this:
"select * from table where username='$var1' and password='$var2';
if the user provided
$var2 = blah' or 1=1 --'
as the password, the statement would be
"select * from table where username='blah' and password='blah' or 1==1--'';
what does the '--' do at the end of the statement? why is it needed? I've tied this in the console and that symbol is needed or else I get an error.
It starts a MySQL comment, so anything after that will not be used for the query.
the double dashes represent a comment, and they are used simply so that if there's anything else on that line in the query, it'll get commented out
So in your php or whatever, you check every field for characters such as ; -- and a few others, and if detected just say sorry can't seem to run that query. The typical characters used in such attacks can be seen being used in examples of how such attacks are run. The ' is a tricky one to filter out as it might be part of user mr o'hara's name for example.
The comment in your example wouldn't be needed in that particular case.
But, imagine this one
"select * from table where password='$var2' and username='$var1';
"select * from table where password='blah' or 1==1-- and username='foo';
note- mysql requires a whitespace character after the double dash for it to be considered a comment.
Checking the values for signs of sql injection is definitely not what you want to do. Simply escape the values, or even better, use prepared statements. You still probably want to validate your user input, but do it for other reasons, not for protection against sql injection.
thanks guys that makes a lot of sense. Also, I've read that an attacker could use sql injections to deface a webpage...
how is this possible? I thought sql could on'y be used to alter db's? unless of course the page displays purely db data and it's displaying data that an attacker produced. Is this the only way? Could they get full access to a server through sql injections?