Filtering out Javascript injection

1.6k views Asked by At

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?

3

There are 3 answers

0
sucotronic On

There are a lot of tools called html purifiers. You can try this for example.

0
Niet the Dark Absol On

The easy answer is replace(/</g,'&lt;');, 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

0
T.J. Crowder On

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.