7

I have an MVC app with a Service layer and I'm trying to figure out how to sanitize all inputs without going insane.

I have validation under control - field-length, data-types, and other validation is being handled both on client and model (EF5).

What I'm now trying to handle is preventing SQL injection and XSS - I was able to break my application by pasting some markup into one of my inputs.

For example:

 <textarea data-bind="value: aboutMe">@Model.AboutMe </textarea>

If I save some script tag in AboutMe:

<script type="text/javascript">alert("hey")</script>

the page breaks due to illegal characters:

  Uncaught SyntaxError: Unexpected token ILLEGAL 

I'm thinking I can just cherry-pick every single input and wrap it in some kind of SanitizeText() function that removes all brackets from anything that's been submitted, but this feel cheap and tedious, and doesn't address SQL injection.

What's the proper way to go about this?

SB2055
  • 12,272
  • 32
  • 97
  • 202

2 Answers2

7

To address issues with XSS etc, you should encode your output properly using e.g. Html encoding - as opposed to your input. You may want to also look at the anti-xss library http://wpl.codeplex.com/releases/view/80289 which includes some excellent classes to help.

To address concerns with SQL injection, you should be using SQL parameters (parameterized queries) http://msdn.microsoft.com/en-us/library/vstudio/bb738521(v=vs.100).aspx alongside appropriate permissions configured in SQL server itself. As you are using EF5 then this will also protect against SQL injection for you, I believe.

geedubb
  • 4,048
  • 4
  • 27
  • 38
  • Unfortunately, the AntiXSS library is quite broken at this point; version 4.2 strips out pretty much *everything*... – Tieson T. Nov 02 '13 at 22:37
  • @Tieson - what do you mean "it strips out". If you use the Encode methods it shouldn't strip anything. It will encode it properly so that XSS is ineffective – geedubb Nov 02 '13 at 22:48
  • 1
    more detailed question posted here in case you have time: http://stackoverflow.com/questions/19747846/sanitizing-input-with-htmlraw-in-mvc4 – SB2055 Nov 02 '13 at 23:02
  • If you use the `GetSafeHtmlFragment` method, it removes every pretty everything from the input string - not exactly useful if you're trying to sanitize input from, say, a WYSIWYG editor. Though I suppose that might work for what the OP wants. I don't think he wants the encoded brackets left in. – Tieson T. Nov 02 '13 at 23:02
  • Pretty sure all ASP.NET Razor Views are HTML Encoded by default. Unless you are explicitly calling `@Html.Raw` you should be ok – Lotok Jan 31 '14 at 11:07
0

If you mean sanitize that the user is not allowed to import html tags, I have to say that asp .net does this by default unless you want to be somewhat safe from XSS. But if you mean form validation This is controlled by @ Html.AntiForgeryToken ()