How to validate jQuery AJAX call ASP.net - asp.net

I have a web application where I have used http-handlers and jQuery for AJAX call.
Now the problem is user can type the same URL in the browser which is generated by the jQuery and operation is being performed.
Can I send some token with the query string and then on server side I can look for the right token before performing any operation.
Hope that I have written my problem correctly.

You may need to handle this in a similar fashion to how it can be handled in the MVC framework. Here is a similar post that describes a potential solution.

The above technique is called
Cross Site Request Forgery
Risk Impact
An attacker can hijack logged in users session for performing malicious transactions.
Recommendations
It is recommended implementing Page token (a random token as an additional parameter in the request) for all transaction pages. This token should be randomly generated and should be unique for each user.
The suggested URL are
http://www.owasp.org/index.php/CSRF_Guard
http://www.cgisecurity.com/csrf-faq.html
var cg = new CSRFGuard();
cg.SetupCSRFTokenNameAndValue();
SessionManager.CustomerConfig.CsrfTokenName = cg.CsrfTokenName;
SessionManager.CustomerConfig.CsrfTokenValue = cg.CsrfTokenValue;
Thanks a lot.

Related

Checkmarx XSRF issue

Checkmarx is complaining about an XSRF issue in our web application. We are using ASP.NET web forms with framework 4.0 (not MVC)
Checkmarx said: Method btnSubmit_Click at line 1760 of \ABC.aspx.vb gets a parameter from a user request URL from element text. This parameter value flows through the code and is eventually used to modify database contents. The application does not require renewed user authentication for the request. This may enable Cross-Site Request Forgery (XSRF).
Any idea of how to prevent XSRF from ASP.NET Webform application?
We have tried a lot of solutions but none of them pass Checkmarx:
Here are some things we tried:
https://software-security.sans.org/developer-how-to/developer-guide-csrf
or
http://willseitz-code.blogspot.com/2013/06/cross-site-request-forgery-for-web-forms.html?m=1
or
https://security.stackexchange.com/questions/187740/two-solutions-for-csrf-on-owasp-for-asp-net-webforms
I think the solutions above should work and protect/prevent our web form from CSRF/XSRF risks, but why can Checkmarx not detect it? Is this a false positive?
It is recommend to check the CxQL queries from Checkmarx Portal (Settings/Scan Settings/Query Viewer) to understand how Checkmarx find a vulnerability, including what kind of protection that Checkmarx is able to detect.
For your case, check the logic in CSharp/Cx/CSharp_Medium_Threat/XSRF.
For Web Form Applications, the query CSharp/Cx/General/Find_XSRF_Sanitize is used to find if you have done any protection in your application.
As the comment of Find_XSRF_Sanitize said:
For ASP Web Forms, the main solution to prevent XSRF attacks is to
assign a unique token to the ViewStateUserKey property of the page.
Also
AntiXsrfTokenKey
is also considered a protection.
If you use ViewStateUserKey or AntiXsrfTokenKey, all the http interactive requests that are defined in the same method as the ViewStateUserKey or AntiXsrfTokenKey will be considered as sanitized request, and will be removed for the potential tainted request list.
Note that in the CxDOM tree, ViewStateUserKey and the sanitized request have common ancestor, which is the method declaration.

ASP.NET MVC Anti Forgery Token is not one-time (per request) token?

