Friday, March 15, 2013

Whats New in WCF 4.5

In the .NET Framework 4.5, a lot of new features have been added to make it simpler Windows Communication Foundation (WCF) applications:

·         Simplification of generated configuration files
Here in WCF 4.5 the config file become simpler in the sense as instead of showing all the binding whether it is default or not, it will only contains the binding where the value is modified from default to others.

·         Support for Contract-first development
This feature will let you create service reference from WSDL file by using svcutl.exe /serviceContract switch

·         ASP.NET compatibility mode
WCF provides ASP.NET compatibility mode to grant developers full access to the features in the ASP.NET HTTP pipeline when writing WCF services. To use this mode, you must set the aspNetCompatibilityEnabled attribute to true in the  section of web.config. Additionally, any service in this appDomain needs to have the RequirementsMode  property on its AspNetCompatibilityRequirementsAttribute set to Allowed or Required. By defaultAspNetCompatibilityRequirementsAttribute is now set to Allowed

·         Default Transport Values
Some new Default transport values are set like

·         XmlDictionaryReaderQuotas Class Updated
Some values are set to as
MaxArrayLength                   (max int value)
MaxBytesPerRead                  (max int value)
MaxDepth                               (128 Nodes)
MaxNameTableCharCount     (max int value
MaxStringContentLength       (max int value)

·         Validation of WCF config file
Now in the build process WCF configuration files are validated.  List of validation errors or warnings are displayed in Visual Studio if the validation fails.

·         New asynchronous streaming support
Streaming becomes smoother as the sending thread will not block the process and there will be a limitation on the buffer size for sender.

·         New HTTPS protocol
The IIS can now support the HTTPS protocol.

·         Ability to generate metadata in a single WSDL
   The metadata of the service can now be generated in a single file by appending. ?singleWSDL in the URL.

·         Websockets support
Bidirectional communication over port 80 and 443, just like the TCP protocol.

·         Support for configuring services in code
A developer can now configure the file by simply modifying the config file; there is no need to compile the code again.

·         XML Editor tooltips
The XML editor will now provide the tooltip as well for every node element.

·         ChannelFactory Caching support
WCF can cache channel factories while developer is using a WCF client proxy

·         Binary encoder compression support
Binary encoding and the file compression is now supported at the service level as will so there will not be chance of a fault if the client use this but the service does not have.

·         UDP Protocol support
Now the service client can sends a message to a service and there is no need to wait till the response comes.

·         Multiple authentication Support
The Service can now support multiple authentications just like the IIS do in the virtual directory if you are using HTTP transport protocol.

·         IDN Support
WCF can now support International Domain Name as well.

Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM

Thursday, March 7, 2013

AntiForgeryToken in MVC

Security in any application is as important as the UI of the application, we can compromise with the UI but we cannot do the same with Security as it possess a great risk to the data we use inside the application. The common security breach can come in the form of Cross Site Request Forgery or CSRF hack. CSRF is the lesser known cousin of XSS.  It is different from another script hacking called as Cross Site scripting XSS.

What is Cross Site Scripting?
XSS is one of the most common application-layer web attacks. XSS commonly targets scripts embedded in a page which are executed on the client-side (in user’s web browser) rather than on the server-side. The concept of XSS is to manipulate client-side scripts of a web application to execute in the manner desired by the malicious user. Such a manipulation can embed a script in a page which can be executed every time the page is loaded, or whenever an associated event is performed.

What is Cross Site Request Forgery?
Cross Site Request forgery also called One Click Attack or Session Riding is a type of a hack where the some unwanted and unauthorized command given by a hacker from a user which is trusted by the web site is executed on server and exploits the trust. It first came in light early at 2001. The attack works by including a link or script in a page that accesses a site to which the user is known (or is supposed) to have been authenticated

How does it work?

Here the hacker inserts some script or link in the code within the browser where the user is using its application or an authenticated one. For example a banking user presented with a link which is redirect the user to some other website with some link rather than the actual bank site. In this way, the attacker can make the victim perform actions that they didn't intend to, such as logout, purchase item, change account information, retrieve account information, or any other function provided by the vulnerable website.

Let’s take a sample MVC web site the site properly blocks anonymous users from taking any action. You can see that in the code for the controller:

public class HomeController : Controller
  //...ur code
Here we use the AuthorizeAttribute on the controller (without specifying any roles) to specify that all actions of this controller require the user to be authentication.

The hackers create the page same as our own page and put some Java script on the page load itself so that the value of the page can be submitted to some false address. The Hacker can create a page like.

    <form name="badform" method="post"
        <input type="hidden" name="FinalAccountId" value="2" />
        <input type="hidden" name="amount" value="1000" />
    <script type="text/javascript">

The hacker created an HTML page that replicates the fields in bank transfer form as hidden inputs and then runs some JavaScript to submit the form. The form has its action set to post to the bank’s URL.

When the user lands in this page which looks exactly the same as the original one, When the unsuspecting bank user visited the hackers website, it recreated a form post to transfer funds, and the browser unwittingly sent the still active session cookie containing the user’s authentication information to the hackers site thus the page will be executed and we will lost our information.

Prevention in MVC

The first step to avoid this is to add the ValidateAntiForgeryTokenAttribute to the action method. This will validate the “token” value created at the time of session start and will be different for each session for each browser.

public ActionResult Transfer(int destinationAccountId, double amount) {
  ///... Ur code

The same we need to add in our View as well, for example a method Html.AntiForgeryToken() 

<% using (Html.BeginForm("Transfer", "Home")) { %>
    <label for="Amount">Amount:</legend>
    <%= Html.TextBox("Amount")%>
    <label for="destinationAccountId">
      Destination Account:
    <%= Html.DropDownList("destinationAccountId", "Select an Account") %>
    <%= Html.AntiForgeryToken() %>
    <input type="submit" value="transfer" />
<% } %>

By adding this the page will get loaded with some encrypted token value which we can see by view source as for example

<input name="__RequestVerificationToken" 
  value="WaE634+3jjeuJFgcVB7FMKNzOxKrPq/WwQmU7iqD7PxyTtf8H8M3hre+VUZY1Hxf" />

This is the most common way  to prevent Cross-Site Request Forgery (CSRF) attacks is to append unpredictable challenge tokens to each request and associate them with the user’s session. Such tokens should at a minimum be unique per user session, but can also be unique per request. By including a challenge token with each request, the developer can ensure that the request is valid and not coming from another source other than the user. This token value cannot be predicted so it will make each request a unique one.

Token In Ajax Call

The same prevention we can add in the Ajax call as well so that the threat can be minimize we can verify the token in the Ajax call by using the jQuery cookie plugin to replace getCookie:

var csrftoken = $.cookie('csrftoken');

Hopefully you have like this post and will try to implement the same in all your important development. Please do share your valuable comment on the same article.

Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM