Pen testing your MVC application - asp.net-mvc

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

Related

Does it make sense to separate Rails API and Rails app?

I have a project that involves both mobile and web clients. The mobile clients will mainly get content and post user updates, while the web client is mainly for creating content. As such, the web client and API share a lot of the same models and validation.
I am trying to decide the best approach in this case:
JSON-only Rails API + separate Rails web client that calls API.
Single Rails app with separation of API and client side (somehow).
The pro for me in terms of option N°1 is the separation of concerns, as I can work on the API while someone else do the web client. The con seems to be lots of duplicated code in terms of validation.
N°2 could make more sense in terms of reducing code duplication but it would get messy if more than one person is working on the same code base and setting up a process to resolve code conflicts is not something I want to do at this point since we're an early stage startup and want to get out something quickly.
Is there anything I'm missing?
The best practice is use ONE rails application for API and Web Interface
To separate those parts, just create a namespace for API like it's described there http://collectiveidea.com/blog/archives/2013/06/13/building-awesome-rails-apis-part-1/
Do it in one.
The con seems to be lots of duplicated code in terms of validation.
No, you would not have duplication the validation happens in the model, which is shared by your API <=> web controllers. Of course, you will have separate implementations for the actual authorization/session handling (if you have those), but these will not likely be duplicate but a bit different for your two access layers.

asp.net mvc consuming asp.net web api end point

Looking at this question:
SO question
The accepted answer by Darin Dimitrov looks appealing (.NET 4.5 version). I am just wondering how this compares performance wise with client side solutions (e.g. using knockout/angular/jquery) to assemble the HTML given some JSON from the web api endpoint. Did someone ever do some perfromance tests on this. What are the pros and cons of the 'client side solution' vs the 'razor server side' solution?
You should have to define performance.
However there is a very big difference between the two options:
if you do it client-side (with ko/ng/jQuery) the server only executes the API controller action and returns the formatted data.
if you do it server side, apart from execution the API action, the server has to execute the MVC controller action, so, undoubtedly, the server does more work.
The only conclusion is that the server has less work to do in the first case. And, usually, the network traffic is reduced (a JSON object is usually lighter than a rendered partial view).
If we're speaking about the user experience, in general client side technologies (jQuery, ko, ng) offer a much better user experience becasue the page is much more responsive: it's easy to show/hide elements, set the focus, make trivial calculations, remote validations... And if we use modern libraries, we can go further on improving the interface resposiveness. For example breeze.js allows to cache data in the client side to avoid making extra ajax calls to the server, giving a much more responsive experience, specially if you anticipate what data can be needed and cached it before hand. You could even persist data in HTML5 storage, so that it's available for other sessions.
Then, from the user viewpoint, I think it's much better the second option. And the server has less work to do, which can make it also more resposive in high-traffic sites.
Even so, I don't know what is "more performant" or even what it is "to be performant".
Whatever it is, using client side technologies is a much better option. But it takes some time to master the associated technologies.

Understanding REST conceptually with Rails

