MySQL Injection
You have probably heard of it. MySQL injection, but what is it?
Full explanation after the jump
It's (basically) breaking out of the formed query and making the website query your request instead. Imagine a code like the following for reading single posts.
SELECT title,message,DATE FROM news WHERE id='<strong>input</strong>';
Yeah? It works all fine and dandy when the user follows valid links generated by your site when the input is an integer. But what if someone tried to input
' OR ''='
Making the code:
SELECT title,message,DATE FROM news WHERE id='' OR ''=''
Which basically says: Get only the rows where the id equals '' (nothing) OR when '' (nothing) equals '' (nothing). Therefore returning ALL rows.
What is worse is when you have a user table hooked up to it on the same database. If the hacker would try the following input:
' UNION SELECT username,password,1 FROM members--
Making the query:
SELECT title,message,DATE FROM news WHERE id='' UNION SELECT username,password,1 FROM members--
You get one guess as to what it would return...
First I'll explain the UNION statement. UNION "merges" two queries together and returns both results. The amount of columns taken from the first query and the second query should always be exactly the same or you will get a MySQL error.
The code I showed would return the news posts and all the username/password combinations.
How would we prevent this?
First of all, we could just use the intval() function in PHP to convert the input string to an integer (anything else than an integer will return 0).
Second of all, you should use mysql_real_escape_string() which will change the quotes to backslash-quote so MySQL will take the quote as part of the id that's needed.
And something I like to add as a small security measure, which I personally use a lot:
Any time you store passwords in a database, apart from just encrypting it with md5() I like to add a string at the end of the password before encrypting it, or encrypting it with md5() twice, both methods make the password (if the hacker can get it) quite impossible to crack.
This, however is security through obscurity, and should never be used.
Thanks for reading
