[C#] 檢查 Sql Injection 非法字元


Posted by mike-hsieh on 2023-11-16

在一些舊專案中,可能有些Sql仍然使用字串相加或是插值語法,這確實會造成不小的隱憂,如果沒有辦法改為參數化,那盡可能提升安全性的方式就是去檢查輸入的字串,以下紀錄。

/// <summary>
/// 檢查SQL非法字元
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public bool IsSafeSqlString(string input)
{
    string[] riskTokens = new string[] { "--", ";--", ";", "/*", "*/", "@@",
                                 "@", "char", "nchar", "varchar", "nvarchar",
                                 "alter", "begin", "cast", "create", "cursor",
                                 "declare", "delete", "drop", "end", "exec",
                                 "execute", "fetch", "insert", "kill", "select",
                                 "sys", "sysobjects", "syscolumns", "table",
                                 "update" };

    foreach (var token in riskTokens)
    {
        if (input?.ToLower()?.IndexOf(token, StringComparison.OrdinalIgnoreCase) != -1)
            return false;
    }

    return true;
}









Related Posts

1251. Average Selling Price

1251. Average Selling Price

Vue.js 學習旅程Mile 5 – 模板語法之二:Directives 指令

Vue.js 學習旅程Mile 5 – 模板語法之二:Directives 指令

DOM 節點 相關屬性

DOM 節點 相關屬性


Comments