PHP

SIMPLE CSRF TOKEN PROTECTION IN PHP

* CSRF = Cross-Site Request Forgery.

* When there are 2 websites - A legit and bad one.

* 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 HTML FORM ON LEGIT SITE <form method="post"    action="http://site.com/delete/">   <p>Type "CONFIRM" to proceed.</p>    <input type="text" name="confirm"/>    <input type="submit" value="Go"/>  </form>

CSRF ATTACK EXAMPLE A

1B

FAKE FORM ON BAD WEBSITE THAT DELETES ACCOUNT ON LEGIT SITE <form method="post"   action="http://site.com/delete/">   <p>CLICK TO REDEEM PRIZE!</p>    <input type="hidden"                     name="confirm"               value="DELETE"/>    <input type="submit" value="WIN!"/>  </form>

CSRF ATTACK EXAMPLE B

1C

GENERATE RANDOM TOKEN, VALID FOR 1 HR (3600 SECS) session_start(); $_SESSION["tkn"] =    bin2hex(random_bytes(32)); $_SESSION["tknexp"] =   time() + 3600;

CSRF ATTACK PREVENTION

2A

EMBED TOKEN INTO FORM <form method="post">   <input type="hidden" name="tkn"     value="<?=$_SESSION["tkn"]?>"/>    <input type="email" name="email"     value="jon@doe.com"/>   <input type="submit" value="Go!"/> </form>

CSRF ATTACK PREVENTION

2B

CHECK TOKEN ON FORM SUBMIT session_start(); if (!isset($_POST["tkn"]) ||      !isset($_SESSION["tkn"]) ||      !isset($_SESSION["tknexp"]))   { exit("Token is not set!"); }

CSRF ATTACK PREVENTION

2C

CHECK AGAINST SESSION if ($_SESSION["tkn"]==$_POST["tkn"]) {   EXPIRED   if (time() >= $_SESSION["tknexp"])     { exit("Token expired."); }   PROCEED - DO PROCESSING   else {     unset($_SESSION['token']);      unset($_SESSION['token-expire']);   } } else { exit("INVALID TOKEN"); }