我用插座做了一个简单的聊天室.如何防止XSS攻击?

I made a simple chat room with sockets.io, how do I prevent XSS attacks?

本文关键字:聊天室 简单 何防止 攻击 XSS 一个 插座      更新时间:2023-09-26

正如标题所说,我用套接字制作了一个简单的聊天室。唯一的问题是,我没有xss保护,而我的伙伴们一直把无限循环作为用户名,所以你可以想象这会变得多么棘手。这是我的app.js

/**
 * Module dependencies.
 */
var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
var io  = require('socket.io').listen(server);
var usernames = {};
io.sockets.on('connection', function (socket) {
  // When the client emits 'sendchat' this listens and  executes
  socket.on('sendchat', function(data) {
    io.sockets.emit('updatechat', socket.username, data);
  });
  // When the client emites 'adduser' this listens and executes
  socket.on('adduser', function(username) {
    // Store the username in the socket session for this client
    socket.username = username;
    // add the client's username to the global list
    usernames[username] = username;
    // echo to the client they've connected
    socket.emit('updatechat', 'SERVER', 'you have connected');
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
    // update the list of users in chat, client-side
    io.sockets.emit('updateusers', usernames);
  });
  socket.on('disconnect', function() {
    // remove the username from global usernames list
    delete usernames[socket.username];
    // update list of users in chat, client-side
    io.sockets.emit('updateusers', usernames);
    // echo globally that the client has left
    socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
  });
});

我如何清理他们的输入来防止这种事情,我试着谷歌XSS保护预防,清理html输入,和其他东西,但我什么也找不到!

客户机代码:

socket.on('updatechat', function(username, data) {
  $('#conversation').append('<b>'+username+ ':</b>' + data.replace() + '<br>');
});

正如我在评论中提到的,不要从服务器发送整个消息。你在浪费带宽,并且把你的表示层和你的服务器混在一起,这将使以后的事情变得非常麻烦。

用用户名发送一些更有用的东西,比如userDisconnected,而不是这个updatechat。让客户端代码显示客户端已断开连接的消息。

现在,为您的客户端做这样的事情:

socket.on('userDisconnected', function(username, data) {
  $('#conversation').append(
    $('<span>').addClass('serverMessage').text(username + ' has disconnected'),
  );
});

这里的关键是您使用$.text()来设置innerText。