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?

Community
  • 1
  • 1
Liad Livnat
  • 7,435
  • 16
  • 60
  • 98

2 Answers2

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>
New Dev
  • 48,427
  • 12
  • 87
  • 129
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.

Liad Livnat
  • 7,435
  • 16
  • 60
  • 98