C# 在不使用参数化查询的情况下,在SQLWHERE子句中包含数据同时避免SQL注入风险的最安全的方法是什么?

C# 在不使用参数化查询的情况下,在SQLWHERE子句中包含数据同时避免SQL注入风险的最安全的方法是什么?,c#,sql,C#,Sql,让字符串安全地包含在SQL查询中的好函数是什么?例如,撇号需要修正,毫无疑问,还会出现其他问题。我想要一个功能,是坚如磐石,将工作给予任何可能的输入一个恶棍可以设计 现在,在大众告诉我使用查询参数和/或否决/关闭这个问题之前,请考虑以下几点: 我一直在使用设计糟糕的API的第三方库。API应按如下方式调用: dataObjectVariable.FindWhere("WHERE RecordID = '(your string here)'"); 现在,我100%同意您的看法,这不是一个好的

让字符串安全地包含在SQL查询中的好函数是什么?例如,撇号需要修正,毫无疑问,还会出现其他问题。我想要一个功能,是坚如磐石,将工作给予任何可能的输入一个恶棍可以设计

现在,在大众告诉我使用查询参数和/或否决/关闭这个问题之前,请考虑以下几点:

  • 我一直在使用设计糟糕的API的第三方库。API应按如下方式调用:

    dataObjectVariable.FindWhere("WHERE RecordID = '(your string here)'");
    
    现在,我100%同意您的看法,这不是一个好的API,因为它(1)向用户公开了内部数据库字段名称,这些名称是实现细节,(2)没有提供使用参数的机会,这些参数首先可以避免这个问题,(3)真的,您可以说SQL本身是一个实现细节,不应该被公开。但我一直在使用这个API,因为它需要与业界领先的系统之一集成。我们也不能要求他们更改API

  • 我在这个网站上搜索了与这个问题相关的其他问题,但发现答案倾向于强烈建议参数化查询。那些试图建议编写一个函数来清理字符串的答案经常被否决,没有经过深思熟虑,等等——我不确定我是否信任他们


我只搜索字符串,而不搜索其他数据类型,如数字、日期等。同样,我100%意识到使用参数化查询的好处,我希望我能使用它们,但我不能,因为我的手被限制在这一点上。

我必须在我们的一个应用程序中使用类似的API。下面是我用来手动绕过SQL注入的验证例程:



internal class SqlInjectionValidator
{

    internal static readonly List _s_keywords = new List
    {
        "alter",
        "begin",
        "commit",
        "create",
        "delete",
        "drop",
        "exec",
        "execute",
        "grant",
        "insert",
        "kill",
        "load",
        "revoke",
        "rollback",
        "shutdown",
        "truncate",
        "update",
        "use",
        "sysobjects"
    };

    private string _sql;
    private int _pos;
    private readonly Stack _literalQuotes = new Stack();
    private readonly Stack _identifierQuotes = new Stack();
    private int _statementCount;

    // Returns true if s does not contain SQL keywords.
    public SqlValidationStatus Validate(string s)
    {
        if (String.IsNullOrEmpty(s))
        {
            return SqlValidationStatus.Ok;
        }

        _pos = 0;
        _sql = s.ToLower();
        _literalQuotes.Clear();
        _identifierQuotes.Clear();
        _statementCount = 0;

        List chars = new List();

        SqlValidationStatus svs;
        while (_pos = _sql.Length)
            {
                break;
            }

            if (_statementCount != 0)
            {
                return SqlValidationStatus.SqlBatchNotAllowed;
            }

            char c = _sql[_pos];
            if (IsEmbeddedQuote(c))
            {
                _pos++;
                chars.Add(_sql[_pos]);
                _pos++;
                continue;
            }

            if (c != '\'' &&
                    IsQuotedString())
            {
                chars.Add(c);
                _pos++;
                continue;
            }

            if (c != ']' &&
                    c != '[' &&
                    c != '"' &&
                    IsQuotedIdentifier())
            {
                chars.Add(c);
                _pos++;
                continue;
            }

            switch (c)
            {
                case '[':
                    if (_identifierQuotes.Count != 0)
                    {
                        return SqlValidationStatus.MismatchedIdentifierQuote;
                    }
                    svs = DisallowWord(chars);
                    if (svs != SqlValidationStatus.Ok)
                    {
                        return svs;
                    }
                    _identifierQuotes.Push(c);
                    break;

                case ']':
                    if (_identifierQuotes.Count != 1 ||
                            _identifierQuotes.Peek() != '[')
                    {
                        return SqlValidationStatus.MismatchedIdentifierQuote;
                    }
                    svs = DisallowWord(chars);
                    if (svs != SqlValidationStatus.Ok)
                    {
                        return svs;
                    }
                    _identifierQuotes.Pop();
                    break;

                case '"':
                    if (_identifierQuotes.Count == 0)
                    {
                        svs = DisallowWord(chars);
                        if (svs != SqlValidationStatus.Ok)
                        {
                            return svs;
                        }
                        _identifierQuotes.Push(c);
                    }
                    else if (_identifierQuotes.Count == 1)
                    {
                        svs = DisallowWord(chars);
                        if (svs != SqlValidationStatus.Ok)
                        {
                            return svs;
                        }
                        _identifierQuotes.Pop();
                    }
                    else
                    {
                        return SqlValidationStatus.MismatchedIdentifierQuote;
                    }
                    break;

                case '\'':
                    if (_literalQuotes.Count == 0)
                    {
                        svs = DisallowWord(chars);
                        if (svs != SqlValidationStatus.Ok)
                        {
                            return svs;
                        }
                        _literalQuotes.Push(c);
                    }
                    else if (_literalQuotes.Count == 1 &&
                            _literalQuotes.Peek() == c)
                    {
                        _literalQuotes.Pop();
                        chars.Clear();
                    }
                    else
                    {
                        return SqlValidationStatus.MismatchedLiteralQuote;
                    }
                    break;

                default:
                    if (Char.IsLetterOrDigit(c) ||
                            c == '-')
                    {
                        chars.Add(c);
                    }
                    else if (Char.IsWhiteSpace(c) ||
                            Char.IsControl(c) ||
                            Char.IsPunctuation(c))
                    {
                        svs = DisallowWord(chars);
                        if (svs != SqlValidationStatus.Ok)
                        {
                            return svs;
                        }
                        if (c == ';')
                        {
                            _statementCount++;
                        }
                    }
                    break;
            }

            _pos++;
        }

