Skip to main content

Potential SQL injection with MsSQL Data Provider

Back to rules list


The dynamic value passed in the SQL query should be validated. Bind variables in prepared statements can be used to easily mitigate the risk of SQL injection.

Risk

If the user input is not properly escaped, a malicious user could insert additionnal SQL statement. The statement could change the sementic of the original query. This could be use to circouncent the application logic. It can also be used maliciously to access data from other tables or escalate to the operating system.

Vulnerable Code

var cmd = new SqlCommand("SELECT * FROM Users WHERE username = '" + username + "' and role='user'");

Solution

var cmd = new SqlCommand("SELECT * FROM Users WHERE username = @username and role='user'");
cmd.Parameters.AddWithValue("username", username);

References

SqlCommand Class Documentation
WASC-19: SQL Injection
OWASP: Top 10 2013-A1-Injection
OWASP: SQL Injection Prevention Cheat Sheet
OWASP: Query Parameterization Cheat Sheet
CAPEC-66: SQL Injection
CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')