![](/img/trans.png)
[英]Download and execute SQL script - what are the security issues + solutions?
[英]is it safe using dynamic SQL with parameters? If not, what security issues might it be exposed to?
例如,這是我正在使用的代碼:
String commandString = "UPDATE Members SET UserName = @newName , AdminLevel = @userLevel WHERE UserID = @userid";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString))
{
SqlCommand cmd = new SqlCommand(commandString, conn);
cmd.Parameters.Add("@newName", newName);
cmd.Parameters.Add("@userLevel", userLevel);
cmd.Parameters.Add("@userid", userid);
conn.Open();
cmd.ExecuteReader();
Reader.Close();
}
該代碼看起來很好。 參數化是一種方法,而不是在一個特殊的SQL語句中連接用戶提供的值,這可以打開你的SQL注入攻擊。 這也可以幫助執行計划重用。
我唯一要補充的是,我更喜歡明確定義參數的數據類型和大小。 例如,如果不這樣做,那么作為示例,所有字符串值將作為NVARCHAR而不是VARCHAR傳遞到數據庫。 因此我喜歡明確。
它可以安全地防止SQL注入,因為它是參數化的。 其他安全問題,例如確保@userid不被欺騙,是應該在應用程序的其他層中處理的單獨的安全問題。
那仍然是一個靜態查詢字符串。 它不是真正的“動態”sql,直到您還可以動態構建部分字符串 - 如下所示:
var sql = "SELECT columns FROM Table WHERE 1=1";
if (!string.IsNullOrEmpty(txtName.Text)) sql += " AND Name LIKE '%' + @Name + '%'";
if (!string.IsNullOrEmpty(txtDesc.Text)) sql += " AND CONTAINS(DESCRIPTION, @description)";
但即便如此,只要您繼續使用源自用戶輸入的查詢的每個部分的參數,這在sql注入意義上仍然是“安全的”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.