Protecting from cross-site request forgery attacks - c#

I am now learning a concept of ASP.NET Core development and during my learning I have found out from the following article that a webpage needs to be protected from unauthorized access in order to prever from Cross Site Request Forgery Attacks.
I have followed several tutorials and for my own (learning) application I have:
Implemented the [Authorize] decorator on the top of my Controller (in my case it was API controller)
In the actual POST, UPDATE methods I have implemented if (ModelState.IsValid) call to check, if necessary parameters have been passed
Used ViewModels instead of actual Models that are used in a database when communicating with a website (or API in this case).
I have the following three questions:
1) Is this approach sufficient in order to protect my website? As an authentication method I am using simple CookieAuthentification. Or in other words (as this might be too broad question), is this approach on a right track to dishearten possible attacker?
2) In my current setup (of using ViewModels instead of real models) is [ValidateAntiForgeryToken] necessary? If yes, what purpose it serves?
3) Now the question (which I am most interested in) is regarding ViewModels. How can ViewModels protect my website from unauthorized attacks? I do understand that in my ViewModel I can only expose variables/properties that I want user to have access to (and hide the rest), but how can it protect my website, when I still need to expose my ID (primary key) (as without ID I cannot imagine how one would do e.g. DELETE / UPDATE calls)?
Any help in this matter would be more than appreciated as I am still learning this subject.

Web site security is a complex issue. Protections should be implemented that are commensurate to the sensitivity of data requiring protection.
1) Some level of Authentication is necessary to protect against an anonymous attack, where an attacker would have an infinite number of tries to get a successful attack.
2) [ValidateAntiForgeryToken] is required for any data change. Without it you could have a user who has successful authenticated and been given a valid cookie, that is then stolen by a malicious actor who has compromised the browser being used by your valid user, and use that stolen cookie to make unwanted data changes.
3) The use of ViewModels means that you have not exposed direct data calls to the database. Yes a malicious actor could modify data in undesirable ways, but is still limited to changes within the scope of your data layer. Without ViewModels it might be possible for an attacker to make changes that you never intended through SQL Injection. If you are using an ORM such as Entity Framework then the possibility of SQL Injection is less likely.

Related

Do I need an access token for my web api service?

I have an application for managing user data. All the business logic is encapsulated within a separate web api service, which the user management web application (among others) calls into. At the moment all web api calls are exposed (they are anonymous). However the web api sits on a separate domain and is only accessible to the applications that call into it.
Is there any benefit to adding bearer tokens and enforce authentication for each API call?
If the web api service is on a separate domain and adequately protected from the internet, then you dont need to authenticate at the service level for external security (over and above any application logins you have).
However, that is not to say that your application is not internally exposed and could be intentionally or accidentally called by malicious intent or an incorrectly configured application, for example, someone accidentally points a load test at production. For this reason I would secure it, at least with a HMAC if you dont want to implement full blown authentication.
EDITED: To add that with any public facing web real estate you should classify your data and decide the appropriate level of security to apply. In some circumstances you may not want to secure GETs of low sensitivity data. On the flip side, exposing GETs allows someone access to try denial of service attacks (by calling your API in a loop from multiple servers / a botnet). When it comes to POSTs, the risk is higher, since consumers will be inserting in to your datastore.
It's also always good to keep the OWASP Top 10 in mind when dealing with security.

Implementing field/column level security in a Web API

