Tuesday, May 27, 2014

C# 6.0 Language Preview

There’s nothing particularly revolutionary or earth-shattering in C# 6.0. If you compare it to other significant releases, like generics in C# 2.0, LINQ in C# 3.0 or TAP in C# 5.0, C# 6.0 is more of a “dot” release than a major one. (The big news being the compiler has been released as open source.)


1.     Indexed Members and Element Initializers

2.     Auto-Properties with Initializers

3.     Primary Constructors

4.     Static Using Statements

5.     Declaration Expressions

6.     Exception-Handling Improvements


Check below reference for more details.






The above C#-specific are implemented entirely in the compiler, without any dependency on an updated Microsoft .NET Framework or runtime.

This means you can adopt C# 6.0 in your development without having to upgrade the .NET Framework for either development or deployment.

In fact, installing the C# 6.0 compiler from this release involves little more than installing a Visual Studio 2013 extension, which in turn updates the MSBuild target files.



Hope this helps.


Arun Manglick


Monday, May 19, 2014

VS 2013 - Browser Link

Browser Link – SignalR channel between browser and Visual Studio


The new Browser Link feature in VS 2013 lets you run your app within multiple browsers on your dev machine, connect them to Visual Studio, and simultaneously refresh all of them just by clicking a button in the toolbar.


You can connect multiple browsers (including IE, FireFox, Chrome) to your development site, including mobile emulators, and click refresh to refresh all the browsers all at the same time.  This makes it much easier to easily develop/test against multiple browsers in parallel.


Browser Link also exposes Browser Link API  o enable developers to write Browser Link extensions

By enabling developers to take advantage of the Browser Link API, it becomes possible to create very advanced scenarios that crosses boundaries between Visual Studio and any browser that’s connected to it.


Web Essentials takes advantage of the API to create an integrated experience between Visual Studio and the browser’s developer tools, remote controlling mobile emulators and a lot more.



Hope this helps.


Arun Manglick


Monday, May 12, 2014

MVC Non Hacking Techniques

Below are major categories:


1.       Cross-Site Scripting and HTML Injection

2.       Session Hijacking

3.       Cross-Site Request Forgery

4.       SQL Injection

5.       Other MVC Defense:



Cross-Site Scripting and HTML Injection


1.       Razor HTML Encoding using the @ Tag

