The CSRF prevention method of using a token on the form for each session is a popular way. However, I don't get how this token way can protect if the file_get_contents
of PHP can get contents of cross domain file form --> it can get the token on the form and use it also.
So how does this token way work?
If I understand your question well, you are imagining a possible exploit like this :
- Attacker creates a PHP page that will present a fake form to a target user
Attacker's PHP script will do a file_get_contents
to download a form(HTML) from target site he is trying to exploit, and scrap out the CSRF token from downloaded HTML, and add this CSRF token inside the fake form presented to the user.
Unsuspecting user will submit the form and an unintended request will be executed in target site with in the context of this user's session.
The CSRF check in target site will pass OK because we have a valid CSRF token in our request
But wait.. do we have a valid token? do we really!
Not if the target site implements CSRF check the right way.
The session is the key here. When you execute file_get_contents
to download a form from target site the request executes in the context of a session of its own, the file_get_contents
process is the client there, and the CSRF token generated for that request will be(must be) valid only with in context of that particular session.
Later, when the target user submits your fake form that request that request executes with in the context of that user's session which is different from the file_get_contents
session, and thus the CSRK token will be rejected if the CSRF check is implemented by the target site in a proper way.
Here is a good article from OWASP to understand more about the recommended Synchronizer Token Pattern for prevention of CSRF