Page 184 - SQL
P. 184
cmd.CommandText = "SELECT * FROM Users WHERE username = @username AND password = @password";
cmd.Parameters.Add("@username", strUserName);
cmd.Parameters.Add("@password", strPassword);
If you do not use parameters, and forget to replace quote in even one of the values, then a
malicious user (aka hacker) can use this to execute SQL commands on your database.
For example, if an attacker is evil, he/she will set the password to
lol'; DROP DATABASE master; --
and then the SQL will look like this:
"SELECT * FROM Users WHERE username = 'somebody' AND password = 'lol'; DROP DATABASE master; -
-'";
Unfortunately for you, this is valid SQL, and the DB will execute this!
This type of exploit is called an SQL injection.
There are many other things a malicious user could do, such as stealing every user's email
address, steal everyone's password, steal credit card numbers, steal any amount of data in your
database, etc.
This is why you always need to escape your strings.
And the fact that you'll invariably forget to do so sooner or later is exactly why you should use
parameters. Because if you use parameters, then your programming language framework will do
any necessary escaping for you.
simple injection sample
If the SQL statement is constructed like this:
SQL = "SELECT * FROM Users WHERE username = '" + user + "' AND password ='" + pw + "'";
db.execute(SQL);
Then a hacker could retrieve your data by giving a password like pw' or '1'='1; the resulting SQL
statement will be:
SELECT * FROM Users WHERE username = 'somebody' AND password ='pw' or '1'='1'
This one will pass the password check for all rows in the Users table because '1'='1' is always
true.
To prevent this, use SQL parameters:
SQL = "SELECT * FROM Users WHERE username = ? AND password = ?";
db.execute(SQL, [user, pw]);
https://riptutorial.com/ 166

