Reputation: 63299
I am doing a chat room website, currently the user can input anything they like to the entry box and send it to all online users. But I am afraid it's not safe, once there are some bad guys sending malicious html/javascript code to break all the other users?
How to avoid that happen?
Upvotes: 0
Views: 192
Reputation: 40139
What everyone said already is right; you need to encode all of that data before sending it to the users.
I just wanted to add, though: be sure you do this encoding on the server, with a built-in (and therefore, well-tested) method provided by the web framework you are using.
Do not try to do this in JavaScript on the client; there are further malicious codes that users could enter which would break that JavaScript itself.
And, do not try to 'roll your own' encoding mechanism, nor try to use a black list approach, where you try to locate only certain "bad" things someone could enter, and replace them. You'll never guess what all the 'bad things' are.
You don't mention your web framework, but most have a built-in functionality that HTML Encodes an entire string so that the string will be displayed literally in the browser, no matter what content is in it.
Upvotes: 2
Reputation:
If you are using PHP, you can use strip_tags() which will remove any tags you specify but still allow some HTML if you so choose to allow it.
Upvotes: 1
Reputation: 1073978
Make sure you encode all content you send, which you want to do anyway. For instance, if the user types <
, you probably want it to show up as <
rather than starting an HTML tag. So if ouputting that output to be in an HTML page, you need to escape it as <
. This has the wonderful effect of preventing people typing in HTML tags (and if they can't send HTML, it'll be tricky to send a script
tag).
The bare minimum you need to encode even just to have the output be correct (much less to protect against malicious output) is <
=> <
and &
=> &
. I always also do >
=> >
as well just for thoroughness, and because I can't help thinking someday, somehow, it's going to matter. :-)
Upvotes: 1
Reputation: 137108
One way could be to convert all the HTML to opcodes. So rather than send <
you send <
etc.
This way the code will be displayed as it was typed, but shouldn't execute.
Upvotes: 1