I have been challenged with the task of reducing SQL injection in somebody elses code however the tool that im using to scan my code doesnt give an explanation on where the injections are, as it just points out the method. Take the following code as an example
public static CommandStatus<int> CreateTable(SqlConnection connection, String tableName, SQLColumn[] columns)
{
string colSQL = columns.Select(f => f.ToString()).Aggregate((f1, f2) => f1 + ",\n" + f2);
if(columns.FirstOrDefault(e => e.IsPK()) != null){
string constraint = GenerateTableConstraint(tableName, columns.FirstOrDefault(e => e.IsPK()).ColumnName());
colSQL += constraint;
}
string sql = "CREATE TABLE " + ParseTableName(tableName) + " (" + colSQL + ") ON [PRIMARY]";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = connection;
cmd.CommandTimeout = GetTimeout();
try
{
int result = cmd.ExecuteNonQuery();
return new CommandStatus<int>(result);
}
catch (Exception e)
{
return new CommandStatus<int>("Failed to create tableName " + tableName + " [SQL: " + sql + "]:" + e.Message, e);
}
}
The ouput from colSQL is
"[RecordID] [NVARCHAR](255) NULL,\n[Address1] [NVARCHAR](255) NULL,\n[Address2] [NVARCHAR](255) NULL,\n[Address3] [NVARCHAR](255) NULL,\n[Address4] [NVARCHAR](255) NULL,\n[Address5] [NVARCHAR](255) NULL,\n[MongoId] [NVARCHAR](100) NOT NULL"
SQLColumns[] columns is just an array of the following
Record
nvarchar(255)
null
My understanding of the inject is that surrounding a string with "[]" makes it safe. IF this is not the case how would I go about making this method SQL inject free.
If you're using Visual Studio, then you can run source code analysis on the solution and it will raise a CA3001 warning when it detects troublespots.
CA3001: Review code for SQL injection vulnerabilities
https://learn.microsoft.com/en-us/visualstudio/code-quality/ca3001
https://learn.microsoft.com/en-us/visualstudio/code-quality/code-analysis-for-managed-code-overview