Warning: SQL injection attacks

452 Views Asked by At

I have been trying to adapt my code to FxCop rules and I found this warning: CA2100 Review the query string passed to 'OleDbDataAdapter.OleDbDataAdapter(string, OleDbConnection)' in 'WavesShaperNew.Parse(string, int)' for possible SQL injection attacks. If the string is composed using any user input, consider using a stored procedure or a parameterized SQL query instead of building the query with string concatenations.

I have searched in the Microsoft Official Site and similar questions, but still do not understand what this warning mean and how to solve it.

ComboBox sheets = new ComboBox();
TextBox startRange = new TextBox();
TextBox endRange = new TextBox();

string query = string.Format("SELECT * FROM[" + sheets.SelectedItem + startRange.Text + ":" + endRange.Text + "]");
query = query.Replace("'", "");

OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
1

There are 1 best solutions below

2
Johnathan Barclay On BEST ANSWER

You should generally parameterise all SQL queries to avoid SQL injection attacks, rather than using string concatenation / interpolation.

However, table names cannot be parameterised.

To avoid SQL injection here, you can whitelist your valid table names:

var queryableTables = new HashSet<string>
{
    "table1",
    "table2",
    // etc.
};

string tableName = sheets.SelectedItem + startRange.Text;

if (!queryableTables.Contains(tableName))
{
    throw new InvalidOperationException($"{tableName} is not queryable");
}

string query = $"SELECT * FROM [{tableName}]");