How to prevent Cross-site request forgery (CSRF) effectively in PHP - php

I am trying to prevent CSRF in php in the following way:
A $_SESSION['token'] is generated at the start of each page. I already know that using $_COOKIES is completely wrong since they are send automatically for each request.
In each <form>, the following input: <input type="hidden" name="t" value="<?php echo '$_SESSION['token']; ?>"> is appended.
The $_SESSION['token']; is validated with the $_POST['t']
Now I have several small questions:
Is this a good way to prevent CSRF? If not please explain.
When another page is opened as well that sets the same $_SESSION variable, the previous (still open) page becomes invalid, how to prevent this?
For forms this method is clear, but how to handle normal links? Is it necessary to append the token to each link as well?
Thank you very much in advance.

Is this a good way to prevent CSRF?
Yes. What this does is to force the client to do a GET on the form before it can do a POST to your form handler. This prevents CSRF in modern browsers since browsers will prevent client-side Javascript to do an XHR GET request to a foreign domain, so a 3rd party cannot imitate your form on their site and successfully get a valid token for the submission.
When another page is opened as well that sets the same $_SESSION variable, the previous (still open) page becomes invalid, how to prevent this?
Allow several tokens to be valid at a time, keeping an array of valid tokens in the session. Alternatively, store no tokens at all and use a token signing scheme instead. I've dabbled in and explained that here. Alternative 2: just use a single token for the whole session, without invalidating tokens. (tip o' the hat to #SilverlightFox in the comments)
For forms this method is clear, but how to handle normal links? Is it necessary to append the token to each link as well?
No. You only need to protect POST requests since presumably only POST requests can alter sensitive data (wink wink nudge nudge, you're sticking to REST conventions, right?!) and XHR GET requests are already blocked browser-side.

CSRF attack occurs when a hacker tries to send a fake request from an authenticated user. normally this attack occurs
in online shops or banks.
Prevent csrf attack in php we can:
1 = Create a check login function:
If the login session is set that is true Ok, if not false and return to login page.
2 = create a random makeToken hash function with: base64_encode(md5(microtime())) and save it into session and create a input hidden type with token name and the value with name Token's function.
3 = Create a checkTocken function and check it, if it is equall to makeToken function, and after that use unset function to unset the session, and create a new one.

Related

CSRF only needed for ajax

I have recently been working with a way to stop CSRF attacks happening by using a token. To my understanding:
1) User logs in, set session cookie to logged in and generate CSRF token and save it to the session
2) User submits form (with token) and it should match the token in session
Hypothetically lets say I have page1.php which has a sql SELECT to get all the users account information and then within the same page I also have an ajax button to page2.php which changes the account information. Obviously I protect page2.php from CSRF (because this is a post request) but how do I protect against page1.php? If this page was to get called from a remote source by ajax or putting an iframe on an attackers website, surely this would print all of the victims account information?
If this is the case how come I can't seem to find anything on protecting all pages from CSRF attacks and I only find resources for protecting against CSRF attacks in ajax?
Suppose you have a page at http://application.com/mypage with some data and a CSRF token generated. Attacker creates http://attacker.com/attack, and when a valid user of application.com visits, makes a request (either via ajax or in an iframe, doesn't matter) to application.com in order to get hold of application data. Standard csrf.
The reason this won't work for the attacker is the same origin policy. When the victim user is on attacker.com, the request to application.com will be cross-domain. If it's an iframe, data will be displayed, but attacker.com will have no access to it, it will only be displayed for the user that could have a look on application.com anyway. If it's an ajax call, the same applies, javascript on attacker.com will have no access to the response, ensured by the browser.
For ajax calls, access to cross-domain responses can be explicitly enabled by the access-control-allow-origin and related response headers (CORS) sent by application.com in the response.
Note that despite being cross-domain, the call will still be made (preflight requests come into play in some cases, but let's not go into that now). It's only the response that will be inaccessible for the attacker, and that is enough to prevent csrf.
(Also as a sidenote, application.com should prevent being displayed in an iframe by for example sending an x-frame-options: sameorigin header to prevent clickjacking and similar attacks, but that was not the question.)
I am not sure I get the point but the token for CSRF should be a nonce, which changes on each call.
Regarding a call coming from some other place, the ajax request should also check that the call comes from a valid user with the correct entitlments as you would do with any "regular" call to the site.
If this is the case how come I can't seem to find anything on
protecting all pages from CSRF attacks and I only find resources for
protecting against CSRF attacks in ajax?
What you ussually do is to set a nonce in a hidden input of the forms you use in "regular" pages.
Hypothetically lets say the page has a sql select on it and does not
request post. Now if this page was to get called from a remote source
by ajax or putting an iframe on their website, surely this would print
all of the victims data?
Make sure that all requests that hand out "confidential" information (either as a webpage or as data for an ajax call (or whatever in the future) do validate that there is a valid session active. If it's not, make sure the server side portion does not hand out anything confidential but instead throw an error and make sure your ajax client understands it and does the right thing for normal users (like telling them they're not logged in and offering them to fix that).
If this is the case how come I can't seem to find anything on
protecting all pages from CSRF attacks and I only find resources for
protecting against CSRF attacks in ajax?
For regular post requests typically the form is output with a hidden input field that holds the CSRF token. That's all.
BUT do make sure the code processing the request validates that the hidden field is present and filled in with the right value.
Also make sure that any request that modifies things is CSRF protected. E.g. that delete button in a non-ajax context should be protected with sending and validation of the CSRF token (hence the button ends up as a form with a hidden field for the CSRF.

is putting token in URL secure to prevent CSRF attacks in PHP applications?

I want to use a token to prevent CSRF attacks on my website (written with PHP). I've used it in forms and it works well. But logout link is not a form; It is only a hyperlink.
Is it secure if I put the token in the query string like this:
Logout
If it has any problem, what is your suggestions and solutions ?
Yes, if the CSRF token is 'unguessable' and validated: the approach is the same in both cases.
From Wikipedia's Cross-site Request Forgery - Prevention:
Web sites have various CSRF countermeasures available .. Requiring a secret, user-specific token in all form submissions and side-effect URLs prevents CSRF; the attacker's site cannot put the right token in its submissions.
It doesn't matter if the token is from a form value or a query string parameter1. An approach that prevents CSRF by including a token in forms is adaptable to (and valid for) hyperlinks2.
1 A MitM / proxy which can intercept a URL can just as easily intercept an HTML form. This is outside the scope of a standard CSRF attack or mitigiation of such. In such cases the CSRF token value is 'knowable' and system is not secure.
2 This assumes the token is a per-user (and time-sensitive) value. A simple HMAC hash of the Session ID should be sufficient in most cases.
I think one of main disadvantages of using CSRF-token in GET requests is possibility of incompetent user to easily disclose his token by copying a link with the token and paste it in some public content like a comment/post/etc... Also GET query parameters including CSRF-tokens usually logged by HTTP servers/proxies and it introduces another risk.
So I suggest you to implement CSRF-secure links using something like this:
<form name="logout" action="logout.php" method="post">
<input type="hidden" name="token" value="9ae328eea8a72172a2426131a6a41adb"/>
</form>
...
Logout
Others made some good points. I add this answer to augment theirs.
Always filter and validate your query string name/value pairs.
Given: You have a database and you want to create a link to help dynamically get (but not change) content that a user can link to. Example: news articles, case studies, public user profiles.
Requirement: Use a query string and deter CSRF by using a token.
One of the purposes of a CSRF token is to help verify that an incoming HTTP request was generated from a page served from your domain (regardless if sessions are in play. The session token is a separate beast). A CSRF token works best when you use more than one defense vector.
Comparison: Check that a submitted token matches one in session.
Time: You can specify a token is only good for a certain period into the future.
public function setFormToken()
{
$token = $this->cipher->getFormToken(); //Some hashing algorithm.
$this->formToken = $token; //In this example, used to insert the token into HTML.
$_SESSION['token'] = $token; //Save the token for comparison upon form submission / HTTP query string processing.
$_SESSION['tokenExpireTime'] = time() + (60 * FORM_TOKEN_EXPIRE_MINUTES); //This is just an abstract example.
return;
}
Then, in addition to comparing the submitted token to the one in session, verify that the submission period is still valid.
private function hasTokenTimeLeft()
{
if(isset($_SESSION['tokenExpireTime']) && (time() < $_SESSION['tokenExpireTime']))
{
return true;
}
throw new SecurityException("Token time has expired for this POST request.", 911);
}
Sessions: If a session has expired, or is non-existent, the a false HTTP request for your content should fail.
Request Info: With HTTP POST request, some attempt to check that the token, user agent, and IP match the one from the original HTTP GET request (which means storing it in session before responding to the GET request).
Query strings, as previously mentioned, can get cached. There is no problem with that if the data is supposed to be publicly available, anyway. Think about someone bookmarking a product on an e-commerce website.
What you have to ask yourself is "Should I be able to get to this content from anywhere, anytime, through this link with a query string?" If yes, do not use a true, backend, randomly generated, CSRF token. Imagine you are running for elected office by word of mouth and people sending links to their friends and family in email (ok, bad practice). In this case, you never want to set off a "trip wire" and cause a fail condition. If a fresh token always needs to be generated on the backend first, emailing your link around will not work.
If you should not be able to get to content from outside of your security context (i.e., before logging in), then you are free to take whatever measures are necessary to fortify your CSRF token strategy using query strings.
Your log out snippet is a perfect example.
Logout
No one from outside your security context should be able to use the logout feature. You want the "trip wire" if someone emails this link around! Obviously, sessions are integrated into this solution (the token has to be stored somewhere while the user uses the page). Session duration and logging out should be managed carefully, and I say you are doing a good job.
Encryption: The only thing you could do better is encrypt the hash/token for the query string, then decrypt it and verify it upon submission. Additionally, you can break the token up into pieces, mix the pieces up, and basically use some security by obscurity string techniques to make your CSRF token more resilient.

CSRF Token Multiple tab issue

I am implementing CSRF token in my website on every post method.
But when i am accessing my webpages in different tabs then token gets change on both pages and token mismatches.
My token is stored in DOM and i am matching token using SESSION.
How to solve this.?
i change the token on every successful request
Yeah this is why we don't invalidate the token on every successful request. That doesn't just break multi-tab browsing, it also means you can't do stuff like hit the back button then submit.
“Invalidate token on every request” is the kind of bogus security recommendation you get from pentest reports where the tester hasn't found much that's really vulnerable. It's a trade-off as always whether you do, but the usability downside almost always outweighs the minimal security benefit.
You only really need to invalidate the CSRF token (along with the session token) on a privilege level change, most notably on login. This mitigates session fixation attacks, by preventing an attacker who knows the session and CSRF tokens prior to login from exploiting those tokens after you've logged in.
You can achieve this easily:
In the server side, store the CSRF tokens in session like this:
$_SESSION['csrf_tokens']['form1'] = //code to generate csrf token
While validating the token on form submit, you can check,
$_SESSION['csrf_tokens']['form1'] === $_POST['csrf_token']
Please post an example code, unless you are using ajax (which I wouldn't recommend for CSRF tokens the code shouldn't change in both tabs if you open a new tab). Also, I disagree with bobince, you are doing the right thing to implement this measure as once you have the logic in place you can easily and effortlessly use it in all your forms. The best way to implement this is to just have each token expire after a certain amount of time.
bobince: CSRF tokes are used to prevent CSRF attacks not session fixation attacks, both are different the former prevents scripts from executing actions on behalf of the user whereas the latter is an attack in which a malicious user impersonates a normal user by guessing or stealing their session id.
Generate two values – one random key (f.e. via uniqid), and a random token.
You generate both every time a form is rendered – and put them both into hidden fields. And you save the token into the session using the random key. Then when the form data is received, you check if the token send is in the session under the key send. (And if so, you delete the entry with this key after processing the form of course.)
Anything else (f.e. expiration time of tokens, binding of tokens to a certain form type out of several) you implement the same as you would before.
is unnecessarily and unsafe like this why you dont create a token based on session with openssl_random_pseudo_bytes() ,which will produce a safe token, and check if is correct or not or you can use also to expire after 2-5 min.also you can check on owasp about tokens on dom,can be easy spoffed !!!

CSRF tokens vs Nonce confusion - are they the same?

In a attempt to make the current application I'm developing more secure, I've been reading about CSRF tokens and also Nonce.
My question simply is, Are CSRF tokens and Nonce the same thing? from what I could gather so far is that both these methods have different techniques to accomplish the same goal, or am I misunderstanding something?
If they are different, could you be nice enough to provide some example code or point me to some links where i can learn more about how to implementing nonces in PHP apps.
Thanks!
No, they're not the same.
Nonces prevent replay attacks (prevent eavesdropper from storing signed request and re-submitting it later, e.g. if Alice sends "Pay Bob $100", you don't want somebody to re-send that 100 times).
CSRF tokens patch HTML-specific weakness in authentication of users' action, where 3rd party website can submit forms with credentials of user viewing the site (e.g. JavaScript on evil.example.com submitting form to facebook.com using your browser, authenticated as you).
CSRF tokens need to be secret, otherwise attacker would have the missing piece required to forge a request.
Nonces don't have to be secret if they're signed with requester's secret (as long as attacker cannot replace one nonce with another).
You can allow replay of requests with CSRF tokens and still be secured against CSRF (you're interested whether that was intentional action by the user, but may not necessarily want to stop user from performing it many times).
In fact, that's very often useful property, e.g. allows users to use Back button and re-submit forms with corrected values. If you implement CSRF protection with Nonce-like mechanism, you'll get false alarms when users refresh submitted pages.
An easy way to prevent CSRF without Nonces is to put session ID in a hidden from field (not a value stored in the session, but ID of the session itself, the same that you store in the cookie [session_id() in PHP]). When the form is submitted check that form's session ID matches ID in the cookie. That is enough for CSRF, since attacker cannot know value of the cookie (CSRF only allows attackers to blindly send cookies).
Nonce is usually some random string that is added to request just to change in unpredictable way the data, which is used to calculate the signature. So nonce usually is not used by any server-side business logic.
While CSRF-token is stored somewhere on server, passed to the client and need to be returned back to the server to compare. And if matches - then OK.
So in your case the better will be to save csrf token once in a session variable like
$_SESSION['csrf_token'] = bin2hex(random_bytes(16));
and use it unchanged during the session life in all forms you have in your application.
(If you don't have random_bytes(), use random_compat to polyfill it.)
It's sort of the same thing. A "nonce" is just a one-time password itself. It can serve as cryptographic salt, but basically is just a random value. See WP:Nonce
But to sum it up, a nonce is often used as CSRF token. It's an implementation detail. The difference to other use cases is that it later gets asserted.
CSRF having some limitation.
in case if you have requirement where you want to open any page or link in new tab then CSRF won't allow. existing token will allow to open page in new tab for 5 times only.
when you will try to open 6th time it will create the new token which will not match with "server side = client side token". earlier token will expire and new token(NONCE) will create, in that case you will get 404 or 405 error.

security token problem with ajax requests

when building apps I use a token to prevent attacks on the forms
each time a form is rendered it gets a new ONE TIME security token that i include in the form as a hidden field. this token is also stored in the session.
when the form is sent, the token is verified against the token in the session to make sure the form is legit. This works great for standard pages.
PROBLEM
when using Ajax to send forms, there may be multiple on a page, once you send one of these forms, the token is then invalid for the others as its a one time token.
does anyone have advise for this? or is it secure enough to generate one token per session and just use that instead of invalidating the token each time a form is sent?
If you want to follow your current approach, you can generate a security token each time you do a an AJAX request, return it in the AJAX response, and inject it into the hidden when you get it.
However, I'd go rethinking your current approach for security tokens. Here you have some tips about that in the OSWAP wiki.

Categories