Sanitizing Input in ASP.NET MVC Application

11,449

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.

Share:
11,449
SB2055
Author by

SB2055

Updated on July 10, 2022

Comments

  • SB2055
    SB2055 almost 2 years

    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?