Thursday, July 30, 2015

Useful Features of C# 6

Last week, I talked about some new features of Visual Studio 2015 here. In today's blog post, I will be discussing some of the new features of C# 6 which I am pretty excited about and will be using in my code soon.

nameof Expression

So many times, we have to use magic strings within our code which essentially map to program elements. For such cases, nameof expression can be pretty useful to access the name of program element.

For example,

public ActionResult Details(int? id)

 /* some code*/

 Employee employee = db.Employees.Find(id);

 System.Diagnostics.Trace.WriteLine(String.Format("The value 

   of variable {0} = {1} is not valid", 

   nameof(id), id));

 /* some code*/

return View(employee);

So by using nameof expression, we don't have to hard code the string id in our trace statement. We can simply use nameof(id). So in future, if we decide to change the name of this variable to something else (right click, Refactor -> Rename), we don't have to worry about updating all our trace statements throughout our code. The nameof expression will use the variable name by itself. This will certainly save us time during refactoring :)

Auto Property Initializers

 Earlier, in order to make a field read-only and set some value to the field, we had to use explicit implementation. We used to set the value of read-only defined backing field and initialize it from within the constructor. Now with C# 6.0 we can assign the value of the property from within their declaration. For example,

public class Employee
        public int EmployeeId { get; set; }

        public string Department { get; } = "Development";


As only get method is exposed, the field becomes read-only. As a result, the underlying backing field automatically becomes read-only. So this makes it more convenient to set the value using auto property initializers.

Null Conditional Operator

This is my favorite one and I think I will be using this the most. So many times, we have lots of null checks throughout our code to avoid null reference exceptions. For example,

            int? myInteger;
            if (myInteger == null)
                return null;
                return myInteger.ToString();

These null checks just pollute our code base and make it look bulky. Now, with the new null conditional operator, we can simply do this:

return myInteger?.ToString();

This will essentially do the same thing as the code above but now it's simply written in 1 line instead of 4 lines. So if myInteger is null, it will return null without throwing any null reference exception. How cool is that?

String Interpolation

I prefer using String.Format for string formatting instead of combining multiple strings using + operator. However, with String.Format() using indexed formatters was somewhat of a pain as my eyes had to go back and forth to see what's the element at zeroth index and first index and so on. As I showed in an example above, String.Format looks like this:

String.Format("The value of variable {0} = {1} is not valid",
 nameof(id), id)

With the new string interpolation feature in C# 6, we can create string expressions that look like a template string containing expressions. The expressions are replaced by their ToString() representations of the expression's result. By using the $ escape character we can simply embed the string name inside curly braces.

System.Diagnostics.Trace.WriteLine($"The value of variable 
{nameof(id)} = {id} is not valid");
In my opinion, it's easier to read and follow an interpolated string.

Exception Filters

With this new feature, you can specify condition along with the catch block. So the exception will be caught only when the condition is met, otherwise it will be skipped.
For example,

string ErrorCode = "1234";
     throw new Exception("User Error");
catch (Exception ex) when (ErrorCode == "5678")
     System.Diagnostics.Trace.WriteLine("Error 5678");
catch (Exception ex) when (ErrorCode == "1234")
     System.Diagnostics.Trace.WriteLine("Error 1234");
catch (Exception ex)
     System.Diagnostics.Trace.WriteLine("Error Unknown");
     System.Diagnostics.Trace.WriteLine("Finally Block");

So as you can see, there are multiple catch blocks here. Since Error Code = 1234 is true, only that catch block gets executed. And finally block gets executed as expected. 


C# is now sharper than ever ;) (This time its not a bad joke...). These new features will certainly make the language easier to use and make developers more efficient.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, July 23, 2015

Useful Debugging Features of Visual Studio 2015

This week Visual Studio 2015 was released. If you haven't laid your hands on it yet, you can  download it from here. I loved some of the debugging features of the new Visual Studio. So I will be discussing some of my favorite ones in this post.

Debugging Features VS2015


This is one of my favorite features. You can view the time elapsed between the current breakpoint and the previous breakpoint.

Perf Tip Visual Studio

In the picture above, we can see that fetching the employees took 1235ms approx.
So if we want to find out the time taken by any code snippet, we don't have to get current time before and get current time after and subtract the two values to get the time taken by the code snippet. We can simply put breakpoints in the Debug mode and find the time taken. This will save us a lot of time when we are looking for performance issues in our application.
Clicking on the Perftip further takes us to the diagnostic data which shows Memory Usage and CPU Usage for the application which is more helpful if we want to dig deeper into the diagnostics.

Lambda Expression Debugging

This is one of the feature which I will be using the most. I use lambda expressions pretty often in my code. Earlier, I was not able to see the results in Watch or Immediate window.
But now, I can see them at both the places.

Lambda Expression Visual Studio 2015

Edit in Debug Mode

Yes, you read correctly that one. When we are at a breakpoint, we can edit the C# code and hit save and continue. We don't have to stop debugging anymore in order to make changes to C# code. Isn't it cool? This will certainly save us time during debugging and fixing code.

References Counts

On top of every class ,property and method we will see the number of references. This feature was available in Visual Studio 2013 Ultimate but now it's available in Visual Studio 2015 Professional too.

Reference Counts Visual Studio

Here, Employee class has 7 references and if source control is set up, it will also show number of authors and changes as well.

Yellow Light Bulb

The new Visual Studio comes with a yellow light bulb which will fill some light in our lives ;) (bad joke :P) . If you click on that, you can get suggestions on what it can do for us. For example, implement Interface with Preview. This feature is similar to the one provided by Resharper already but it's better than that because it shows me the Preview as well. Resharper had only one option: Implement Members whereas Visual Studio allows me to preview as well as implement and a few more options as seen in the snapshot below.

