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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 10: Building Secure ASP.NET Pages <strong>and</strong> Controls 273Use the following countermeasures to prevent XSS attacks:●●Validate inputEncode outputValidate InputValidate any input that is received from outside your application’s trust boundary fortype, length, format, <strong>and</strong> range using the various techniques described previously inthis chapter.Encode OutputIf you write text output to a <strong>Web</strong> page <strong>and</strong> you do not know with absolute certaintythat the text does not contain HTML special characters (such as , <strong>and</strong> &), thenmake sure to pre-process it using the HttpUtility.HtmlEncode method. Do this evenif the text came from user input, a database, or a local file. Similarly, useHttpUtility.UrlEncode to encode URL strings.The HtmlEncode method replaces characters that have special meaning in HTML toHTML variables that represent those characters. For example, < is replaced with &lt<strong>and</strong> " is replaced with &quot. Encoded data does not cause the browser to executecode. Instead, the data is rendered as harmless HTML.Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));Data-Bound ControlsData-bound <strong>Web</strong> controls do not encode output. The only control that encodes outputis the TextBox control when its TextMode property is set to MultiLine. If you bindany other control to data that has malicious XSS code, the code will be executed onthe client. As a result, if you retrieve data from a database <strong>and</strong> you cannot be certainthat the data is valid (perhaps because it is a database that is shared with otherapplications), encode the data before you pass it back to the client.Sanitizing Free Format InputIf your <strong>Web</strong> page includes a free-format text box, such as a “comments” field, inwhich you want to permit certain safe HTML elements such as <strong>and</strong> , you canh<strong>and</strong>le this safely by first pre-processing with HtmlEncode, <strong>and</strong> then selectivelyremoving the encoding on the permitted elements, as follows:StringBuilder sb = new StringBuilder( HttpUtility.HtmlEncode(userInput) ) ;sb.Replace("&lt;b&gt;", "");sb.Replace("&lt;/b&gt;", "");sb.Replace("&lt;i&gt;", "");sb.Replace("&lt;/i&gt;", "");Response.Write(sb.ToString());

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

Saved successfully!

Ooh no, something went wrong!