ASP.NET (Server\Passive) XSS Encoding Code Review

When code reviewing ASP.NET MVC application to prevent passive XSS issues (for an example of an active XSS issue see ASP.NET (Client\Active) XSS) there are two areas broadly to consider, what is
1) being submitted and stored in your db in the first place i.e. prevent anything nasty from being stored in the first place
2) being displayed on the screen i.e. be suspicious of anything displayed on the screen

This post is going to look at second part. Which is that everything that you output on the screen from any source (your db, third party systems, query string, input fields) should be treated as suspicious and encoded. The correct approach is to assume that whatever you are displaying is already hacked and is malacious.

You may hear what are the chances of system X being hacked, but this is about habit as well as risk. If you encode everything you display then the next person copying the code will follow the same practises (hopefully) and by default you and other developers in your company will create more secure code.

Encoding – in terms of the output on the screen good practice is as follows

1) Encode everything from your models using the @ symbol in your razor views i.e. @model.Name

2) if @Html.Raw(myString) is used make sure that anything added to the string is encoded. You need to look at how myString is constructed and make sure the user (or another user) has not injected something nasty in to it. i.e. instead of the cs code
myString = myString + user.address;
Use something like
myString = myString + Encoder.HtmlEncode(user.address);

Or ideally just use fixed text (thus you are not reflecting any input from any user either query string, input field or db) i.e.

myString = myString + “The address you have supplied is in the wrong format the correct format is blah blah”

3) Note the @ symbol in your razor views is for html encoding not javascript. Instead use an approach like @Ajax.JavaScriptStringEncode(ViewBag.Message)’ see http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/html-encoding-in-mvc/

4) If using telerik client templates always use #: as oppose to #=
i.e.
.ClientTemplate(@Html.ActionLink(“#:Name#”, “Detail”, “Template”, new {id = “#:TemplateId#”}, null).ToHtmlString());
As oppose to #=
.ClientTemplate(@Html.ActionLink(“#=Name#”, “Detail”, “Template”, new {id = “#=TemplateId#”}, null).ToHtmlString());

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s