Reputation: 31
I have a textarea in which I have put validation code not to allow <script>
tags and Javascript tags, but the user can enter descriptions like <strong onmouseover=alert(2)>
.
So when someone hovers over this string tag JS alert box shows up.
How can I stop this kind of javascript injection?
Upvotes: 1
Views: 1747
Reputation: 1073968
You'll need to properly sanitize the HTML you allow. This is non-trivial, as you've discovered. (You probably need to disallow iframe
and several other elements.)
Proper sanitizing requires a whitelist of elements, and within those a whitelist of attributes allowed on each. Obviously the various onXyz
attributes would not be on the whitelist.
Sanitizing must happen server-side, because anything client-side can be bypassed. So without knowing what server technology you're using, one can't recommend something. For instance, JSoup is a well-known one for Java, but of course, that's not useful to you if you aren't using Java. :-) For .Net, there's the HTML Agility Pack or the Microsoft Anti-XSS library, but this is a very incomplete list.
Upvotes: 1
Reputation: 324600
The easy answer is replace(/</g,'<');
, but of course that prevents any HTML from being used. This is why BBCode, Markdown and other such languages exist: to provide formatting features without granting the user permission to post arbitrary code.
Alternatively, just search for things of the pattern /\bon[a-z]+=/i
Upvotes: 0
Reputation: 1504
There are a lot of tools called html purifiers. You can try this for example.
Upvotes: 0