SQL Injection High

SQL Injection is a critical vulnerability that can lead to data or system compromise. By dynamically generating SQL query strings, user input may be able to influence the logic of the SQL statement. This could lead to an adversary accessing information they should not have access to, or in some circumstances, being able to execute OS functionality or code.

Detector ID
csharp/sql-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1public void SqlInjectionNoncompliant(string sql)
2{
3    using (SqlConnection connection = 
4           new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI;")) {
5        connection.Open();
6        // Noncompliant: Detected a formatted string in a SQL statement.
7        SqlCommand command= new SqlCommand(sql);
8    }
9}

Compliant example

1public void SqlInjectionCompliant()
2{
3    using (SqlConnection connection =
4           new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI;"))
5    {
6        string sql = "SELECT * FROM Customers WHERE EmployeeId = @EmployeeId";
7        // Compliant: Obtain a PreparedStatement 'SqlParameter'.
8        SqlCommand command = new SqlCommand(sql);
9        command.Parameters.Add(new SqlParameter("@EmployeeId", System.Data.SqlDbType.Int));
10    }
11}