Input Data Validation in C# - Anti Cross Site Scripting

Cross Site Scripting

Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

See more information: https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
See more information about how to prevent ithttps://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

    public class AntiCrossSiteScriptingValidationRule : IValidationRule
    {

        public bool IsValid(string input)
        {
            var pattern = new StringBuilder();

            //Checks any events          
            pattern.Append(@"((alert|on\w+|function\s+\w+)\s*\(\s*(['+\d\w](,?\s*['+\d\w]*)*)*\s*\))");

            //Checks any html tags
            pattern.Append(@"|(<(script|iframe|embed|frame|frameset|object|img|applet|body|html|style|layer|link|ilayer|meta|bgsound))");

            //Checks any CSS Attacks 
            pattern.Append(@"|((\%3C)|<)((\%2F)|\/)*[a-z0-9\%]+((\%3E)|>)");

            //Checks any image tag Attack
            pattern.Append(@"|((\%3C)|<)((\%69)|i|(\%49))((\%6D)|m|(\%4D))((\%67)|g|(\%47))[^\n]+((\%3E)|>)");

            //Checks any CSS Attacks
            pattern.Append(@"|((\%3C)|<)[^\n]+((\%3E)|>)");
            
            return !Regex.IsMatch(input, pattern.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled);
        }

    }


Comentarios