I'm remaining vague on purpose, as I do not want to give away info as how to hack user accounts.
These are tips, on how to avoid the kind of attack you mentioned.
It is extremely important that you validate your users input, especially the username and password.
Be sure that usernames do not contain single quote marks ('), the string wildcard char (%) or equal signs (=).
A simple way to test this using PHP:
-
$invalidStrings = array("'", "%", "=");
-
foreach($invalidStrings as $str) {
-
if(strpos($_POST['Username'], $str) or strpos($_POST['Password'], $str)){
-
echo "Invalid character used";
-
exit()
-
}
-
}
-
else {
-
echo "Its all good!";
-
}
-
EDIT: Fixed a couple of errors in the code.
Using hashing algorithms like SHA or MD5 on passwords will in many cases prevent attacks as you mentioned, as the entire string passed from the user will be run through the algorithm and the output will be a string of letters that can't be used to attack your database.
This will also ensure that if by some means a hacker (or anybody) would steal your users information, the passwords will be unusable.
Using hashing algorithms in MySQL is extremely simple. You can simply put your password strings into the sha() function and it will be automaticly converted into a 40 char mess that nobody can read. Then when you want to validate, you simply turn the new string into the same mess and try to match it.
For example:
-
/* This will insert a messed up
-
* 40 char string into the password field
-
*/
-
INSERT INTO user(password)
-
VALUES ( sha('myPassword') );
-
-
/* This will try to match the password
-
* by hashing the input and matching it
-
* with the one already scrambled in the database
-
*/
-
SELECT * FROM user
-
WHERE password = sha('myPassword');
-
This example is obviously flaved as it is missing the username portion, but it explains what I mean.