11.07.2015 Views

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: Building Secure ASP.NET Pages <strong>and</strong> Controls 269Sanitizing InputSanitizing is about making potentially malicious data safe. It can be helpful when therange of allowable input cannot guarantee that the input is safe. This might includestripping a null from the end of a user-supplied string or escaping values so they aretreated as literals. If you need to sanitize input <strong>and</strong> convert or strip specific inputcharacters, 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 commentfields, see “Sanitizing Free Format Input” under “Cross-Site Scripting,” later in thischapter.Validating HTML ControlsIf you do not use server controls — that is, controls with the runat=“server” attribute— <strong>and</strong> instead use regular HTML controls, you cannot use the ASP.NET validatorcontrols. Instead, you can validate your <strong>Web</strong> pages’ content by using regularexpressions in the Page_Load event h<strong>and</strong>ler, as follows.using System.Text.RegularExpressions;. . .private void Page_Load(object sender, System.EventArgs e){// Note that IsPostBack applies only for// server forms (with runat="server")if ( Request.RequestType == "POST" ) // non-server forms{// Validate the supplied email addressif( !Regex.Match(Request.Form["email"],@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",RegexOptions.None).Success){// Invalid email address}(continued)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!