用于在WinForms中检测SQL注入的正则表达式

vts*_*123 5 c# regex sql-injection

我想要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;

    }
Run Code Online (Sandbox Code Playgroud)

但似乎我做了一些错误,因为我的代码不检测注射.我做错了什么?我想在定义Regex表达式时有问题吗?

Ode*_*ded 15

不要试图用RegEx做到这一点 - 有很多方法可以解决它.请参阅这个关于使用RegEx进行解析的经典SO答案 - 它特定于HTML,但仍然适用.

您应该使用参数,这些参数位于BCL中并且内置了反SQL注入措施.

更新:(以下评论)

如果您真的必须解析SQL,请不要使用RegEx,原因是链接文章中列出的原因.RegEx不是解析器,不应该用作一个解析器.

使用SQL解析器 - 这应该有助于清理尝试.这是一个,这里是另一个.

您可以继续进行科学调查.