I'm a little late to the party, but I'm trying to wrap my brain around how REST is supposed to work, both in general and in Ruby on Rails. I've read a bunch of articles online about this already, but still don't feel like I'm getting the big picture.
REST as I understand it, is a series of aspirational statements, with the net result at the bottom being that URLs should contain all the information necessary to handle a request, and gets should not be able to change the state on the server, and a bunch of other concrete guidelines.
As I understand it, REST in Rails is based around CRUD, which is to say, every model has a create, read, update and a delete action. Each of these actions is accessed through a similar set of URLs, generated by mapping a resource in the routes. So a login URL is creating a user session, so the URL would look like example.com/session/new with a POST, and logout would be example.com/session/destroy with a POST.
What exactly is the benefit of standardizing URLs in this fashion? It strikes me as optimizing for machine readability at the expense of human readability. I know that you could then remap in the routes file example.com/login to example.com/session/new but that is just one more step for no apparent gain to me.
Is it considered really bad practice to develop a website that uses traditional routes now?
Furthermore, each of these CRUD actions should be able to respond to requests with whatever type of response the request is looking for. So the same link to, say, example.com/tasks could also be called at example.com/tasks.xml to get an xml representation of the result, or example.com/tasks.json for a json representation.
Is this to say that a RESTful API would just be the usual links on the site but with xml appended? It strikes me as very strange and awkward that a web API would behave in this way, but this seems to be what's implied by everything I've read. I'm more used to seeing an API that has links like example.com/api/tasks to get the list of tasks. What exactly is the advantage of this approach?
Rest provides another chunk of "convention over configuration." For a widely used, limited set of common problems (crud actions against the models as a whole), rest is very useful as an application development convention.
What exactly is the benefit of
standardizing URLs in this fashion?
Programmer efficiency. Less to think about; enables more time to be spent on harder problems, etc. Better maintainability. Easier testing. Etc.
Is it considered really bad practice
to develop a website that uses
traditional routes now?
Yes, for crud actions that are interacting with an entire record of the model.
Furthermore, each of these CRUD
actions should be able to respond to
requests with whatever type of
response the request is looking for.
So the same link to, say,
example.com/tasks could also be called
at example.com/tasks.xml to get an xml
representation of the result, or
example.com/tasks.json for a json
representation.
Is this to say that a RESTful API
would just be the usual links on the
site but with xml appended?
Yes, if your api fits the rest model. I think the big issue is authentication. If you want your api to be stateless, then you'll probably need to include authentication with each call. At that point, if you don't want to use HTTP level authentication, you'd need to decide how to include the credentials.

Am I wrong in wanting to roll my own Authenticate / Authorize system given the following requirements?

In my pet project I want to have a user system with the following requirements:
It needs to work with Db4o as a persistance model
I want to use DI (by means of Turbine) to deliver the needed dependencies to my user model
It needs to be easy to plug in to asp.net-mvc
It needs to be testable without much hassle
It needs to support anonymous users much like SO does
I want Authentication and Authorization separated (the first can live without the second)
It needs to be safe
I'm aware I'm putting a few technologies before functionalities here, but as it is a pet project and I want to learn some new stuff I think it is reasonable to include them as requirements.
Halfway in rolling my own I realized I am probably suffering some NIH syndrome.
As I don't really like how needlessly complex the existing user framework in asp.net is, it is actually mostly only all the more complicated stuff regarding security that's now giving me some doubts.
Would it be defendable to go on and roll my own? If not how would you go about fulfilling all the above requirements with the existing IPrinciple based framework?
It sounds to me like what you want to do is roll your own Custom .NET Membership Provider.
It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above).
Direct from MSDN...
Implementing a Membership Provider
I think you recognize where the thin parts in your consideration are: namely in that you've included how to do what you're doing as motive in why you're doing it and the NIH (funny: I'd never seen that before) issue.
Putting those aside, your provider is something that you could potentially reuse and it may simplify some of your future efforts. It should also serve to familiarize you further with the issue. As long as you understand the ASP.NET framework so you can work with it too if you need to (and aren't specialized such that you don't know what you're doing if you're not using your tool) then I believe you've already crafted your defense.
As DOK mentioned, be cautious that you're not rolling your own here to avoid a larger task at hand in whatever your other functionality is. Don't let this be a distraction: it should be something your application really needs. If it's not, then I'd lean towards focusing on your software's core mission instead.
If you go ahead and create your own custom solution, you will have a better idea of how difficult it is and what features you want. This will help you to evaluate off-the-shelf solutions for future projects.
OTOH, spending time developing functionality that is already readily available means you won't be spending that time working on the major functionality of your project. Unless authentication and authorization are a major component of your project, you might consider investing your time, and expanding your knowledge, in another area.
I too am working on a pet Project using ASP.net MVC and db4o and did the same thing, so you're at least not alone in going down that route :). One of the biggest reasons for me to start playing around with db4o as persistence layer is that especially authorization on field level (i.e I'm allowed to see Person A's first name but not Person B's first name) is though to achieve if you're forced into complex SQL statements and an anemic domain model.
Since I had complex authorization needs that needed to be persisted (and synchronized) in both db4o and Solr indexes I started working on rolling out my own, but only because I knew up front it was one of the key features of my pet project that I wanted 100% control over.
Now I might still use the .Net Membership provider for authentication but not (solely) for authorization of objects but only after i POC'd my authorization needs using my own.

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.

Resources