引入XSS的jQuery$.ajax()调用

jQuery $.ajax() call introducing XSS

本文关键字:调用 ajax XSS jQuery 引入      更新时间:2023-09-26

今天我注意到,当我访问我的网站时,它会显示一个alert(1);,并重定向任何访问它的人,所以是其他网站。

我知道这是一个JavaScript漏洞,所以我一次取出一些代码,发现下面的代码是导致该漏洞的原因。

var all_chats = setInterval(function() {
  $.ajax({
    url: './requests/chat.php',
    type: 'POST',
    success: function(chats) {
      $('.chat').html(chats);
    }
  });
}, 1000);

chat.php文件如下:

<?php 
  require '../includes/functions.php';   
?>
<table width='100%' border='0' cellspacing='0' cellpadding='0' class='resultsTable'>
    <thead>
        <tr>
            <td>NAME</td>
            <td>TIME</td>
            <td>CONVERSATION</td>
        </tr>
    </thead>
    <tbody>
    <?php echo getChats(); ?>
    </tbody>
</table>

PHP getChats()函数:

function getChats() {
global $PDO;
    $stm = $PDO->prepare("SELECT * FROM `chats` ORDER BY `cid` DESC LIMIT 100");
        $stm->execute();
            while($Try = $stm->fetchAll()) {
                foreach($Try as $Array) {
                            if(!isset($row_num)) $row_num = 1;
                            $row_class = (++$row_num % 2) ? '' : 'greyRow';
                                echo '<tr class="' . $row_class . '">';
                                echo '<td>' . $Array['uid'] . '</td>';
                                echo '<td>' . time_ago(date('Y-m-d H:i:s', $Array['time'])) . '</td>';
                                echo '<td>' . $Array['message'] . '</td>';
                                echo '</tr>';
                }
            }
}

如果允许用户将其输入作为聊天记录存储在数据库中而不进行编码,则您的代码易受XSS攻击。所以当你调用这个来返回存储的内容时,它是

<?php echo getChats(); ?>

字符串返回到可能包含恶意输入的客户端,此代码将执行它:

$('.chat').html(chats);