C# SQL injection not detected

  • versions used: SonarCloud
  • I am evaluating SonarCloud security scanning with a sample ASP.NET MVC 4.7.2 project and am not able to get it to identify SQL injection vulnerabilities.

My project is using the default Sonar Way quality profile.

Sample code:

public class HomeController : Controller
    {
        public ActionResult UnsafeSql(int id)
        {
            using (SqlConnection conn = new SqlConnection(""))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM Table WHERE Id = '" + id + "'");
                cmd.Connection = conn;
                conn.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
            }
            return View();
        }
    }

The command in UnsafeSql() has an injection vulnerability and should be flagged by SonarCloud according to Database queries should not be vulnerable to injection attacks. However, no rule violations are found.

I have tried variations of the code using a DataReader instead of DataAdapter and this does not trigger a rule violation either.

Hi Laura,

Thank you for sharing this code sample.
From what I see the user controlled variable is id. Because its type is int we consider this variable as safe. For example, if you try to inject something like ' OR '1'=1 in id the framework would throw an error.

Obviously it could behave differently on your side. If this is the case, let me know and I will investigate it further.

Best

1 Like

Hi Pierre-Loup,

I changed the parameter from an int to a string as suggested, but SonarCloud is still not finding any issues.

Revised code:

public ActionResult UnsafeSql(string id)
        {
            using (SqlConnection conn = new SqlConnection(""))
            {
                SqlCommand cmd = new SqlCommand("SELECT * FROM Table WHERE Id = '" + id + "'");
                cmd.Connection = conn;
                conn.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds);
            }
            return View();
        }

My sample code is in a public project at perkinscoie/sonarcloudmvctest if you want to take a look.

I believe you don’t see the issues you expect because your project is considered as a Test project: https://sonarcloud.io/documentation/analysis/scan/sonarscanner-for-msbuild/#detection-of-test-projects

Your project is named SonarCloudMVCTest. If you rename it SonarCloudMVC, you should see the expected SQLi.

Alex

That fixed it! I removed “Test” from the project name and analysis is now working. Thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.