Sanitize Input

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

Sanitizing is about making potentially malicious data safe. It can be helpful when the range of allowable input cannot guarantee that the input is safe. This might include stripping a null from the end of a user-supplied string or escaping values so they are treated as literals. If you need to sanitize input and convert or strip specific input characters, use Regex.Replace.

Note Use this approach for defense in depth. Always start by constraining input to the set of known "good" values.

The following code strips out a range of potentially unsafe characters, including < > \ " ' % ; ( ) &.

private string SanitizeInput(string input)
{
 Regex badCharReplace = new Regex(@"([<>""'%;()&])");
 string goodChars = badCharReplace.Replace(input, "");
 return goodChars;
}

For more information about sanitizing free format input fields, such as comment fields, see "Sanitizing Free Format Input" under "Cross-Site Scripting," at http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh10.asp?frame=true#c10618429_007

References

Personal tools