简体   繁体   English

防止jQuery html()中的XSS

[英]Prevent XSS in jQuery html()

I receive data from a database using ajax and then adds it together with HTML code to the website using the .html() jQuery function, like this: 我使用ajax从数据库接收数据,然后使用.html()jQuery函数将其与HTML代码一起添加到网站,如下所示:

$.ajax({
    url: "getDatabaseData.php",
    type: "post",
    dataType: "json",
    success: function(response){
        $("#message-div").html(getMessagesHtml(response));
    }
});

function getMessagesHtml(messages){
    var result = "";
    for(var i = 0; i < messages.length; i++){
        result += 
            "<div>" + 
                "<p>Name: " + messages[i].name + "</p>" + 
                "<p>Message: " + messages[i].message + "</p>" + 
            "</div>";
    }
    return result;
}

Here is the getDatabaseData.php that gets and returns the data from the database: 这是从数据库获取并返回数据的getDatabaseData.php:

$messages = $CFG_DB->select("SELECT name, message FROM messages");
echo json_encode($messages);

Imagine for example if message contain the following text: 例如,假设消息中包含以下文本:

<script>XSS Attack code goes here</script>

My questions are: 我的问题是:

  1. Will there be an XSS issue when doing like this? 这样做会不会出现XSS问题?
  2. In case there is an issue, how can I prevent it? 万一出现问题,我该如何预防?

I guess that using text() instead of html() is not an option in this case since I also add html code. 我猜在这种情况下,使用text()而不是html()是不可行的,因为我还添加了html代码。

Without javascript, when printing the data using PHP I just use htmlentities on the variables received from the database to prevent XSS, for example htmlentities(messages[i].name) and htmlentities(messages[i].message). 没有javascript,当使用PHP打印数据时,我只是在从数据库接收的变量上使用htmlentities来防止XSS,例如htmlentities(messages [i] .name)和htmlentities(messages [i] .message)。 But I have not seen any similar for javascript. 但是我还没有看到任何类似的JavaScript。

Setting text with user input is the safest way. 用用户输入设置文本是最安全的方法。 Instead of creating html strings, create elements instead 与其创建HTML字符串,不如创建元素

Something like: 就像是:

function getMessagesHtml(messages){

  return messages.map(function(o){
    var $div = $('<div>');
    $div.append($('<p>', {text: "Name: " + o.name}));
    $div.append($('<p>', {text: "Message: " + o.message}));
    return $div;
  });

}

Per comments an alternative is create a sanitizing helper function that creates an element that passes the input string as text to the element and returns that text 根据评论,一种替代方法是创建一个清理助手函数,该函数创建一个元素,该元素将输入字符串作为文本传递给该元素并返回该文本

function text(str){
   return $('<div>',{text:str}).text();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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