PHP

SIMPLE CSRF TOKEN PROTECTION IN PHP

(quick guide & example)

CSRF = Cross-Site Request Forgery.

When there are 2 sites - Legit and bad.

Bad website masquerades as the good one, to bait users into doing a forged request on the legit site.

WHAT IS CSRF?

1A

DELETE ACCOUNT FORM ON LEGIT SITE

CSRF ATTACK EXAMPLE A

1B

<form action="http://site.com/delete/">   <p>Type "CONFIRM" to proceed.</p>    <input type="text" name="confirm">    <input type="submit" value="Go">  </form>

FAKE FORM ON BAD WEBSITE THAT DELETES ACCOUNT ON LEGIT SITE

CSRF ATTACK EXAMPLE B

1C

<form action="http://site.com/delete/">   <p>CLICK TO REDEEM PRIZE!</p>    <input type="hidden" name="confirm"   value="CONFIRM">    <input type="submit" value="WIN!">  </form>

GENERATE RANDOM TOKEN session_start(); $_SESSION["token"] = bin2hex(random_bytes(32)); $_SESSION["expire"] = time() + 3600;

CSRF ATTACK PREVENTION

2A

EMBED TOKEN INTO FORM <form method="post">   <input type="hidden" name="token"   value="<?=$_SESSION["token"]?>">    <input type="email" name="email">   <input type="submit" value="Go!"> </form>

CSRF ATTACK PREVENTION

2B

CHECK TOKEN if (isset($_POST["token"]) &&    isset($_SESSION["token"]) &&    isset($_SESSION["expire"]) &&    $_SESSION["token"]==$_POST["token"]) {

  EXPIRED?   if (time()>=$_SESSION["expire"]) { exit(); }

  PROCEED   unset($_SESSION["token"]);    unset($_SESSION["expire"]);   echo "OK"; }