我用socket.io创建了一个简单的聊天室,如何防止XSS攻击?

时间:2013-05-12 22:13:05

标签: javascript node.js socket.io

正如标题所说,我用sockets.io创建了一个简单的聊天室,唯一的问题是我没有xss保护,而且我的好友继续将无限循环作为用户名,所以你可以想象它是如何得到的:P。这是我的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>');
});

1 个答案:

答案 0 :(得分:2)

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

而不是updatechat发出,请尝试使用用户名发送更有用的内容,例如userDisconnected。让客户端代码显示客户端已断开连接的消息。

现在,对于您的客户,请执行以下操作:

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

这里的关键是你使用$.text()来设置innerText。 HTML变得无关紧要。