Patrick Son
Patrick Son

Reputation: 3

Angular 2 DomSanitizer: Cannot trust both HTML and CSS without also allowing JavaScript

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.

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>"

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)"

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?

Upvotes: 0

Views: 1500

Answers (1)

funkizer
funkizer

Reputation: 4897

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.

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>

Upvotes: 3

Related Questions