1

I used ng-bind-html in order to prevent cross site scripting, read about sanitize and found this discussion and another good discussion.

Although, i did't work for me, can you please help me in figure out why?

HTML:

<p class="big-text" ng-bind-html="to_trusted(message)">

JS:

$scope.to_trusted = function(html_code) {
    return $sce.trustAsHtml(html_code);
};

when i'm adding the following line

<img src="x" onerror="alert('cross')">

and adding it to a message i can see it rendered in the DOM, and when i'm refreshing the page i can see the message.

dom image

and the popup is shown: enter image description here

can you please tell me what am i doing wrong?

3
  • Is this cross-site how? Looks like you are calling it in the same page. Commented Feb 4, 2015 at 15:57
  • every user that will open the site will get this alert, instead of the alert it can be malicious script Commented Feb 4, 2015 at 16:00
  • Liad, this is not cross-site, it is your own site accepting untrusted user input (you should sanitize the content of the message at the server, not at the client). Commented Feb 4, 2015 at 16:04

2 Answers 2

12

First of all, it's not XSS on its own.

Second, $sce.trustAsHtml does exactly the opposite of what you thought - it, in fact, instructs Angular to "trust" that the HTML is safe - not to sanitize.

To sanitize, you need to add ngSanitize as a dependency to your app, and ng-bind-html directly to html_code (without to_trusted).

angular.module("myApp", ["ngSanitize"])
  .controller("MainCtrl", function($scope){
     $scope.html_code = '<img src="x" onerror="alert(\'cross\')">';
  });

And in the HTML:

<div ng-bind-html="html_code"></div>
Sign up to request clarification or add additional context in comments.

Comments

4

After using Sanitize i change my code and used getTrustedHtml instead trustAsHtml, it runs the sanitize on controller.

$scope.to_trusted = function(html_code) {
    return $sce.getTrustedHtml(html_code);
};

And it solves my issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.