CRV2 InputValIntro

Revision as of 10:36, 5 April 2014 by Larry Conklin (Talk | contribs)

Jump to: navigation, search

Review code for input validation

Validation of user input and encode output from users.

All data from users needs to be considered untrusted. Remember one of the top rules of secure coding is “Don’t trust user input”. Always validate user data with the full knowledge of what your application is trying to accomplish.

Regular expressions can be used to validate user input, but the more complicated the regular express are the more chance it is not full proof and is very hard to test.

.Net Request Validation

One solution is to use .Net “Request Validation”. Using request validation is a good start on validating user data and is useful. The downside is too generic and not specific enough to meet all of our requirements to provide full trust of user data.

You can never use request validation for securing your application against cross-site scripting attacks.

The following example shows how to use a static method in the Uri class to determine whether the Uri provided by a user is valid.

var isValidUri = Uri.IsWellFormedUriString(passedUri, UriKind.Absolute);

However, to sufficiently verify the Uri, you should also check to make sure it specifies http or https. The following example uses instance methods to verify that the Uri is valid.

var uriToVerify = new Uri(passedUri);
var isValidUri = uriToVerify.IsWellFormedOriginalString();
var isValidScheme = uriToVerify.Scheme == "http" || uriToVerify.Scheme == "https";

Before rendering user input as HTML or including user input in a SQL query, encode the values to ensure malicious code is not included.

You can HTML encode the value in markup with the <%: %> syntax, as shown below.

<%: userInput %>

Or, in Razor syntax, you can HTML encode with @, as shown below.


The next example shows how to HTML encode a value in code-behind.

var encodedInput = Server.HtmlEncode(userInput);

Data validations checklist for the Code Reviewer.

Data/Input Validation:

  • Ensure that a DV mechanism is present.
  • Ensure all input that can (and will) be modified by a malicious user such as HTTP headers, input fields, hidden fields, drop down lists, and other web components are properly validated.
  • Ensure that the proper length checks on all input exist.
  • Ensure that all fields, cookies, http headers/bodies, and form fields are validated.
  • Ensure that the data is well formed and contains only known good chars if possible.
  • Ensure that the data validation occurs on the server side.
  • Examine where data validation occurs and if a centralized model or decentralized model is used.
  • Ensure there are no backdoors in the data validation model.
  • "Golden Rule: All external input, no matter what it is, is examined and validated.",-and-what-to-do-instead#validation