CSRF protection of GET links - csrf

I need to add CSRF protection to a web application.
Problem is in the fact that the app relies heavily on links (GET requests that is) to make changes in the database.
Links are generated using a class, so I could easily add an extra parameter for CSRF token to each link.
However, I understand that CSRF token in a GET request might not be a good enough protection.
Note that app is only available over HTTPS, so GET params can not be exposed/stolen during client/server communication (but history stealing issue remains).
Could GET CSRF token param be considered "safe enough" in this setting?
If not, what is the best way to solve this problem? Only thing that comes to my mind is to wrap each of my links into a form (ether explicitly, or creating form onSubmit using JavaScript).

To be able to read the response to a CSRF attack’s request, an attacker would need to get the victim to execute his JavaScript code. So, CSRF for a "GET" request is almost not useful. This is assuming you have followed the standards that "GET" requests should not modify any data and any modifications need to be done only using "POST"
Using cookie based authentication and SSL should keep you away from a guy who is trying to change the parameters
You may want to introduce some signing based on timestamp to avoid replay attacks
That said, if you have any POST requests, you should consider the CSRF protection.

Related

Stateless REST API with CSRF and XSS protection

Is it possible to protect stateless REST API from both XSS and CSRF attacks?
Currently, I'm using JWT token stored in secure/httpOnly cookie for stateless authentication. This should protect the API from most common XSS attack: stealing cookies with XSS-injected JavaScript and sending them to the attacker.
However, this doesn't protect the API from CSRF attack, where attacker would trick the authenticated user to follow a link to the particular web API call to actuate adverse transaction on behalf of the victim. How could I protect the API from this attack without introducing server side state?
Also, is it true XSS vulnerability would inheritedly allow CSRF type attack in the following scenario: Injected JavaScript would retrieve CSRF token from the client side state, DOM or the browser storage and prepare a malicious ajax call to the server. Browser would still automatically include the httpOnly cookie for the same origin request. Is there a way to get protected from this other than protecting from the XSS vulnerability in the first place?
Stateless anti-forgery tokens
The first question is about preventing CSRF without server-side state. The current approach for stateless anti-forgery tokens is the double submit cookie pattern.
CSRF attacks depend on the browser automatically sending the API's own cookies back to it, regardless of where the request originated. The attacker doesn't have or need access to the cookie contents. They only need to trick the user into loading malicious HTML. The double cookie pattern adds a new requirement: the attacker must know and separately send the contents of the anti-forgery cookie.
There are ways for an attacker to overwrite the anti-forgery cookie with their own. So you may want to look at some additional security hardening for this approach. Especially HMAC signing the anti-forgery token to prevent token substitution. Using HSTS and the __Host cookie prefix to ensure transport security and proper cookie scope. And having the client provide the anti-forgery token in a custom header.
The custom header ensures the request must be sent from JS, since HTML-tag-based CSRF attacks cannot set custom headers. Being sent from JS also triggers additional protections. For cross-origin requests it triggers SOP on the browser and CORS validation on the server. The server can also do basic Origin validation.
Regarding the scope of CSRF attacks, here is a note from the OWASP CSRF link at the top.
Forcing the victim to retrieve data doesn’t benefit an attacker because the attacker doesn’t receive the response, the victim does. As such, CSRF attacks target state-changing requests.
XSS question
Yes, an XSS attack could happen that way. Once a malicious script is loaded into JS, it has free reign to use anything accessible to Javascript. Including app code/memory, browser storage, and cookies. Even though HttpOnly cookies are not readable, they can still be sent in requests. A non-targeted attack might look for key data in locations used by popular frameworks. And might try to probe for popular/discoverable API frameworks on the server. A targeted attack means the attacker studied your system and crafted a custom payload for it.
The primary vector for XSS is unsanitized external data (user input, database values, etc.). To prevent XSS, check out these guidelines from OWASP. Of note is that front-end frameworks like Angular, React, Svelte, Vue, and others have built-in XSS protection. Because they sanitize data before rendering it. Example: an attacker enters an HTML string into an input. When it is later displayed, these frameworks HTML-encode the string. So left and right angle brackets are replaced with < and > and so on. This causes the browser to evaluate the string as text instead of runnable HTML. But you can still mess it up in different ways if careless.
XSS attacks can also come from external resources. Maybe a compromised CDN or NPM script. If your deployed code takes dependencies on NPM libraries, pay extra attention to NPM audit warnings. One attack pattern is to attach a small loader (easier to go unnoticed), which will fetch attack payloads at runtime. A CSP policy can help prevent this. Specify an allowed list of resources -- your app assets and API URLs -- and block all others. CSP can also prevent data exfiltration.
For both CSRF and XSS
For attacks on your API, you can additionally employ server-side mitigations. IP-based throttling / temporary bans, unusual activity grey-listing and alerting, etc.
For especially sensitive operations, one strategy is to use an escalated authorization. This could take the form of requiring the user to re-authenticate or use a 2nd factor like a one-time password. This can block automated attacks since it requires active user intervention.
To mitigate attackers using existing escalated authorizations (which may also be in a cookie or app memory), they can have short expirations and be limited to specific operations. To go even further, the approved operations + relevant data can be signed. This will prevent malicious scripts from reusing an escalation to execute the same kind of operation with different data. Even further, these sensitive operations can be idempotent. So if an attacker does resend already-executed operations, they will not cause any additional changes in the system.
Zooming out
Try to engineer your systems to be as uninteresting as possible to hackers. Use trusted external services for sensitive needs like credit cards and credentials. Ideally (from a security perspective) the hacking risk would be reduced to just data vandalism/loss. So in the worst case that a breach happens, it would have little long-term impact. And it could be recovered with common practices, including routinely tested backups. And then further mitigations added for the specific attacks used.
Tread especially carefully with user-to-user interaction. Since this adds more targets and pivot points for hackers -- your user base. The most security-conscious eyes should be on these pieces. Not only for technical dangers like user-to-user XSS attacks, but also social ones. Human weaknesses are the most well-known and easiest to exploit.
Lastly, there is no sense investing in mitigations which have low risk/consequences in your situation. So do not take everything here as a requirements checklist. It's not a complete list anyway. Focus on your biggest risks first. Reevaluate periodically.
You can generate a token (e.g. a UUID) and put it into the jwt token as well as send it back to the client. Then the client sends it during every each request in a header. Then the server can compare the token in the header and the token in the jwt token to make sure the request comes from the client who was aunthenticated.

