2

I have some text entry fields on a form and I want to prevent the user from submitting any HTML content, thus reducing chances of XSS attacks or just breaking the layout.

Is there any standard way to do this check with Fluent Validation or do I need to roll my own using a Regex. I'd prefer to use a tried and tested method rather than write my own and risk missing something subtle.

I'm using it with .Net6 and ASP.Net for Web APIs. We intend to update to .Net7 in the next few months so anything that brings could be useful.

Mog0
  • 1,689
  • 1
  • 16
  • 40
  • Maybe I'd try to parse it as HTML. If it has anything more than one single plain text node then it's bad, no? – Fildor Dec 12 '22 at 14:38
  • ^^ Just tried to fiddle something. Doesn't work particularly well. – Fildor Dec 12 '22 at 15:01
  • Second attempt a little better: https://dotnetfiddle.net/PcDma4 but still ... very naive approach, I am afraid. – Fildor Dec 12 '22 at 15:14

1 Answers1

0

My source for all of this is this page.

First of all you would need to replace the & character with &amp; Then replace < with &lt; Finally replace > with &gt;.

You could also surround your html with <pre> tags, so that it preserves line returns and spaces.

SupaMaggie70 b
  • 322
  • 3
  • 8
  • 1
    @Fildor Oops, my bad. On mobile right now so autocorrect. Will change that. – SupaMaggie70 b Dec 12 '22 at 14:44
  • Typos happen ;) – Fildor Dec 12 '22 at 14:45
  • @Fildor Yeah, still glad you caught it though! – SupaMaggie70 b Dec 12 '22 at 14:46
  • This is how to display the content while preventing XSS, which whilst good, I'm wanting to prevent the potentially dangerous content from getting into the database in the first place as an extra layer of protection - we already have encoding on the output but we've been told to prevent it from being input as well. – Mog0 Dec 12 '22 at 14:46
  • @Mog0 My bad, in that case it is a little bit more difficult. My guess would be to check for opening and closing these things <>. If you aren’t using an iframe for each, which you obviously aren’t, checking for the wouldn’t work. I will think about it and let you know if I come up with a better solution. – SupaMaggie70 b Dec 12 '22 at 14:49