Angular 2 DomSanitizer:在不同时允许JavaScript的情况下无法同时信任HTML和CSS [英] Angular 2 DomSanitizer: Cannot trust both HTML and CSS without also allowing JavaScript

查看:28
本文介绍了Angular 2 DomSanitizer:在不同时允许JavaScript的情况下无法同时信任HTML和CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些需要保存到后端并以HTML形式呈现给其他用户的用户输入.它需要支持链接和CSS样式,但是要去除JavaScript以避免XSS攻击.

I have user input that needs to be saved to the backend and rendered to other users as HTML. It needs to support links and CSS styling, but strip out JavaScript to avoid XSS attacks.

考虑测试输入值 test =< span style ='color:red;'>< strong> Test</strong></span>< img src ='#'onerror ='alert(1)'hidden>< script> alert(2)</script>".如果我使用DomSanitizer中的bypassSecurityTrustHtml,它将保留所有内容,包括不安全的JavaScript:

Consider a test input value of test = "<span style='color: red;'><strong>Test</strong></span><img src='#' onerror='alert(1)' hidden><script>alert(2)</script>". If I use bypassSecurityTrustHtml from the DomSanitizer, it leaves everything in, including the unsafe JavaScript:

this.sanitizer.bypassSecurityTrustHtml(test)
// returns "<span style='color: red;'><strong>Test</strong></span><img src='#' onerror='alert(1)' hidden><script>alert(2)</script>"

但是,如果我使用sanitize方法,它会删除JavaScript,但也会删除CSS:

However, if I use the sanitize method, it takes out the JavaScript but also removes the CSS:

this.sanitizer.sanitize(SecurityContext.HTML, test);
// returns "<span><strong>Test</strong></span><img src="#" hidden="">alert(2)"

我是否仍然可以使用DomSanitizer保留HTML和CSS但删除JavaScript?还是我需要使用其他图书馆?

Is there anyway for me to use the DomSanitizer to keep HTML and CSS but remove JavaScript? Or will I need to use another library?

推荐答案

样式属性并不安全,因此,如果您不信任110%的用户,则不要允许他们.您的应用只有最弱的链接才安全.这可能也是为什么角钢也剥掉它们的原因.如果必须解决此问题,则需要其他解决方案.

Style attrs aren't safe, so if you don't trust your users 110%, don't allow them. Your app is only as safe as it's weakest link. It's probably why angular strips them too. If you must get around this, you need another solution.

使用样式进行xss的方法有很多种,但是考虑到一些简单的方法:

There are many ways to do xss with styles but consider something as simple as:

<a href="https://malicious.site" style="position:absolute;z-index:9999;top:0;left:0;bottom:0;right:0;opacity:0">You can't see me</a>

这篇关于Angular 2 DomSanitizer:在不同时允许JavaScript的情况下无法同时信任HTML和CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