Search code examples
laravelcsrf

Does Laravel CSRF protection provide 100% safety?


Laravel documentation says:

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application. Since this token is stored in the user's session and changes each time the session is regenerated, a malicious application is unable to access it.

Laravel config session.php file guarantees session cookie lifetime is 120 minutes by default:

'lifetime' => env('SESSION_LIFETIME', 120)

So let's imagine, for example, I authenticate into the Laravel app and receive session cookies. What will happen if within 120 minutes after authentication I will go to a malicious website and get exposed to CSRF attack? Of course, considering the fact cors.php config is set to allow accept any (*) origin ('allowed_origins' => ['*']).

In my current understanding within these 120 minutes after authentication browser has the session cookie, so if I go to a malicious website and get exposed to CSRF attack, the attack will be successful.

Please correct me if my current understanding is wrong?


Solution

  • So the problem with my understanding was that I was not aware of the fact you can't access a cookie of the origin that differs from website you are trying to access it. So in case of csrf, origin of malicious website differs from the origin of CSRF-TOKEN cookie which is provided by Laravel server, therefore attacks fails. So yeah laravel csrf protection works.

    Full explanation of CSRF protection to the beginners as myself:

    1. What is csrf attack? Imagine, you authenticated into website with domain A, and received the session cookie from server that serves the site A. Annother malicious website with domain B contains a script which produce a request to the server which serves domain A as you enter the site B. As long your browser contains the session cookie of website A, the script attempting to attack from website B will be successful.
    2. So how does csrf token help to cover this vulnerability? Now laravel server sends you response with XSRF-TOKEN cookie, when you try to send axios request with script from domain A, axios automatically places value of XSRF-TOKEN to X-XSRF-TOKEN header in case of same-origin request (when website A has domain of the same origin as the server). In case of malicious website with non same-origin request, script can't access the XSRF-TOKEN cookie because it is not possible to accesss a cookie of another origin. So axios can't place a value of XSRF-TOKEN to a requst header or a request parameter. Server examines incoming request for X-XSRF-TOKEN or csrf token parameter, server is not able to find it, and so therefore server doesn't validate the request.