Any reason not to trust ASP.NET AntiForgeryToken? - asp.net-mvc

I know that Stack Exchange sites do not use the ASP.NET MVC built-in #Html.AntiForgeryToken() for the prevention of XSRF/CSRF attacks. Instead of creating a hidden input named __RequestVerificationToken with a really long value based on the machineKey section of the web.config, the Stack Exchange method creates an input named fkey with a MUCH more succinct value. This is apparently a Guid, and based on evidence from the Stack Exchange Data Explorer project on Google Code, this value is tied to each individual user, remaining fairly constant until you log in or out.
Also, the Stack Exchange value is constant on a page, and is made available to client script, so that Ajax posts for voting and things like that also use the token. By contrast
So why does Stack Exchange march to its own drummer?
Is there a reason not to trust AntiForgeryToken?
Does the AntiForgeryToken have some limitations that the Stack Exchange team was unwilling to accept? If so what were they?
Or maybe AntiForgeryToken just wasn't around (it started life in the MVC Futures project) when Stack Overflow was started, and if they had it to do over from scratch today they would use AntiForgeryToken?
I've been unable to find any blog posts from Jeff or others on the Stack Exchange team to explain the guiding principles behind how the XSRF-prevention policy on the SE network. It would be really nice if one of them could do a write-up, assuming of course that it could be done in general terms without creating a vulnerability. It would be really valuable information for those of us that want to make our websites secure, but aren't entirely comfortable just blindly trusting Microsoft to do it for us.

The one limitation we ran into with the default implementation was the lack of out-of-the-box support for AJAX calls. The hidden field approach works for sites that primarily deal with traditional form POSTs; but, not quite for AJAX heavy sites like SO.
We implemented the approach outlined in this CodeThinked blog post and we couldn't be happier. It looks like Phil Haack also supports this approach, based on his oct 2011 blog post
Couple of (unsolicited, I know!) pointers:
if you are running a web-farm, you should, of course use a static machinekey in your Web.config
Make sure all your servers have this KB installed. Otherwise, you may run into machinekey validation issues

Related

Confused about protecting against XSS and which tools to use

VS2013, MVC, VB
I'm asking this question now because much time has passed since most of the posts that I read about XSS protection.
In the spirit of SO, my technical question is if someone can confirm that Microsoft's HtmlAgilityPack does not really do what AntiXSS does. I've read posts where people suggested that AntiXSS has problems, so they used htmlAgilityPack, but then the posts, including on SO, that state clearly they are not the same tool. That AntiXSS is what one would use for XSS protection.
If someone could clarify that I'd appreciate it.
A second, and not intended to be asking an opinion question per se, is to ask if the problems previously claimed against AntiXSS are by and large solved and is that the right tool to use for XSS protection when using MVC.
My intent is to use a whitelist approach for XSS protection.
Followed the guidance from this post as a basis for coding a whitelist filter using the html agility pack. The link shows a function used in a web pages approach, but the basic algorithm works fine coded in the controller of an MVC project to sanitize input from an RTF/WSIWYG editor (CKEditor)

Current status of Upshot.js

