Protect Node.js Chat (Avoid XSS)

I am creating a simple little chat with Node.js and socket.io

When a user enters his message, he is broadcast to all other users.

The server sends a message:

io.sockets.emit('fromServerToClient', { "message": message }); 

The client displays it:

 socket.on('fromServerToClient', function (data) { $('#messages').append(data.message + '<br />'); }); 

But when you send something like <script>alert(1);</script> , it runs in every client browser.

This is a serious security flaw, and I want to avoid it as much as possible. I have seen people avoid the characters &, <, > and " , but I don't think that is enough!

How can I be 100% sure that I do not have an XSS vulnerability in chat?

By the way, I always specify the encoding to avoid UTF-7 attacks.

Thank you for your help.

+6
javascript security xss
source share
2 answers

Do not use .html() because it is mainly eval on steroids - it can trigger the interpretation of a good variety of languages.

Text is always interpreted as text:

 $('#messages').append($("<div>", { text: data.message })); 
+8
source share

Itโ€™s best here to do nothing for the server!

Yes, you read it right. The right place for content to โ€œexitโ€ is where it is displayed, in the context in which it is displayed. This is called Filter-In, Escape out.

Thus, in your case, the client must handle the evacuation for you. Funny that jQuery (it looks like you're using) has a method that does this for you: $.fn.text() . Thus, your client code becomes:

 socket.on('fromServerToClient', function (data) { $('#messages').append($('<div></div>').text(data.message)); }); 

I added a div so that each post can be properly formatted ...

But your server side should not have anything to do with this shielding.

Now you can filter out everything that looks like HTML on the server, which will be called Filtering (and either replace it or reject it). But definitely not to avoid it!

+3
source share

All Articles