You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OWASP Policy Factory sanitizer阻止HTML注入的问题及解决咨询

OWASP HTML Sanitizer 未阻止<img src="1"/>注入的问题排查与解决

问题原因

你当前配置的策略明确允许了<img>元素及其src属性,仅对<a>标签的href协议做了https限制,对<img>的src没有任何协议或内容校验规则。所以当传入<img src="1"/>时,sanitizer会认为这是符合规则的内容,不会将其过滤为空字符串。

解决方法

根据你的需求选择对应方案:

方案1:完全禁止所有<img>元素

直接移除策略中关于<img>的配置项,这样所有<img>标签都会被过滤掉:

PolicyFactory policy = new HtmlPolicyBuilder()
    .allowElements("a")
    .allowUrlProtocols("https")
    .allowAttributes("href").onElements("a")
    .requireRelNofollowOnLinks()
    .build();

方案2:仅允许src为HTTPS协议的<img>元素

给<img>的src属性添加HTTPS协议校验,不符合的src会被移除,若<img>无合法属性则会被过滤:

PolicyFactory policy = new HtmlPolicyBuilder()
    .allowElements("a")
    .allowUrlProtocols("https")
    .allowAttributes("href").onElements("a")
    .requireRelNofollowOnLinks()
    .allowAttributes("src").onElements("img").matching(HtmlPolicyBuilder.SCHEME_HTTPS)
    .build();

方案3:自定义规则过滤无效<img>

如果需要更严格的校验(比如检查src是否为完整有效的HTTPS URL),可以自定义验证逻辑,同时配置必须有合法src才保留<img>:

PolicyFactory policy = new HtmlPolicyBuilder()
    .allowElements("a")
    .allowUrlProtocols("https")
    .allowAttributes("href").onElements("a")
    .requireRelNofollowOnLinks()
    .allowAttributes("src").onElements("img").matching((context, value) -> {
        // 这里可以自定义验证逻辑,示例:检查是否为完整HTTPS URL
        return value != null && value.startsWith("https://") && value.length() > 8;
    })
    // 强制要求img必须有合法的src属性,否则移除整个元素
    .requireAttributes("src").onElements("img")
    .build();

内容的提问来源于stack exchange,提问作者Andi Hasanaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:40:06