Does CSRF exist in pure rest api without UI?

I don't know much about CSRF, but after reading the doc, it seems it only happens in browser. So now I have a library with rest api, but no ui. Do I need to take care of CSRF in this rest api ? Thanks
First of all, it's important to note that CSRF is an attack that can be exploited in browers.
According to Guidelines for Implementation of REST, a document issued by NSA, REST APIs are vulnerable to CSRF attacks:
F. Cross Site Request Forgery:
Cross site request forgery (CSRF) attacks attempt to force an authenticated user to
execute functionality without their knowledge. [...]
It is important to note that CSRF attacks execute functionality, but are unable to
interact with the response from the targeted server. [...]
REST is stateless at its core and thus inherently vulnerable to CSRF attacks. [...]
Two approaches are suggested to ensure protection. Summarizing them below:
Custom HTTP header
The first method involves checking the presence of a custom header (agreed-upon between the server and a client – e.g. X-CSRF or X-Requested-By) in all state-changing requests coming from the client. The value of the header does not really matter. It works, because the browser would not send custom headers unless the web page makes a request using XMLHttpRequest, which only allows requests to the same site.
This method is currently used by Jersey, the JAX-RS reference implementation for REST web services in Java.
And it's also mentioned in Robust Defenses for Cross-Site Request Forgery from Stanford University.
CSRF tokens
The second method involves protecting REST endpoints against CSRF attacks by establishing session state. This approach violates REST principles and involves the use of a CSRF token that is generated for each action, then associated with the user session and submitted with each important website action.
This essentially forces a sequential ordering of actions on the application.

Is there any safe way to keep rest auth token on the client side for SPA?

