Input Data Validation in C# - Anti Sql Injection

SQL Injection

SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands.

See more informationhttps://www.owasp.org/index.php/SQL_Injection


Anti SQL Injection Validation Rule

    public class AntiSqlInjectionValidationRule : IValidationRule
    {
        public bool IsValid(string input)
        {
            var pattern = new StringBuilder();

            //Checks any SQL meta-characters
            pattern.Append(@"(\%27)|(\')|(\-\-)|(\%23)|(#)");

            //Checks any SQL meta-characters
            pattern.Append(@"|((\%3D)|(=))[^\n]*((\%27)|(\')|(\-\-)|(\%3B)|(;))");

            //Checks any typical SQL Injection attack with keyword 'or'
            pattern.Append(@"|(\w*((\%27)|(\'))((\%6F)|o|(\%4F))((\%72)|r|(\%52)))");

            //Checks any SQL Injection with the 'UNION' keyword
            pattern.Append(@"|(((\%27)|(\')|(\s))union((\%27)|(\')|(\s)))");

            pattern.Append(@"|(((\%27)|(\')|(\s))and((\%27)|(\')|(\s)))");

            pattern.Append(@"|(((\%27)|(\')|(\s))or((\%27)|(\')|(\s)))");

            pattern.Append(@"|(((\%27)|(\')|(\s))insert(\s)into((\%27)|(\')|(\s)))");

            pattern.Append(@"|(((\%27)|(\')|(\s))insert((\%27)|(\')|(\s)))");
            
            //Checks any SQL Injection attacks on a MS SQL Server
            pattern.Append(@"|(exec(\s|\+)+(s|x)p\w+)");
            
            pattern.Append(@"|([\t\r\n])");

            pattern.Append(@"|(--[^\r\n]*)");

            pattern.Append(@"|(||[^\r\n]*)");

            pattern.Append(@"|(&&[^\r\n]*)");

            pattern.Append(@"|(=[^\r\n]*)");

            pattern.Append(@"|(/\*[\w\W]*?(?=\*/)\*/)");

            pattern.Append(@"|(b(ALTER|CREATE|DELETE|AND|OR|DROP|EXEC(UTE){0,1}|INSERT( +INTO){0,1}|MERGE|SELECT|UPDATE|UNION( +ALL){0,1})\b)");
            
            return !Regex.IsMatch(input, pattern.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }

    }

Comentarios