问题描述
我一直在尝试使我的代码适应Fxcop规则,但发现以下警告:CA2100查看“ WavesShaperNew.Parse(string,int)”中传递给“ OleDbDataAdapter.OleDbDataAdapter(string,OleDbConnection)”的查询字符串sql注入攻击。如果字符串是使用任何用户输入组成的,请考虑使用存储过程或参数化SQL查询,而不要使用字符串连接构建查询。
我已经搜索了Microsoft Official Site和类似的问题,但仍然不明白该警告的含义以及解决方法。
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);
解决方法
通常应参数化所有SQL查询以避免SQL injection攻击,而不是使用字符串串联/插值。
但是,表名无法参数化。
为避免在此处进行SQL注入,您可以将有效的表名列入白名单:
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}]");