Yellow light Bulb Visual Studio


These are some of the features that I explored so far and really liked. I will be talking about more such features, as I explore them, in future posts.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, July 16, 2015

Access Unauthorized Data By Exploiting Robots.txt

In today's blog post, I will be discussing how to Robots.txt can be luring to an attacker and how we can prevent the attacks posed by this.


Robots.txt is a standard used by websites to inform crawlers and bots about which areas should or should not be scanned. So you can go to any website and visit /robots.txt and it might look something like this:

User-agent: *
Disallow: /*wrappertype=print
Disallow: /*/content/url/
Disallow: /*/content/current/url/
Disallow: /navigation/
Disallow: /error
Disallow: /fragments/
Disallow: /logos/
Disallow: /country-fragment/
Disallow: /admin/password/ 
Disallow: /cgi-bin/
Disallow: /classes/
Disallow: /format/
Disallow: /frames/
Disallow: /db/HELPFILES/
Disallow: /db/MANAGEMENT/
Disallow: /db/SUPPORT/ADVERTS/
Disallow: /db/SUPPORT/AFP/
Disallow: /db/SUPPORT/BSTAR/
Disallow: /db/SUPPORT/DAWN/
Disallow: /db/SUPPORT/DAWSON/
Disallow: /db/SUPPORT/ET/
Disallow: /db/SUPPORT/JAGGED/
Disallow: /db/SUPPORT/SHOP/

So when any crawlers visit the site, they avoid the areas mentioned here.

Such an information is luring to the attacker as it might give them a nice starting point.
As you can see, I see there is a directory called /admin/password. That looks luring. So as an attacker, I will try to go and access the directory directly from my browser and if proper access controls are not in place, I will be able to browse it.
You must be thinking - who will be so stupid to leave it so insecure? Surprisingly, lots of websites do that. And that's where all their passwords are stored :) So the attacker can simply browse to the directory and view or download all the passwords.

Another neat little trick that might help with the directory traversal is as follows:

Try /admin/password. If it doesn't work, try /admin/password/randomNumber&Text/../

The "/../" takes you one directory up. If the website is insecure you might be able to access /admin/password now.

How to Prevent

Having proper access controls for each and every area of your website is a must. For example, a proper admin access for especially sensitive information should be explicitly placed.


So in today's blog post, we saw how robots.txt file can be luring to the attacker and how having proper access controls is a must for a website to be more secure.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, July 9, 2015

Cross Site Request Forgery in Single Page Applications

Cross Site Request Forgery in Single Page Applications

Recently, I presented security in MVC Applications at SoCal Code Camp. There I talked about Cross-Site Request Forgery Attack as I have discussed in previous blog post here.
As everybody is moving to Single Page Applications (SPA) these days, somebody in the audience asked me about how to prevent CSRF attack in SPA application. So today's blog post is dedicated to understand how to prevent a CSRF attack in SPA application.

Setting up SPA Application

In my example, I have created a simple SPA application using ASP.NET MVC and AngularJS. I am simply retrieving an employee record and allowing the user to edit and save it into the database.

Clicking on the save button simply makes the POST Request:

$scope.saveEmployee = function () {

$'/api/employee', {

 'employeeId': $scope.employeeId, 'Name': $,
 'department': $scope.department, 
 'division': $scope.division


    .success(function (data, status, headers, config) {

 }).error(function (data, status, headers, config) {



The POST Request passes all the data like employeeId, Name, Department and Division to the EmployeeController.cs POST Action method which saves it to the database.

The POST Request requires user to be authenticated and have the valid session. So any unauthorized user can't edit Employee records without being authenticated. So we are safe there.

Now imagine a user is authenticated and he opens another tab and visits another website in same browser which tries to submit a similar POST request with bad data. Since his session is valid, the request will go through. So the victim has been fooled into some unwanted action without his knowledge.

In case of regular MVC applications, we can simply add AntiforgeryToken to our razor view and decorate our action method with [ValidateAntiForgeryToken] and that will prevent us from such cross site request forgery attacks. However, in case of SPA everything is happening on AJAX requests. So we need to add our antiforgery tokens to our POST request explicitly.

Anti-forgery Token in SPA

In order to use the token in our POST request, we need to add it to our view first. So I created a hidden field on my View:

<input id="antiForgerySpaToken" 
"antiForgerySpaToken='@GetSpaAntiforgeryToken()'" />

In .NET we have this method AntiForgery.GetTokens() to generate the tokens for us. So I added a javascript function which gets the tokens from server and adds it to the View.


public string GetSpaAntiforgeryToken()


   string cookieToken, formToken;

   AntiForgery.GetTokens(null, out cookieToken, 
      out formToken);

   return cookieToken + ":" + formToken;




So this will get the Antiforgery tokens from the server and put it on the page.

Now on every POST request we will be submitting the token for verification. So we add the token to the header like this:

 $scope.saveEmployee = function () {

    $'/api/employee', {

    'employeeId': $scope.employeeId, 

    'Name': $,

    'department': $scope.department, 

    'division': $scope.division

}, {headers: { 'RequestVerificationSpaToken': 
$scope.antiForgerySpaToken }})

    .success(function (data, status, headers, config) {

}).error(function (data, status, headers, config) {



So now the token is being passed in the request header. At the server side we need to verify whether the token is authentic or not.

In Web API, all the HTTP Requests pass through various handlers before they reach the controller. I created a Delegating Handler which verifies whether the token is correct or not.
If the token is not correct, we know that the request is not valid.

public class AntiForgerySpaTokenHandler : DelegatingHandler


private string SpaTokenName = "RequestVerificationSpaToken";

protected override async Task<HttpResponseMessage> 
   SendAsync(HttpRequestMessage request,

     CancellationToken cancellationToken)


     if (request.Method != HttpMethod.Get)




             IEnumerable<string> vals;

             if (request.Headers.TryGetValues(SpaTokenName,
               out vals))


                 var cookieToken = String.Empty;

                 var formToken = String.Empty;

                 var tokens = vals.First().Split(':');

                  if (tokens.Length == 2)


                     cookieToken = tokens[0].Trim();

                      formToken = tokens[1].Trim();


                 AntiForgery.Validate(cookieToken, formToken);



     catch (Exception e)


      return request.CreateResponse(HttpStatusCode.Forbidden);



    return await base.SendAsync(request, cancellationToken);



We need to add this handler to the MessageHandlers List. So In WebApiConfig.cs, I added:

config.MessageHandlers.Add(new AntiForgerySpaTokenHandler());

So here if the tokens do not match, the Handler prevents the request from being propagated to Controller and sends a Forbidden response.
So now if the attacker tries to send the POST request, it will not have the valid tokens atleast and that will prevent us from CSRF attacks.


So we saw how CSRF is a different beast in SPAs. In future, hopefully .NET will make this easier to implement. But until then we need to explicitly take care of this.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, July 2, 2015

Framework Information in Response Header

In today's blog post we will be discussing how framework version information is easily available to see on so many websites and how it can be luring to the attacker. We will also discuss how we can avoid leaking out such information.

Framework Information

Recently, I got to know about shodan - world's most dangerous search engine. Being an attacker's best friend, it helps find websites with vulnerabilities which are easier to hack.
There are many ways that the attacker can get information about the server and framework that your website is currently running on. Some of these frameworks have known vulnerabilities. Especially, the older it gets, the more vulnerabilities are known. For example, if your site is running on ASP.NET Version 1.1, its vulnerabilities are known here. This website called cvedetails has lot of information on known vulnerabilities and exploits.

In our ASP.NET web application, such information is visible in the response headers. If we look at our application and open up the Http Request for the webpage, we can see them like this:

Response Headers Visible in ASP.NET

So its telling me that the site is running on ASP.NET Version 4.0.30319 along with MVC Version.
Such type of information can be luring to the attacker and should be avoided from being sent out.
Imagine if it was some really old version with some known vulnerabilities which the hacker can easily use to his advantage.
I am not saying that hiding this information from response headers will prevent hacker from ever finding out that information or it will make our application safe from those attacks to which our framework is vulnerable. There might be other places where this information is being leaked out or hacker is able to figure these things out. But my point is, we are making it difficult for the attacker to find this information and security is all about decreasing the probability of getting hacked. By hiding such information, we are just adding another layer of protection.

In order to hide these response headers in ASP.NET MVC application, we need to follow these steps:

i) To remove X-AspNet-Version add this to web. config:

  <httpRuntime enableVersionHeader="false" />

ii) To remove X-Powered-By add this to web.config:



        <remove name="X-Powered-By" />



iii) To remove X-AspNetMvc-Version, in Global.asax.cs in Application_Start() method, add this line:

MvcHandler.DisableMvcResponseHeader = true;

By using these, now my response headers look like this:

Response Headers Hidden in ASP.NET


So we saw how exposing such information can be harmful and how we can prevent that in our ASP.NET MVC application.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)