How can I check for any html <script> tags in C#, plus anything else nasty?

c#, html, regex

Solution

Really you should use white-list validation (i.e. allow only specific examples that you know are safe) rather than trying to detect and remove potentially hazardous input.

One really nice way to do this is to use Markdown rather than just allowing HTML input.

There are OWASP Guidelines for HTML injection.

Problem

A user is allowed to format their html in a textbox. This then gets sent to the backend where it will be validated. Other users may then see this textbox. I want to check for any tags in the backend. I know this can be done with a relatively simple regex. I would just do something like `<\s*?script\s*?>` My issue though is if someone does something like this: ``` <a href="http://example.com" onClick="alert(1);">test</a> ``` This would pass validation. I could also make the regex check for onClick, but I'm sure there are other ways around this. My question: Is there a good way to do this? Am I just going to have to rely on regexes and my own research to figure out how else they could run a script? EDIT I suppose I could create a whitelist of what they can enter. It's primarily meant for formatting text, so `<b>, <i>, <h>` etc. This may or may not be an acceptable solution though, I need to look and see what the actual use case is. I'm hoping there's a different solution to this.

Original source

Related problems