2015-10-16 50 views
0

所以我有點問題。在我開發的網站上,我允許人們輸入地址,一旦他們點擊保存按鈕,他們輸入的地址就會存儲在我的數據庫中。ASP.NET中的參數化查詢SQL注入

我(誤)的印象是,使用參數化查詢將有助於防止SQL注入,這裏是我的代碼,一旦按下「保存」

SqlConnection Conn = new SqlConnection(@"Data Source=**********;Initial Catalog=********;Persist Security Info=True;User ID=******;Password=*********"); 
SqlCommand updateMeeting = new SqlCommand(@"UPDATE [*******].[dbo].[**********] SET [email protected], [email protected], [email protected], [email protected] WHERE Title = '" + commands[1] + "' AND Date = '" + Convert.ToDateTime(commands[2]) + "' AND Location = '" + commands[3] + "'", Conn); 
updateMeeting.Parameters.AddWithValue("@title", newTitle); 
updateMeeting.Parameters.AddWithValue("@date", newDate); 
updateMeeting.Parameters.AddWithValue("@location", newLocation); 
updateMeeting.Parameters.AddWithValue("@announcement", newBody); 
updateMeeting.Connection.Open(); 
updateMeeting.ExecuteNonQuery(); 
updateMeeting.Connection.Close(); 

newTitle的newDate,newLocation和newBody只是字符串變量取自他們相關的文本框。

請放心,命令數組已被消毒。這不是我的注射問題起作用的地方。

,但如果我輸入以下爲我的「位置」文本框中注入攻擊成功,並連續被添加到我的數據庫

');INSERT INTO [********].[dbo].[*********] (Title) VALUES ('Injection'); -- 

所以很明顯,我錯過了一些東西或者我不理解這些參數化查詢如何工作。這不是確保「位置」的VarChar值只是「')的全部要點; INSERT INTO [****]。[dbo]。[******](Title) VALUES('Injection'); - 「

注射攻擊不應該失敗嗎?

+3

'和位置=「」 +命令[3]'這不是參數化,只是正常的級聯所以有人能寫什麼 – lad2025

+1

你的整個'WHERE'條款採用級聯。 – Greg

+0

當執行注入嘗試的語句時'commands [3]'的值是什麼? –

回答

3

你真正貼近 - 你有你參數與更新的值,而不是值在WHERE條款。嘗試這樣的事情,而不是:

SqlConnection Conn = new SqlConnection(@"Data Source=**********;Initial Catalog=********;Persist Security Info=True;User ID=******;Password=*********"); 
SqlCommand updateMeeting = new SqlCommand(@" 
    UPDATE [*******].[dbo].[**********] 
    SET [email protected], 
     [email protected], 
     [email protected], 
     [email protected] 
    WHERE Title = @commands1 
     AND Date = @commands2 
     AND Location = @commands3", 
     Conn); 
updateMeeting.Parameters.AddWithValue("@title", newTitle); 
updateMeeting.Parameters.AddWithValue("@date", newDate); 
updateMeeting.Parameters.AddWithValue("@location", newLocation); 
updateMeeting.Parameters.AddWithValue("@announcement", newBody); 
updateMeeting.Parameters.AddWithValue("@commands1", commands[1]); 
updateMeeting.Parameters.AddWithValue("@commands2", Convert.ToDateTime(commands[2])); 
updateMeeting.Parameters.AddWithValue("@commands3", commands[3]); 
updateMeeting.Connection.Open(); 
updateMeeting.ExecuteNonQuery(); 
updateMeeting.Connection.Close(); 
+0

好的答案,顯示可能的解決方案,而不是隻指出問題+1。OP可能想使用'Parameters.Add(「@ title」,SqlType.VarChar ).Value = newTitle' for de claring參數。 'AddWithValue'有一些風險取決於數據庫類型/大小。 – ovaltein

+0

感謝您的代碼和快速響應。我很高興在它投入生產之前它被抓住並修好了。 –

1

這不是一個參數化查詢。在你where條款你只是連接字符串:

"... WHERE Title = '" + commands[1] + "' AND Date = '" + Convert.ToDateTime(commands[2]) + "' AND Location = '" + commands[3] + "'"