How to protect user specified table name from SQL Injection in C#, using MySQL

徘徊边缘 提交于 2019-12-12 04:44:20

问题


As a reaction to MySqlParameter as TableName, it seems that MySQL's Connector/NET library doesn't support table names from user input in the following way:

MySqlCommand cmd = new MySqlCommand("SELECT * FROM @table");
cmd.Parameters.AddWithValue("@table",TableNameFromUserInput);

So I tried to find another way, but I couldn't find any libraries that did this for me.

When searching for how to do this manually, I couldn't found anything that didn't tell you to use "prepared statements" from some already defined library, no matter the language.

To my limited knowledge of SQL, I only think it's necessary to put backticks (`) around the user input and then check the input for backticks - but I wanted to be sure.

Question

How do you protect a user specified table name from SQL-Injection when the MySQL Connector doesn't support it?


回答1:


Check if

TableNameFromUserInput

is an existing table, before executing the query. That prevents other errors like "table doesnt exist" aswell.




回答2:


you cannot add tableName (as well as columnName) as parameter in prepared statements because it only supports for a value. For your safety, add additional code to validate tableName, ex.

string tableName = "hello";
tableName = UDFunctionClean(tableName);
string query = String.Format("SELECT * FROM `{0}`", tableName);
MySqlCommand cmd = new MySqlCommand(query);


来源:https://stackoverflow.com/questions/13495968/how-to-protect-user-specified-table-name-from-sql-injection-in-c-using-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!