[英]Regex for detecting SQL Injections in WinForms
我想要cach輸入,這似乎像SQL注入。 所以我寫了這個方法:
public static bool IsInjection(string inputText)
{
bool isInj = false;
string regexForTypicalInj = @"/\w*((\%27)|(\'))((\%6F)|o|(\%4F))((\%72)|r|(\%52))/ix";
Regex reT = new Regex(regexForTypicalInj);
if (reT.IsMatch(inputText))
isInj = true;
string regexForUnion = @"/((\%27)|(\'))union/ix";
Regex reUn = new Regex(regexForUnion);
if (reUn.IsMatch(inputText))
isInj = true;
string regexForSelect = @"/((\%27)|(\'))select/ix";
Regex reS = new Regex(regexForSelect);
if (reS.IsMatch(inputText))
isInj = true;
string regexForInsert = @"/((\%27)|(\'))insert/ix";
Regex reI = new Regex(regexForInsert);
if (reI.IsMatch(inputText))
isInj = true;
string regexForUpdate = @"/((\%27)|(\'))update/ix";
Regex reU = new Regex(regexForUpdate);
if (reU.IsMatch(inputText))
isInj = true;
string regexForDelete = @"/((\%27)|(\'))delete/ix";
Regex reDel = new Regex(regexForDelete);
if (reDel.IsMatch(inputText))
isInj = true;
string regexForDrop = @"/((\%27)|(\'))drop/ix";
Regex reDr = new Regex(regexForDrop);
if (reDr.IsMatch(inputText))
isInj = true;
string regexForAlter = @"/((\%27)|(\'))alter/ix";
Regex reA = new Regex(regexForAlter);
if (reA.IsMatch(inputText))
isInj = true;
string regexForCreate = @"/((\%27)|(\'))create/ix";
Regex reC = new Regex(regexForCreate);
if (reC.IsMatch(inputText))
isInj = true;
return isInj;
}
但似乎我做了一些錯誤,因為我的代碼不檢測注射。 我做錯了什么? 我想在定義Regex表達式時有問題嗎?
不要使用字符串解析或正則表達式來處理這類事情。 SQL語法太復雜,無法使用正則表達式進行可靠的解析。
而是使用帶占位符的參數化查詢,並完全避免字符串連接。 這將在其根源上擊敗SQL注入。
var command = new SqlCommand(connection);
command.Text = "INSERT INTO foo (a, b, c) VALUES (@a, @b, @c)";
command.Parameters.AddWithValue("a", "this is invulnerable");
command.Parameters.AddWithValue("b", "to any sort of SQL injection");
command.Parameters.AddWithValue("c", "--'; DROP DATABASE");
command.ExecuteNonQuery();
如果你真的想幫助你的“不那么有經驗的程序員”,你最好不要試圖檢測他們在代碼中執行內聯sql的時間。 寫一個FxCop規則來發現它應該不會太困難。 如果您將其作為后期構建過程的一部分包含在內,或者如果您有團隊系統,則將規則設置為使構建失敗,他們很快就會掌握它。
SQL注入的問題是,用戶輸入用作SQL語句的一部分。 通過使用預准備語句,您可以強制將用戶輸入作為參數的內容進行處理(而不是作為SQL命令的一部分)。 查詢參數通過將文字值與SQL語法分開來幫助避免此風險。
大多數客戶端API(包括.NET)都支持查詢的參數化。 這允許將用戶輸入嵌入為參數。 參數是用戶輸入值的占位符,在執行時替換。 這樣,用戶無法注入SQL代碼,因為整個用戶條目被視為參數的值,而不是作為追加到查詢的字符串。
參數化是SQL注入攻擊的最佳解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.