简体   繁体   中英

jquery - how to escape html to prevent XSS?

I'm using laravel, when a user sends a text message, it may contain some malicious code. When I use {{}} it will show me the exact text the user has sent. If he has sent

<script>alert("malicious")</script>

it will show exactly the same and it's good, but when I use jquery ajax, I put the fetched data to some variables within some html tags and lastly append all of them to a main tag like so:

   data = '';
    //loop starts here // some otger codes deleted for cleanness
    data += "<h2>"+response.name+"</h2>";
    data += "<p>"+response.description+"</p>";
    $('#mydata').html(data);

and now the problem is that if I use html() the user malicious code will be executed and if I don't, the result will not be shown as html.

I guess I should do something with $.parseHTML , isn't it?

Thanks

You should use jQuery text() to encode the data.

$('#mydata').text(data);

EDIT: To create the content of #mydata you can use

$('#mydata')
  .html("")
  .append($("<h2></h2>").text(response.name))
  .append($("<p></p>").text(response.description))

You can also do this to remove tags...

$('#mydata').text(data).replace(/(<([^>]+)>)/ig,"");

read more on this post Todo List Sanitizing Input jQuery

you cannot render user data as HTML and escape it into safe way in the same time. You may assume that some god-level regex could help you to drop just attributes but not tags. Unfortunately there are so many ways to inject JS into markup then you will never be sure.

So you have just few options:

  1. ignore risks at all

  2. escape all the things (either using jQuery's text() or escaping on backend side with htmlspecialchars()

  3. use non-HTML markup that is translated to HTML by simple rules in controlled way

I used:

npm js-htmlencode

and it worked.

We had a similar scenario in of the project I worked. We used to get html content from server side which should be appended to DOM using Jquery. Before adding it to Add, we wanted to validate the HTML content we received from Server to safe guard the XSS security issues. Following is the generic method to encode the HTML content,

function htmlEncode(source) {
  return $("<div>").text(source).html();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM