Search code examples
phpcsrf

PHP: CSRF prevention, checking for remote addess


I am writing a PHP class for CSRF prevention.

The class can generate CSRF tokens, and later check them, but I would to also verify -as an extra - if the request comes from the same browser ($_SERVER['HTTP_USER_AGENT']), and the same IP ($_SERVER['REMOTE_ADDR']). I know that some users may have dynamic IP addresses, and these addresses can change. So my question is: it is possible that a user's IP address to change between 2 requests? Should I also check for $_SERVER['REMOTE_ADDR'] or only the user agent?


Solution

  • The IP address is unreliable for anti-CSRF because it can change frequently which will make your web application unusable for those users. AOL is an example of an ISP that has been known to switch IPs between requests.

    The user-agent is again not very reliable. This can also change because it usually contains software version details and sometimes names of installed software or plugins. Also consider that the user agent is sent in the same place as the session ID cookie (within the HTTP request) so if an attacker is able to obtain the session ID, then it's likely that they already have or can obtain the associated user-agent.

    The best form is CSRF protection is to generate tokens to be checked when actions are performed. Ideally the token should change throughout the session and not remain static.