I believe this post answers your updated question:
Due to the same origin policy, the attacker cannot access the cookie. But the browser will add a cookie to the POST request anyway, as you mentioned. For this reason, you must also set the CSRF token from the code (for example, in a hidden field). In this case, the attacker must know the value of the CSRF token as stored in the victim's cookie at the time the malicious form was created. Since it cannot access the cookie, it cannot reproduce the token in its malicious code, and the attack failed.
Now you can imagine other ways of storing a token than in a cookie. The fact is that an attacker cannot get it. And the server should have a way to check it. You can imagine storing a token with a server-side session and storing a token on some “safe” path on the client side (“safe”, which means that an attacker cannot access it).
Here is a quote from OWASP:
In general, developers only need to generate this token once for the current session. After the initial generation of this token, the value is stored in the session and is used for each subsequent request until the session expires. When the request is issued by the end user, the server component must check the availability and validity of the token in the request compared to the token found in the session . If the token was not found in the request or the provided value does not match the value in the session, then the request must be aborted, the token must be reset, and the event is recorded as a potential CSRF attack.
After all, security requires two things:
- The CSRF toner must be sent from the code, which means that the malicious code must know it.
- The CSRF icon should be stored in some “safe” place for comparison (a cookie is convenient for this ).
I am not an expert, but this is my understanding of the problem. Hope this helps.
Jonesv
source share