Good night, there is such code in the login.php file:

if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) { if ( !isset( $_SESSION[ 'csrf' ] ) || $_SESSION[ 'csrf' ] !== $_POST[ 'csrf' ] ) throw new RuntimeException( 'CSRF attack' ); } $key = sha1( microtime() ); $_SESSION[ 'csrf' ] = $key; 

Because of this code, the following error is generated in the logs:

PHP Fatal error: Uncaught exception 'RuntimeException' with message 'CSRF attack' in /var/www/login.php:26\nStack trace: \ n # 0 {thrown in /var/www/login.php on line 26, referer: www.travianx5.ru/login.php

Can you explain what the above code does? And how do I get rid of this error?

  • in all forms, add a field with "csrf" and record $ _SESSION ['csrf'] from the session there - IVsevolod

2 answers 2

The above code just causes an error. Your condition says "If there is no csrf session, or the csrf session is not equal to POST from csrf, then we cause a RuntimeException error with the message 'CSRF attack'"

And then a key is written to the session, which, for sure, is not equal to POST from csrf. This is the condition that works.

To get rid of, it is necessary to erase all this:

 if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) { if ( !isset( $_SESSION[ 'csrf' ] ) || $_SESSION[ 'csrf' ] !== $_POST[ 'csrf' ] ) throw new RuntimeException( 'CSRF attack' ); } 

    This is a protection against CSRF attacks , which blocks the request if it does not contain the correct CSRF value (here it is just a hash of time) that allows you to protect against a specific type of automated requests. CSRF-protection is put down simultaneously in the form and in the session, and the action is performed only if the values ​​from the incoming form and session match. You obviously have either the form does not include the CSRF, or you somehow did not send all the data.

    There are two ways to get rid of it: sort out what the form gives out (and make sure that the form contains the same thing as the session), or cut the whole piece of code to hell. I wouldn’t call protection in the form of a hash in time, it just increases the complexity (even if it is necessary to adjust it to the nearest microsecond), a sort of pseudo-GSBR. Although still better than nothing.