正则表达式防止XSS或其他东西

本文关键字:其他 XSS 正则表达式 | 更新日期: 2023-09-27 18:05:27

我正试图保护我的网站免受跨站点脚本(XSS),我正在考虑使用正则表达式来验证用户输入。

这是我的问题:我有一个危险的HTML标签列表…

<applet>
<body>
<embed>
<frame>
<script>
<frameset>
<html>
<iframe>
<img>
<style>
<layer>
<link>
<ilayer>
<meta>
<object>

…我想把它们包含在正则表达式中——这可能吗?如果没有,我应该用什么?你有什么想法来实现这样的东西吗?

正则表达式防止XSS或其他东西

    public static bool ValidateAntiXSS(string inputParameter)
    {
        if (string.IsNullOrEmpty(inputParameter))
            return true;
        // Following regex convers all the js events and html tags mentioned in followng links.
        //https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet                 
        //https://msdn.microsoft.com/en-us/library/ff649310.aspx
        var pattren = new StringBuilder();
        //Checks any js events i.e. onKeyUp(), onBlur(), alerts and custom js functions etc.             
        pattren.Append(@"((alert|on'w+|function's+'w+)'s*'('s*(['+'d'w](,?'s*['+'d'w]*)*)*'s*'))");
        //Checks any html tags i.e. <script, <embed, <object etc.
        pattren.Append(@"|(<(script|iframe|embed|frame|frameset|object|img|applet|body|html|style|layer|link|ilayer|meta|bgsound))");
        return !Regex.IsMatch(System.Web.HttpUtility.UrlDecode(inputParameter), pattren.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled);
    }

请阅读OWASP XSS(跨站点脚本)预防小抄表以获取广泛的信息。黑名单标记不是一种非常有效的方法,并且会留下空白。您应该过滤输入,在输出到浏览器之前进行清理,编码HTML实体,以及我的链接中讨论的各种其他技术。

您应该将字符串编码为HTML。使用dotNET方法

HttpUtils.HtmlEncode(string text)

有更多的细节http://msdn.microsoft.com/en-us/library/73z22y6h.aspx

将黑名单作为消毒处理是无效的,正如已经讨论过的那样。想想当有人提交精心设计的输入时,你的黑名单会发生什么:

<SCRIPT>
<ScRiPt>
< S C R I P T >
<scr&#00ipt>
<scr<script>ipt>(是否递归应用黑名单;-))

这不是一个可能的攻击的枚举,但只是一些例子记住如何黑名单可以被击败。这些都将在浏览器中正确呈现。