1

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 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.