SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. It generally allows an attacker to view data that they are not normally able to retrieve.
SQL Injections can be used find the credentials of other users in the database OR to add, modify, and delete records in the database.
Example of SQL injection
It is a simple example of authenticating with a username and a password.
SELECT * FROM Users WHERE User=' + txtUserName.Text + ' AND Pass=' + txtPassword.Text
so a simple sql injection would be just to put the Username in as ‘ OR 1=1–. This would effectively make the sql query:
SELECT * FROM Users WHERE User='' OR 1=1-- ' AND PASS=' + password
This says select all customers where they’re username is blank (”) or 1=1, which is a boolean, equating to true. Then it uses — to comment out the rest of the query. This will return all the Users!
Preventing SQL injection
Most instances of SQL injection can be prevented by using parameterized queries (also known as prepared statements) instead of string concatenation within the query.
string sql = "SELECT * FROM Users WHERE User=@UserName AND PASS= @Password";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
var userName = new SqlParameter("@UserName", SqlDbType.Text);
userName.Value = txtUserName.Text;
var password = new SqlParameter("@Password", SqlDbType.Text);
password.Value = txtPassword.Text;
command.Parameters.Add(userName);
command.Parameters.Add(password);
var results = command.ExecuteReader();
}
The way parameterized queries work, is that the SQL Query is sent as a query, and the database knows exactly what this query will do, and only then will it insert the username and passwords merely as values. This means they cannot effect the query, because the database already knows what the query will do. So in this case it would look for a username ( ‘ OR 1=1–)