How do you prevent a client from sending a huge websocket packet?

1.2k Views Asked by At

I'm making a webapp that uses WebSockets for communication between the browser and node server.

If you open up the debug console (F12), you can access the socket instance and write to it.

For example, socket.send('packetname', 'data')

What's stopping someone from opening the console and writing something like this?

socket.send(new Array(99999));

All this data being sent to the server can be overwhelming and by the time it gets there, the bandwidth is already used and it's already been processed. Of course there is validation but at that point it's too late and the resources have already been spent processing it.

You also can't just check the length of the array because someone could send an array where the first element is a huge array instead, or anything really. I don't think there's a way to calculate byte size so I guess the best option is stringifying the data to check its size (which is extremely slow)?

All my packets are very small. I am looking for a way of preventing packets over a certain size from being sent to the server. Is this possible?

2

There are 2 best solutions below

0
On

There likely isn't any "best" solution to this. I would just think about things you can implement on the server side to detect if something like this might be happening. As far as stopping a client on the client side, it is difficult or maybe impossible to do that. Your server is designed to accept connections and data, so clients can attempt to exploit this.

One possible solution I can suggest is having an "upper limit" on how much data a client would send in a single operation. I don't know the nature of your application, but perhaps a client sending 2500 bytes of data in a single operation would be completely impossible given the nature of your app.

In this case, if an operation (bytes received) begins exceeding this upper limit, the connection can then be dropped.

This is only one potential solution I can think of, but you will need to come up with something along these lines.

5
On

Unless you have full control over the client (which you don't) you cannot hinder the client to send arbitrary large data to your system. The client would not even need to use a browser so any restrictions inside the browser will not work.

You just have to deal with it, like with disconnecting the client immediately if you get an unexpected amount of data and maybe blacklisting the origin so that the next attack attempt will be stopped earlier.