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>
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 .
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.
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.
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.
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 ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With