        if (_literalQuotes.Count != 0)
        {
            return SqlValidationStatus.MismatchedLiteralQuote;
        }

        if (_identifierQuotes.Count != 0)
        {
            return SqlValidationStatus.MismatchedIdentifierQuote;
        }

        if (chars.Count > 0)
        {
            svs = DisallowWord(chars);
            if (svs != SqlValidationStatus.Ok)
            {
                return svs;
            }
        }

        return SqlValidationStatus.Ok;
    }

    // Returns true if the string representation of the sequence of characters in
    // chars is a SQL keyword.
    private SqlValidationStatus DisallowWord(List chars)
    {
        if (chars.Count == 0)
        {
            return SqlValidationStatus.Ok;
        }

        string s = new String(chars.ToArray()).Trim();
        chars.Clear();

        return DisallowWord(s);
    }

    private SqlValidationStatus DisallowWord(string word)
    {
        if (word.Contains("--"))
        {
            return SqlValidationStatus.CommentNotAllowed;
        }
        if (_s_keywords.Contains(word))
        {
            return SqlValidationStatus.KeywordNotAllowed;
        }
        if (_statementCount > 0)
        {
            return SqlValidationStatus.SqlBatchNotAllowed;
        }
        if (word.Equals("go"))
        {
            _statementCount++;
        }

        return SqlValidationStatus.Ok;
    }

    private bool IsEmbeddedQuote(char curChar)
    {
        if (curChar != '\'' ||
                !IsQuotedString() ||
                IsQuotedIdentifier())
        {
            return false;
        }

        if (_literalQuotes.Peek() == curChar &&
                Peek() == curChar)
        {
            return true;
        }

        return false;
    }

    private bool IsQuotedString()
    {
        return _literalQuotes.Count > 0;
    }

    private bool IsQuotedIdentifier()
    {
        return _identifierQuotes.Count > 0;
    }

    private char Peek()
    {
        if (_pos + 1 < _sql.Length)
        {
            return _sql[_pos + 1];
        }

        return '\0';
    }

}

内部类SqlInjectionValidator
{
内部静态只读列表_s_关键字=新列表
{
“改变”,
“开始”,
“提交”,
“创建”,
“删除”,
“放下”,
“执行官”,
“执行”,
“赠款”,
“插入”,
“杀死”,
“加载”,
“撤销”,
“回滚”,
“关闭”,
“截断”,
“更新”,
“使用”,
“系统对象”
};
私有字符串sql;
私人国际邮政;
私有只读堆栈_literalQuotes=新堆栈();
私有只读堆栈_identifierQuotes=新堆栈();
私有int_语句计数;
//如果s不包含SQL关键字,则返回true。
公共SqlValidationStatus验证(字符串s)
{
if(String.IsNullOrEmpty)
{
返回SqlValidationStatus.Ok;
}
_pos=0;
_sql=s.ToLower();
_literalQuotes.Clear();
_identifierQuotes.Clear();
_statementCount=0;
列表字符=新列表();
SqlValidationStatus svs;
while(_pos=_sql.Length)
{
打破
}
如果(_statementCount!=0)
{
返回SqlValidationStatus.SqlBatchNotAllowed;
}
字符c=_sql[_pos];
如果(i嵌入报价(c))
{
_pos++;
字符添加(_sql[_pos]);
_pos++;
继续;
}
如果(c!='\''&&
IsQuotedString())
{
添加(c)项;
_pos++;
继续;
}
如果(c!=']'&&
c!='['&&
c!=“”&&
IsQuoteIdentifier())
{
添加(c)项;
_pos++;
继续;
}
开关(c)
{
案例“[”:
如果(_identifierQuotes.Count!=0)
{
返回SqlValidationStatus.mismatchDidIdentifierQuote;
}
svs=不允许字(字符);
if(svs!=SqlValidationStatus.Ok)
{
返回svs;
}
_推送(c);
打破
案例']':
如果(_identifierQuotes.Count!=1||
_identifierQuotes.Peek()!='[')
{
返回SqlValidationStatus.mismatchDidIdentifierQuote;
}
svs=不允许字(字符);
if(svs!=SqlValidationStatus.Ok)
{
返回svs;
}
_identifierQuotes.Pop();
打破
案例'':
如果(_identifierQuotes.Count==0)
{
svs=不允许字(字符);
if(svs!=SqlValidationStatus.Ok)
{
返回svs;
}
_推送(c);
}
else if(_identifierQuotes.Count==1)
{
svs=不允许字(字符);
if(svs!=SqlValidationStatus.Ok)
{
返回svs;
}
_identifierQuotes.Pop();
}
其他的
{
返回SqlValidationStatus.mismatchDidIdentifierQuote;
}
打破
案例'\'':
如果(_literalQuotes.Count==0)
{
svs=不允许字(字符);
if(svs!=SqlValidationStatus.Ok)
WHERE RecordID = 'DEMO'
WHERE RecordID = 0x44454D4F