I'm making a webpage based around players being able to invite other players to parties, and other things a long the lines.
I have your basic send / receive / update of the chat/users in your party. The only thing is, what's to stop somebody from sitting there opening up a developer console and going
socket.emit('updateUsers', 'Weiner');
socket.emit('updateUsers', 'Idiot');
socket.emit('updateUsers', 'Bad word');
socket.emit('updateUsers', 'Other stupid malicious really long spam the chat name');
How can I prevent against this so that they can not do such things?
(Full JS Stack, Node.js) Thanks!
I faced this problem aswell, This was my solution as far as spamming emits go (malicious socket use)..
basically binds to all emits and checks if the emit name is contained in
spamCheckFunctions
if it is it will add a spam point, if a user exceeds a spam score amount (maxSpam
); he will be disconnected. And for every milliseconds defined atantiSpam
will minus the user spam score defined atantiSpamRemove
I'm sure there are cleaner solutions but this one worked out pretty good for me :)
Just make sure to verify/authenticate the users.
this is how I authenticate them (not using nodejs as a webserver, but had django):
now you can access
socket.handshake.cookie['sessionid']
(in my case this worked with django) then match thesocket.handshake.cookie['sessionid']
with a entry where your sessions are stored on the webserverUse rate-limiter-flexible package for limiting number of events per second. Limiting by IP is the most simple, but would be better to limit by userId if possible.
Read more in official docs
A way to prevent spam is to either implement user authentication and/or a packet rate limiter. Add a middleware function which keeps track of the socketId and the amount of packets being sent through that socket. When it exceeds your limit disconnect the socket.
You can even add an extra function which keeps track of the IP address of that socket, if an IP address will be disconnected too often due spam you can ban that ip. Add a check on your connection event which IP addresses are allowed.
Use an md5/sha key which behaves like a cookie.
Generate a key for a specific user and send it to the client and always check that incoming requests have the same key
It won't be completely secure since the hacker can always find your key in either the source code or localStorage but try to hide it through obfuscation of your code
That's a difficult problem in general. Two things you could do:
1) Use self-invoking functions on the client side, i.e.
Obviously it is on the client side so this is not really secure. But it's not bad to have such wall.
2) On the server side keep track of the frequency of posting. For example if someone posts 5 times in a second, then you can assume that it is a spam and you could block that socket. It is especially effective if combined with authentication and complex registration (so people will have problem in creating new account).