Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 766
ahat91 Avatar asked Nov 20 '17 15:11

ahat91


People also ask

Is using innerHTML safe?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .

What is the disadvantage of innerHTML?

Disadvantages of innerHTMLIt is very slow because as inner HTML already parses the content even we have to parse the content again so that's why it takes time. When we have used the event handlers then the event handlers are not automatically attached to the new elements created by innerHTML.

Does angular sanitize innerHTML?

Angular comes with a built-in html sanitizer DomSanitizer , as a security feature, thats used whenever you use [innerHtml] . Its a great feature - but has a pretty annoying bug/feature in that if you have elements with inline styles, the styles wind up getting removed from your page.


2 Answers

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.

like image 73
Seyed Ali Roshan Avatar answered Oct 12 '22 19:10

Seyed Ali Roshan


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

like image 13
Dev Avatar answered Oct 12 '22 17:10

Dev