I have a .NET Web API that allows clients to return details of People and associated data.
There are a number of non-fixed roles in the system (it's multi-tenanted) and each Role has access to particular fields e.g. Admin could see Date of Birth, non-admin can't.
The structure of the application is:
Client Controllers > Business/Service layer > Repositories > Database
Data access is currently being managed through a combination EntityFramework for Add/Update/Delete and Dapper for Queries.
My question is: is there a excepted standard/common of approach of filtering data at field level going to the client, and returning from a client before updating models in the database? Ideally if there was some sample code or application to demonstrate the approach.
My initial thoughts on this are to filter the ViewModels before they get sent to the client and perform checks before updating the EntityFramework models, but this seems disjointed. Also I'm not 100% on the best approach to this either way.
Other possibles I have considered are:
Use a formatter to remove data before being sent to client, and a custom security attribute to filter data before hitting the controller action.
Move away from EntityFramework and implement my own secure Data Access Layer to handle all of this
Implement the security at the database level
A ViewModel per entity per role, although I have discounted this as with non-fixed roles this can blow up quite quickly.
I'm not aware of any frameworks available that offer field-level security but lots of commercial products offer very configurable field-level security e.g. SalesForce, Microsoft CRM, etc.. and essentially I would like to implement something similar but on a smaller scale.

Exposing existing Service Layer using ASP.NET WebApi

I currently have a layered architecture that is as follows:
Service Layer - This is the main interaction point with the domain.
Contains all the business rules, validation, etc.
Data/Repository Layer - This is the layer that handles all persistence of the data. Contains no business logic or validation. Contains basically Repository<T>, UnitOfWork (EF Specific) and all the EF things like DbContext, EntityTypeConfiguration's, etc.
Entity Framework
SQL Server
I am using an Anemic Domain Model, so basic POCO's that represent the problem domain.
I have a couple questions about exposing this via ASP.NET WebApi.
Where does the security live at? Basically things like does a user have the access to edit a record, or type of record. Can a user perform a specific action, etc. As well as things like Authentication/Role Based Authorization.
Should I use the WebApi as the actual service layer, or use it to expose my existing service layer over HTTP in a RESTful manner?
Given a basic example of say changing a name of a category, where do I enforce that the current user has authority to change said record? Do I rely on the Thread.CurrentPrincipal to get the Identity to check for a given role, and set that in the WebApi? Mvc Application?
Are there any good examples out there that show this type of situation I am talking about?
BTW - I am using ASP.NET MVC 5 to serve up the shell of the application (SPA) and then the front-end is going to be all AngularJS.
Regarding your first question about the level of security your services should have the correct answer is what I believe it should be a principle in all applications:
Services should have enough security to protect the data from unwanted users.
Once you create a service and make it public you are exposed to possible attacks of course having complex security rules may increase development time and some situations may create a decrease in performance; measure the level of the threat and plan your security accordingly.
WebApi was created with intention to provide services through Http/Rest all the principles and features build-in were made with that intention so regarding your second question and like you inferred at the end of it it is a service layer but an Http/Rest service layer.
WebApi uses an attribute Authorize to enforce security an as it is normally with .NET Frameworks you can inherit from it and extend it. You can learn more about it here.
And since you are using Angularjs and even though you will need MVC5 to use WebApi my recommendation is that you do not use MVC razor or any other server technology to render your pages.

Controlling access to pages by cookies

I want to control access to certain pages of my app by cookie. But I want to coordinate this from only one place. I thought put a check in a Layout.cshtml I.E. That way all pages use this Layout will do automatically. Is that good?
Edit: Security for this app its not a concern.
You're violating one of the core principles of MVC – never put real logic in a view.
Instead, you should create an ActionFilter.
You should also figure out how to secure the cookie; you should probably use ASP.Net's existing membership system
No, it's not good because cookies can be manipulated easily by anyone.
Why don't you want to use the normal Authentication and Authorization techniques that are already available?
Using cookies for controlling access to pages does NOT sound like a good idea. You will have to create a way to secure the cookie, which isn't easy. Without that, your authentication will be easy to spoof.
I would recommend that you use the built in authentication and authorization mechanisms for MVC 4, which is well tested and built for this purpose. Here is one article to get you started.
Using the [Authorize] and [AllowAnonymous] attributes of MVC4, you can be quite flexible when restricting parts of your site to authorized users.
I've posted a more lengthy example using above mentioned attributes as an answer to another SO question.
you should use the Authorize attribute on your controllers/pages instead of cookies
and restrict the pages to certain roles and assign users to roles.

Where to locate custom membership, roles, profile providers in a 3-tier setup?

I have a 3 tier ASP.NET MVC 3 project that has a data layer, service layer then a presentation layer which calls upon the service layer to get data. I'm actually using the doFactory patterns in action solution.
I want to implement a custom membership, roles, profile provider but I'm not sure exactly where to put it. I was thinking of putting it in the service layer then have the provider call on the DAO objects to get the info.
Any other ideas?
You're thinking pretty well. Though the UI layer interacts with the client and takes their password, your service layer should process attempts the enter system.
Your action methods pass along the information to the service objects responsible for authorization.
Your service layer would have no idea whether it is in a web application or not.
The data layers is just the place where that information is stored, not where it is processed.
You might choose to keep the ID of the user in the UI layer, in session. On login the Service layer would take the username/password/whatever and return a UserID. Or, your action methods could pass in a session key into the service layer each time, to get the User information.
Edit due to comment: I'm doing this in my current project (couple $million scope). I have my security decisions in the action methods. (Though of course the tools for making this simple are objects from the Service Layer.) For example, if the current user doesn't have this role or that role, then redirect them to a rejection page, otherwise, do the thing. MyServiceLayerObject.DoThing() has no security inside it.
It's the simplest way for my app and many others. ("Simplest" means it will will be screwed up the least. When it comes to security, simple is good!) Since the Action method is the gateway to the functionality, having security in the service layer would just cause extra work and actually obscure what security was happening. Now, that's my app, where there is usually one place where each action takes place.
Your app may be different. The more different action methods and (especially) different components are using your Services Layer's functionality, the more you'd want your Service Layer functionality locked down with your authorization scheme. Many people feel that security should always be in the service layer, and that any additional security actions in the UI layer would be bonus redundancy. I don't agree with that.
Here is an existing implementation of Membership Providers in 3 tier world that I found when looking for the same thing...
http://elysianonline.com/programming/wcf-wrapper-for-asp-net-membership/
And here ...
http://elysianonline.com/programming/using-the-wcf-membership-provider/

Categories

Resources