I've read a lot of articles and made some own tests and what I can see from my tests and source code (IsCookieTokenValid and GenerateCookieToken - you can see there hard coded IsSessionToken = true) that ASP.NET Anti Forgery Token is per session, not per request (or POST request and so on). So token stored in the cookie remain the same during user's session. But token on the form changes (it's new) with every request (page refresh).
I've check if form submit with old form tokens are still valid, and they are. So what's the point to generate every time new form token if old tokes still valid and token in the cookie remains the same during the user's session?
I don't see in the code any setting to change this behavior and make token "one-time". The only option or solution is to delete the cookie and that will force to generate the new one. Correct? Any other ideas?
I ended up modifying ASP.NET MVC library and added setting GenerateOnetimeToken to AntiForgeryConfig to be able generate new pair of tokens (cookie and form tokens) with every page request (AntiForgeryToken() helper call).
Here is ASP.NET MVC 5 branch for this change.

Requesting header by name angular

I have an asp.net application that I'm attempting convert the front end to Angular. Getting header information is important to the view. I'm used to getting the header information like so in C#:
httpContext.Request.Headers["USERID"]
How can I do the same thing in an angular controller?
In asp.net each request runs in its own independent context and hence the header access as you have shown in your code make sense.
This does not hold good for angular or in fact any client side framework. You can always get the headers for any request or response made using angular $http but the question is which request? During the lifetime of the app you would make many such requests.
Let's say you want to get the current userid, you can create a service that returns the logged in user. There are two ways to implement such a sevice
create a method on server to return this data. Invoke this method from service and cache results
on the client side assuming there is a login request made through angular, implement a success callback method which can update the service with the logged user id.
You can look at $http documentation here to understand how to access headers.

PageMethods security

I'm trying to 'AJAX-ify' my site in order to improve the UI experience. In terms of performance, I'm also trying to get rid of the UpdatePanel. I've come across a great article over at Encosia showing a way of posting using PageMethods. My question is, how secure are page methods in a production environment? Being public, can anyone create a JSON script to POST directly to the server, or are there cross-domain checks taking place? My PageMethods would also write the data into the database (after filtering).
I'm using Forms Authentication in my pages and, on page load, it redirects unauthenticated users to the login page. Would the Page Methods on this page also need to check authentication if the user POSTs directly to the method, or is that authentication inherited for the entire page? (Essentially, does the entire page cycle occur even if a user has managed to post only to the PageMethod)?
Thanks
PageMethods are as secure as the handler in which they reside.
FormsAuthentication will protect everything except the Login page.
On an unprotected handler, like login, you should expose only methods that 1) are not sensitive or 2) validate the user.
EDIT: in response to comments and other answers regarding CSRF and XSS please see http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx
You're trying to protect against CSRF attacks.
These attacks can be prevented by requiring an authorization code in the POST parameters, and supplying the auth code in the initial page load. (The auth code should be per-IP address and per-user, and should expire quickly)
For added security, you can make each auth-code only usable once, and have each request return a new auth-code. (However, if any request fails, you'll need to reload the page)
I am working on a project that heavily utilizes ASP.Net WebForms Page Methods which I talk to using Ajax. This is rather very convenient for me than writing all my codes in JavaScript.
However, Securing the page methods became an issue which troubled me. I see that I can access the page methods via Postman and Fiddler hence, enabling hackers to play with your APIs.
My solution was quite simple which I discovered accidentally. Adding a static Cookie request to the page method would return error for any app that is NOT the website.
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static string GetAnything(object dat)
{
HttpCookie myguid = HttpContext.Current.Request.Cookies.Get(Constants.Session.PreventHacking);
var hackguid = myguid.Value ?? ""; //other page method contents
return "anything";
}
A postman request to this method would return :
{
"Message": "There was an error processing the request.",
"StackTrace": "",
"ExceptionType": ""}
While a more detailed error would show if on LocalHost.
I understand there are browser ad-ons that can intercept API calls by sitting just beside the website. I have not tested this. A separate security fix has to be built for this however.
I'll update here once I perform some tests.
Think of Pagemethods like a mini webservie local to the page. The fact is they will have no extra checks and verifications in place except those that are placed on the entire website, and those that you choose to put in.
Using Pagemethods is a smart idea from the point of view of 'Encapsulation', and if you're going to use them it doesn't hurt trying to put in some extra security measures in place.

how to save and retrieve cookies using ajax webservice calls

Hi I have web app which stores certain things on a page in a cookie when the page posts back in case the user doesn't finish what they're doing and come back later. But now I must do a javascript time-out and actively save the info to the cookie rather than wait for the user to postback. All my cookie code is on server side where I use Response and Request objects to read and write cookies and I want to leverage that. So I would like to just use ajax calls to a webservice. Is there a way for me to access Request and Response objects and read and write cookies to the browser via those objects during a webservice call? Or should I just go with javascript?
EDIT: Sorry i wanted to specify that I would like to use jquery-ajax.
Implement an ajax callback on a timer that posts back every n number of seconds. When the ajax posts back, check your constraints and simply update the cookie.
OK so I created the static web method on .cs side of the page and in the method I enable session. So this way, I can save stuff to cookie by making ajax calls and using my already existing .cs cookie code.

Resources