I am thinking of using upshot.js along with Knockout in one of my very important projects. I do not see any documentation or any activity around upshot. Before I commit to this decision, is this project still active?
If the entire asp.net stack is now open and one can see what is getting committed to repository, why this small library is still not on codeplex or github for community to see?
I hope this is still on radar of asp.net team.
According to this blog post, Upshot is officially dead:
http://www.riaservicesblog.net/Blog/post/WCF-RIA-Services-is-Dead-Long-Live-WCF-RIA-Services.aspx
The author points to BreezeJS as an alternative:
http://www.breezejs.com
Upshot is officially dead.
"Earlier this year the Beta version of Visual Studio 2012 included a template that was designed for building “single page applications” using Upshot.js and a special Web API-based DataController that provided support for insert, update, and delete operations using the unit of work pattern with transaction support. We are not currently continuing work on that template or Upshot.js. We want to first focus on improving the development experience with existing popular JavaScript libraries and in future versions we will revisit this decision and see if additional libraries are needed to round out the SPA experience."
http://aspnetwebstack.codeplex.com/wikipage?title=Roadmap
Give a shot to JayData at http://jaydata.org, it has JavaScript Language Query and JavaScript CRUD capabilities with change tracking, batches and a lot more. What it offers over BreezeJS is its provider agnostic architecture and a number of providers that you can use out of the box: OData, webSQL, IndexedDB, localStore, Facebook and YQL.
JayData plays nicely with NodeJS and let you consume OData from a JavaScript based middletier.
Also you can use JayData not only to consume but also to provide OData if you are using it on the server side with NodeJS and mongoDB.
The ASP.NET team haven't finished the official release of ASP.NET SPA in time to ship with the final ASP.NET MVC 4 release but they are still working on it.
You can find the source code for ASP.NET SPA and follow the development effort on the ASP.NET CodePlex site:
ASP.NET SPA Source Code (to look at the upshot stuff click Browse and expand src/SPA/upshot
ASP.NET SPA Discussions
The general lack of documentation is caused by the fact that there haven't be an official release yet.
Speaking for my company - we used exactly the same combination (Knockout + Upshot) and after sweating a lot of blood, we decided to get rid of Upshot and replace it with JQuery's ajax calls. Much more transparent and much more bugfree. However, much more code, too.
Back in February the authors of Upshot promised they would put documentation on in a week or so and since then I've heard nothing of them. If you want my opinion, I think this project has already been buried or indefinitely postponed.
Accodding to what is said on the discussions(see http://aspnetwebstack.codeplex.com/discussions/topics/5321/asp-net-single-page-application) on SPA, the whole SPA strategy would change, so I think the final version o SPA or whatever will replace it will be quite different from the actual bits...so I don't know if it is a good move continuing using the actual version...that at my bets knowledge is not compatible with Mvc 4 RTM.
I am the author of the Mvc Controls Toolkit there we implemented some js functions to help querying OData, and to update entitiess that are on the client side. They handle validation errors(both client side and server side), return to client principal keys created on the server, do changes tracking (to send to the server just changed entities) and allows undoing changes done on the client side. They handle also one to many relations. Moreover, updates are handled not only with WebApi controllers but also with normal controllers.
Give a look to this first tutorial: http://dotnet-programming.com/post/2012/04/03/Mvc-Controls-Toolkit-Support-to-Mvc4-WebApi.aspx
and then refer to the other tutorilas linked.

Pen testing your MVC application

Here are some the commonly known practices for securing an MVC application:
Encode your output
Parameterize your SQL
Test your search backwards and forward
1 way hash passwords
Lock out accounts or limit login attempts
Use code based impersonation when accessing the file system
Access SQL with a locked down username
Use Honey-pots or captchas for form submissions to counter bots
If there are any I missed or misstated please feel free to contribute.
What other techniques/best practices do you use or think about when pen testing your own software. What do you do to "kick the tires" before taking a applications live.
What pen testing services or software do you use if any?
All methods that use modelbinding should be secured with whitelists or blacklists on bindable properties.
string[] allowedProperties = new[]{ "Title", "Description"};
UpdateModel(myObject, allowedProperties);
or
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include="Title,Description")] MyObject object )
{
}
This is of course to prevent crafted requests from attempting to update/manipulate your objects in ways that weren't intended.
Your list is good, although it is a bit vague. For instance md4 is a one way hash, but its extremely insecure as i can generate a collision on my desktop in less than a day. sha256 with a large salt value is a more secure approach. (I know even this is description incomplete, don't flame)
There is never a catch all security check list that will work across the board. Specific applications can have specific vulnerabilities. Sometimes these flaws can be logic errors that really don't have a classification.
The OWASP Top 10 web application vulnerabilities is an excellent resource that you should study. Most notably you are missing XSRF on your list which can be a devastating attack. There are a large number of "sink" based attacks which you have not listed. For instance what if an attacker could pass in a path of his choice to fopen? A Study In Scarlet goes over many of these attacks against PHP.
All of your suggestions apply to any web application, not just MVC applications.
An MVC-specific suggestions would be something like "skinny controllers, fat models".

Securing an ASP.Net MVC Site

As a relative newcomer to both web and MVC, I am looking for a good summary of security best practices that I should implement.
The site will be public facing with "moderately sensitive data" (meaning we can't get sued, but probably wouldn't make many friends if the data got out!) and will have the following security steps taken:
a: Forms/membership authentication and authorization
b: Parameterized queries to prevent sql injection.
c: Automatic timeout with x min of inactivity
c: SSL for client to server encryption
What else do you recommend?
*Securing IIS and the network don't fall under my domain, so I'm more interested in the things I need to do to the software.
If you are using cookies to recognize users, be sure to use an arbitrary token (such as a GUID) to store on the client for identification. I've seen too many websites that store my email address or username in my cookie... just have to change it to another!
Write your software so that it can run under medium trust.
If you are new to web development you should be aware of cross site scripting (XSS). You can use Http.Encode helper method to protect against this in ASP.NET MVC.
Make sure you prevent out of order requests. Ensure client is authenticated before allowing to see sensitive data, or in some cases, make sure the client has come through the correct channel, before allowing a data manipulation. For example, only allow adding an item to your cart if the request came from the product details page. If you don't check, any one can mess around with the action. The URL would be like http://server/cart/add/XYZ123 and anyone could just tweak the 'id' parameter.
Here's another biggie to watch out for: CSRF
http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/
Take a look at this post by Phil Haack- one of the MS dev’s involved in the development.
Additionally take a look at Microsoft Anti-Cross Site Scripting Library to filter out all incoming parameters
Maybe you should choose methods that can be invoke from outside or not. For example be careful make a method like delete any tables like http://yourhost.com/edit/deletealltable.
Make sure you design your class and methods well. And give attributes [NonAction] for preventing public method being invoke.
Make sure you display data (especially sensitive) as you need with minimum fancy design and use client script as long as needed.
Remove any unused trash files like unused files in your solution folder.
Check and double check and validate any input control like textbox. I just can give something in the textbox to hack your system.
If you use mix between MVC and regular ASP.NET, please remove any dependency between them.
Be sure you cover the basics thoroughly, independently of ASP.NET. Make sure your DBMS has a separate user with the minimal required privileges (e.g., CRUD and executing sprocs from specified databases) set up to access the database from the web application. Parameterizing queries is an excellent idea, but ALWAYS SCRUB YOUR INPUT ANYWAY: it is not a complete defense against sql injection.
Keep your design clean and easy to understand. Document whatever you do clearly, especially on the database side. It would be very bad if all your good work were destroyed by two programmers months or years later--one who didn't realize, say, that the database user for the web application (now accessing a database on a different server) shouldn't have root privileges, and another who added a control that didn't cleanse input properly. There's only so much that can be done about this sort of thing, but designing for the possibility that fools will be maintaining your code isn't so that coders will think you're sweet--it's so that fools won't put you out of business.

Is ASP.NET webforms swept under the rug to make room for mvc?

I've read all the marketing speak about how mvc and webforms are complementary etc...
However it seems that all the blogs talk about is mvc and the only news coming out is about mvc.
Is Microsoft going to continue to IMPROVE webforms as a first class citizen or will it just be a supported technology as they move all their real efforts, developers and resources to mvc over time?
Is there any real evidence of any new exciting improvements coming to webforms in the near future?
You could do worse than take a look at Phil Haak's post from November:
The Future of WebForms and ASP.NET MVC
He points out 5 key things anounced under ASP.NET at PDC last year:
Core Infrastructure including scale and performance
Web Forms including issues with Client IDs, ViewState, CSS use, etc
AJAX
Data and Dynamic Data
MVC
Coupled with that, there are things that have been built as part of ASP.NET MVC that have already been released for webforms like the Routing module which is going to be great help in some of my projects, even without using MVC.
On top of those, there are also a number of changes coming in VS2010 that should help web developers using either WebForms or MVC, which would be good.
Bloggers tend to talk about what is shiny and "new", that's the way things go - you're bound to see a lot of words written about it because of that, although MVC is hardly a new design pattern - it goes back at least 30 years.
The same could be said of WPF/Silverlight - are they WinForms/WebForms killers? No. They are alternative offerings, with some benefits over the earlier way of doing things, but also with some differences/drawbacks.
I was at a conference (Remix 08) and Scott Gu said they will definatly be continuing to support both methods and that MVC was not appropriate for every application. Scott said there were a number of coming improvements for web forms model (although didnt say what they were).
The web forms model will not disapear because:
Web forms model is better for some types of applications, e.g. small apps, those requiring long processes that make use of view state useful
Many applications are using it
Many third party components developed for it
ASP.net implementation is not mature yet (although does seem pretty good so far)
Microsoft will probably announce a number of new features in PDC in a few weeks time.
Microsoft is finally coming to terms to one basic fact of development. You can't provide the ultimate solution to any problem. This is why MVC is being developed, and Scott Guthrie is clearly stating that MVC is meant for larger, more enterprise-y sites. Web forms will continue to exist and be developed as a simple, RAD-based approach to web development.
If you take a step back and review all recent improvements and additions to the Microsoft stack, you can quite easily categorize them between these two classes. For example:
Data access: LINQ-to-SQL vs EntityFramework
Remoting: WCF vs WebServices
LiveID: LiveID (web) authentication vs RPS authentication
...
I only hope that Microsoft will make this distinction clearer with time, because there seems to be a lot of confusion among developers as to what tool should be chosen for which task.
In conclusion, I think that Microsoft will keep on developing both because they cater to different developer profiles. Microsoft has obviously a lot of interest in growing its developer base as much as possible and to make the .NET stack as useful as possible.
I am going to go out on a limb here and disagree with the general idea that MVC is the "enterprise" framework here or is somehow the better of the two.
MVC is great! But just look at the name. It stands for "Model, View, Controller"... see the "view" in there?
Now look at the competition, "Web Forms"... see the "forms" in that one?
MVC does a great job in "view" type situations. For sites that publish content ("views" of information) MVC probably has an edge, especially for larger systems that need a lot of testing and very a formal design to support intelligent view switching.
For applications that interact heavily with the user via forms (data collection and data entry heavy apps) web forms has an edge due to the inherent use of form posts as a primary mechanism.
While you can do views with web forms and you can do forms with MVC, each has trade-offs. In the current state of MVC, I find that writing heavy data entry "views" is much more difficult and painful than with web forms... and I don't mean a little bit.
In the future I do expect to see MVC get better with dealing with data entry scenarios, but these scenarios will likely come at a pretty high price compared to doing those with web forms.
Neither is more "enterprise" level than the other as far as I can tell... what I'm most interested in going forward are hybrid applications that use MVC for the display and publishing end of the business while web forms are used more naturally for heavy data entry end... all in the same web project... I sure hope we see something like that.
Before word of the MVC framework started spreading, we spent a good deal of time at my company developing our own .NET MVC framework.
This was because we didn't want to be constrained by the limitations of the WebForms abstraction - we wanted to avoid the 'clunky' feel and user interface compromises that WebForms seems to impose on all by the most heavily customised applications. Also, we wanted friendly URIs and we wanted a better separation of front-end and back-end development than that offered by WebForms (we settled on an XML / XSLT architecture).
In my opinion, WebForms in fact offer a much poorer method of interacting with the user specifically due to the use of ViewState, PostBacks, etc etc that abstract the actual mechanics of HTTP from the developer - this gives them less latitude in how they allow users to interact with the system. The classic example is that because WebForms pages are almost always the result of a POST, if the user attempts to refresh the page, the user gets a nasty warning message from the browser. The pattern in the traditional web development world for dealing with this has always been to include a 302 Redirect directive in the HTTP Response, thus sticking to the original HTTP paradigm of GETs being for retrieving data, and POSTs being for sending data. Other, similar problems exist such as the inability to have two forms on a page (for example a login form to a website on a different server).
That said, for RAD, WebForms are brilliant. I'm currently developing the admin application for a webapp we've developed using our custom MVC framework, and I'm flying through since all I need is to display the contents of a load of database tables, and in some cases allow the user to edit them, in various different ways.
I think that if we need to convince ourselves that MS are going to continue to support WebForms - just think of all the ex-Windows developers. These are the people that WebForms was originally developed for, and they're not going away. Corporate developers will be your saviour if you're a WebForms fan.

Resources