Play the game at www.RainingChain.com.
Check the source code on Github.

Monday, 9 March 2015

Preventing Socket.io DDOS

Raining Chain HTML5 MMORPG uses Socket io library for websockets. Even though it is a great library to handle websockets, it is very vulnerable to DDOS.

A player could open the console with F12, type
while(true) socket.emit('eventName',bigObject);
and crash your server (or at least slow it down).


This means you need to implement a system to disconnect a player that sends too much data.

On the server, instead of using:

io.on('connection', function (socket) {
 socket.on('eventId', function (data) {
  //stuff   
 });
 socket.on('eventId2', function (data) {
  //stuff2 
 });
});

Use

handleSocket = function(socket,eventId,data){
 if(Date.now() - socket.lastEventTimestamp < 5){
  socket.disconnect(); //optional
  return;
 }
 socket.lastEventTimestamp = Date.now();
 
 if(eventDb[eventId]){
  eventDb[eventId](socket,data);
 }
 
}
eventDb = {
 stuff:function(socket,data){
  //stuff
 }
 stuff2:function(socket,data){
  //stuff2
 }
}

This is the most simple system. One could implement different thresholds for every event and take into consideration the size of the data sent. Instead of disconnecting the socket when sending too fast, one could keep track of how many times it has happened and only disconnect if it happened more than 100 times in the last minute.

1 comment:

  1. Hello,

    I have been trying to implement this, however, it appears that eventId and data, are always undefined. I'm curious if you still use this and how?

    here's how I use it:

    io.on("connection", handleSocket);

    Thanks!

    ReplyDelete