If we get token from the rest server and use AuthorizationToken header in every request for authorization, we still need to keep it when the browser's page is closed.
The only universal way to do it is to put the token to cookies. But in such way even if the cookies are not used for authentication, they can be stolen by XSS.
And we can't use httpOnly flag. So:
Are there any other specific ways to protect the token and keep it safe?
If HTTPS is used during the whole session and the cookies with token were stolen, is it possible to hijack the https session with a token?
My answer is perhaps a bit naive but why not store the token in the persistence storage of your browser. If you use Angular, with code as describe below:
function((...), $window) {
(...)
$window.sessionStorage['userToken'] = '<user-token>';
}
I don't really see other approaches (exception cookies) to keep such hints when the browser's page is closed.
The problem with cookies is that your client needs to be a browser to leverage this feature transparently... Moreover it's really not the better approach for authentication within RESTful services ;-)
You can combine this with a mechanism of security tokens with an expiration date and the ability to refresh them, as described in the following link: https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/.
In addition, you can use JS framework like Angular that provides solutions to XSS. See the following links for example:
http://java.dzone.com/articles/angularjs-how-handle-xss
angularjs + cross-site scripting preventing
Hope it provides some hints to your issue,
Thierry

CSRF token protection using cookie

Is it a good practice to save the csrf token in a cookie or is it better to use a hidden field in a form? Also is it good to regenerate csrf token every user request like what captchas are doing?
Thanks
It is best to include it in the form. The idea behind a CSRF token is that it is not passed passively (e.g. if a malicious user is able to trick the browser into accessing some URL that does something nasty). Cookies are passed passively.
The best explaination to this question can be found on OWASP website at OWASP CSRF Prevention Cheat Sheet page.
Firstly, using cookie for a CSRF token can not help much because all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request.
Secondly, the application can include hidden input parameter in the form with a common name such as "CSRFToken". The value of this token must be randomly generated such that it cannot be guessed by an attacker.
Furthermore, Challenge-Response is another defense option for CSRF. It can be implemented in following ways:
CAPTCHA
Re-Authentication (password)
One-time Token
The CSRF cookie is certainly open to attack but implementation safe as the session value will always be checked against a submitted token value either stored in the body or header of the request so I can't see a reason against. The double submit (http only cookie vs post data) or token synchronizer (session vs post data) patterns outlined on the OWASP website are good pratices and both use cookies.
Double submit as mentioned earlier moves the storage to the client so is considered stateless but either way two tokens for comparison, of which one always remains unknown to the attacker.

GWT - Dealing with XSRF/CSRF

Am I correct, that if I pass a self-generated sessionID with every RPC request, and only check this sessionID instead of the one passed in the cookie header, the session can't be hijacked by malicious sites? I know that you should also send this sessionID in the cookie and then compare it with the one sent with every request to detect an XSRF attack but doing it my way should at least protect against XSRF attacks, doesn't it?
EDIT
I know that GWT 2.3 takes care of XSRF by providing XSRF Token Support. Sadly I'm stuck with GWT 2.2 and so have to deal with it by myself.
Yes, because the browser doesn't have enough information to convince your application that it has the right credentials. In a traditional XSRF attack the browser mechanism itself is being exploited and if it doesn't know how to send the extra information or what information to send then it just won't work.
However, with this approach, I would be aware that a malicious attacker could still compromise your self-generated sessionID and use it as soon as they figured out the mechanism.
See this wiki page on cryptographic nonce for more ideas. In using the nonce you're creating something that can only be used for that moment. Once the moment passes the data either becomes useless (in terms of a password salted with a time) or won't be accepted by the server. This is traditionally used to prevent replay attacks because, if you'll forgive me, the nonce has passed.
You might want to look at OWASP's CSRF Guard Project. They use a filter that checks every request to the server for the required CRSF Token. It's quite configurable - you can specify various aspects of your defense for ex:
URLs which don't require protection
entry point form which the CRSF Token
is to be generated (upon login)
the behaviour when a possible attack
is picked up (redirect, logging) etc
It's effectively a solution which requires no code change where the latest version also supports AJAX (RPC) calls to the server. So I believe it's definitely an option to try out (I'm currently POCing this solution for a fairly large GWT app).
Lastly I trust that you have already built your defenses against XSS. As XSRF defenses can be nullified if XSS is possible (not to mention that XSRF attacks are generally launched via XSS).