防止xss(跨站脚本攻击)

Posted 专治spark

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了防止xss(跨站脚本攻击)相关的知识,希望对你有一定的参考价值。

采用bs4过滤的方式:

from bs4 import BeautifulSoup


class XSSFilter(object):
    __instance = None

    def __init__(self):
        # XSS白名单
        self.valid_tags = {
            "font": [color, size, face, style],
            b: [],
            div: [],
            "span": [],
        }

    def __new__(cls, *args, **kwargs):
        """
        单例模式
        :param cls:
        :param args:
        :param kwargs:
        :return:
        """
        if not cls.__instance:
            obj = object.__new__(cls, *args, **kwargs)
            cls.__instance = obj
        return cls.__instance

    def process(self, content):
        soup = BeautifulSoup(content, html.parser)
        # 遍历所有HTML标签
        for tag in soup.find_all(recursive=True):
            # 判断标签名是否在白名单中
            if tag.name not in self.valid_tags:
                tag.hidden = True
                if tag.name not in [html, body]:
                    tag.hidden = True
                    tag.clear()
                continue
            # 当前标签的所有属性白名单
            attr_rules = self.valid_tags[tag.name]
            keys = list(tag.attrs.keys())
            for key in keys:
                if key not in attr_rules:
                    del tag[key]

        return soup.decode()


if __name__ == __main__:
    html = """<p class="title">
                        <b>The Dormouses story</b>
                    </p>
                    <p class="story">
                        <div name=root>
                            Once upon a time there were three little sisters; and their names were
                            <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
                            <a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
                            and they lived at the bottom of a well.
                            <script>alert(123)</script>
                        </div>
                    </p>
                    <p class="story">...</p>"""

    obj = XSSFilter()
    v = obj.process(html)
    print(v)

 

以上是关于防止xss(跨站脚本攻击)的主要内容,如果未能解决你的问题,请参考以下文章

防止xss(跨站脚本攻击)

PHP实现的防止跨站和xss攻击代码

如何防止跨站点脚本攻击

特殊字符的过滤,防止xss攻击

php安全字段和防止XSS跨站脚本攻击过滤函数

php防止sql注入以及xss跨站脚本攻击