2.       White List Approach [HTML Agility Pack (]

3.       Request Validation

a.      Request validation sounds more useful than it really is. It does block real attacks, but it also generates a lot of false alarms, which can be frustrating to the user.

b.      The problem is that request validation rejects any data even slightly resembling an HTML tag, and this can include valid data.

c.       For example, request validation would reject a perfectly valid string such as I'm writing C# code with generics, e.g., List<string>, and because we never see the request in the MVC application, we are unable to provide guidance to the user as to how to avoid these errors.


Since the false positives frustrate users too much, this feature is often disabled in production, leaving the application unprotected against this kind of attack.

Two Approach to disable.


1.       Apply the [AllowHtml] attribute to a property in a model class

2.       Apply the [ValidateInput(false)] attribute to a controller


4.       JavaScript String Encoding

a.      We can’t rely on the HTML encoding, and we don’t want to render the user-supplied value without making it safe. Fortunately, there is an alternative, although it is not as elegant as we might hope. The

b.      Ajax helper class, which has a method called JavaScriptStringEncode, which encodes a string so that is safe to display and escapes characters so that JavaScript will understand them.


                <script type="text/javascript">

$(function () {

// The following line is the only one that really matters for this example

var searchTerm = "@Html.Raw(Ajax.JavaScriptStringEncode(Model))";



{ q: searchTerm, v: "1.0" },

function (searchResults) {


$.each(searchResults.responseData.results, function () {









Session Hijacking


5.       IP Address Checks

6.       HttpOnly Flag on Cookies


Response.Cookies.Add(new HttpCookie("MyCookie")


   Value = "my value",

   HttpOnly = true




Cross-Site Request Forgery


Cross-Forgery Attacks are made in two steps:

·          Hacker simply sends a valid form submission to your POST-handling Create/Edit() action method.

·         Your site entertains the request, assuming we are using some kind of cookie-based authentication system and the visitor currently has a valid authentication cookie, and our server will take action on the request as if the victim intended it.


Using below it can be avoided.


7.       Validate the incoming HTTP Referrer header.

a.      When making any HTTP request, most web browsers are configured to send the originating URL in an HTTP header called Referer

b.       If we check it and find it referencing an unexpected third-party domain, we know that it’s a cross-site request.

c.       However, browsers are not required to send this header (for example, most don’t after a META HTTP-EQUIV="refresh" command), and some people disable it to protect their privacy.

d.      Overall, this is a weak solution.


8.       Require some user-specific token to be included in sensitive requests

9.       Combining MVC Framework’s Html.AntiForgeryToken() helper and its [ValidateAntiForgeryToken] filter




a.      To protect a particular HTML form, include Html.AntiForgeryToken() inside the form. Here’s an example:


                @using(Html.BeginForm()) {


                                <!-- rest of form goes here -->



b.      This will render something like the following:


<form action="/UserProfile/Edit" method="post" >

<input name="__RequestVerificationToken" type="hidden" value="B0aG+O+Bi/5..." />

<!-- rest of form goes here -->



c.       At the same time, Html.AntiForgeryToken() will give the visitor a cookie whose name begins with __RequestVerificationToken.

d.      The cookie will contain the same random value as the corresponding hidden field.

e.       This value remains constant throughout the visitor’s browsing session.

f.        Next, we must validate incoming form submissions by adding the [ValidateAntiForgeryToken] attribute to the target action method. Here’s an example:



public ActionResult Edit(string email, string hobby)


   // Rest of code unchanged



g.      [ValidateAntiForgeryToken] is an authorization filter that checks that the incoming request has a Request.Form entry called __RequestVerificationToken.

h.      It checks the request comes with a cookie of the corresponding name, and that their random values match.

i.         If not, it throws an exception (saying “a required anti-forgery token was not supplied or was invalid.”) and blocks the request.


                                The MVC Framework’s antiforgery system has a few other handy features:


o   The antiforgery cookie’s name has a suffix that varies according to the name of your application’s virtual directory. This prevents unrelated applications from accidentally interfering with one another.


o    Html.AntiForgeryToken() accepts optional path and domain parameters; these are standard HTTP cookie parameters that control which URLs are allowed to see the cookie.

For example, unless you specifically set a path value, the antiforgery cookie will be visible to all applications hosted on your domain (for most applications, this behavior is fine).


o   The __RequestVerificationToken hidden field value contains a random component (matching the one in the cookie), but that’s not all.

If the user is logged in, then the hidden field value will also contain their user name (obtainedfrom HttpContext.User.Identity.Name and then encrypted).

[ValidateAntiForgeryToken] checks that this matches the logged-in user. This adds protection in the unlikely scenario where an attacker can somehow write (but not read) cookies on your domain to a victim’s browser and tries to reuse a token generated for a different user



                                This approach to blocking CSRF works well, but you should be aware of a few limitations:

• Legitimate visitors’ browsers must accept cookies. Otherwise, [ValidateAntiForgeryToken] will always deny their form posts.

• It works only with forms submitted as POST requests, not as GET requests.

• It’s easily bypassed if you have any XSS vulnerabilities anywhere on your domain. Any such hole would allow an attacker to read any given victim’s current __RequestVerificationToken value and then use it to forge a valid posting. So, watch out for those XSS holes!



SQL Injection


10.   Defense Using Parameterized Queries


a.      Occurs when code constructs dynamically generate & executes SQL queries(shown in bold).



public ActionResult LogIn(string username, string password) {

string sql = string.Format("SELECT 1 FROM [Users] WHERE Username='{0}' AND Password='{1}'",username, password);


// Assume you have a utility class to perform SQL queries as follows

DataTable results = MyDatabase.ExecuteCommand(new SqlCommand(sql));

if (results.Rows.Count > 0) {

FormsAuthentication.SetAuthCookie(username, false);

return RedirectToAction("Index", "Home");

} else {

TempData["message"] = "Sorry, login failed. Please try again";

return RedirectToAction("LoginPrompt");




b.      It makes no attempt to validate or encode the user-supplied username or password values, so an attacker can easily log in under any account as below.

SELECT 1 FROM [Users] WHERE Username='anyone OR 1=1' AND Password='blah' OR 1=1 --'      

SELECT 1 FROM [Users] WHERE Username='anyone OR 1=1' AND Password='blah' ; DROP TABLE [Users]'



Defense Using Parameterized Queries

c.       The solution is to use SQL Server’s parameterized queries instead of pure dynamic queries.

d.      Stored procedures are one form of parameterized query, but it’s equally valid to send a parameterized query directly from our C# code. Here’s an example:


string query = "SELECT 1 FROM [Users] WHERE Username=@username AND Password=@pwd";

SqlCommand command = new SqlCommand(query);

command.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;

command.Parameters.Add("@pwd", SqlDbType.NVarChar, 50).Value = password;

DataTable results = MyDatabase.ExecuteCommand(command);


e.       This takes parameter values outside the executable structure of the query, neatly bypassing any chance that a cleverly constructed parameter value could be interpreted as executable SQL.


11.   Defense Using ORM


a.      If your data access code is built on almost any object-relational mapping (ORM) tool, such as theEntity Framework , all queries will be sent as parameterized queries.

b.      Unless you do something unusually dangerous—e.g., constructing unparameterized Entity SQL queries dynamically with string concatenations—the SQL injection danger vanishes



Other MVC Defense:


1.       Don’t Expose Action Methods Accidentally

2.       Don’t Allow Model Binding to Change Sensitive Properties



More References:

  - OWASP Zed Attack Proxy (ZAP) - Link



Thanks & Regards,

Arun Manglick,

Project Manager - Forecasting
: 9158041782| 9850901262| Desk Phone: +912040265348 |

- 4,000+ professionals globally.
- USA | Canada | UK | The Netherlands | UAE | India | Singapore | Hong Kong | Japan