Is it safe to use [innerHTML] in Angular 5?
Asked Answered
C

2

30

I have seen conflicting reports that it is dangerous to use the [innerHTML] tag in Angular2+. Is that still the case or has it since been fixed?

for example is this code dangerous:

<div [innerHTML]="post.body"></div>
Cuba answered 20/11, 2017 at 15:28 Comment(1)
Yes, it's safe. Have a look at the Angular security documentation.Hexapod
B
21

as it said in here (in angular site itself), it looks like there are no worries about it because angular, automatically recognize the unsafe values and sanitizes them.

here is what written in there:

Interpolated content is always escaped—the HTML isn't interpreted and the browser displays angle brackets in the element's text content.

For the HTML to be interpreted, bind it to an HTML property such as innerHTML. But binding a value that an attacker might control into innerHTML normally causes an XSS vulnerability. For example, the code contained in a <script> tag is executed:

export class InnerHtmlBindingComponent { // For example, a user/attacker-controlled value from a URL. htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>'; }

Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the text content of the <script> tag and the <b> element.

so I think, yes it is safe.

Burstone answered 3/3, 2018 at 7:4 Comment(0)
O
14

I confirm.

I just tried the following <div [innerHTML]="<span (touch)=() => {alert('Code has been successfully executed on client from external malicious input');}">test xss</span>"></div>

Nothing is executed and the DOM inspection shows that (touch) has been removed from the span by angular. It's all good ;-)

Otti answered 14/6, 2018 at 5:53 Comment(1)
even if you would bypass sanitization it would not work.Eightieth

© 2022 - 2024 — McMap. All rights reserved.