Prevention of CSRF for Web Security
Cross Site Request Forgery (Cross-Site Request Forgery) is a type of network attack, the attack can send a request in the name of the victim to the attacked site without the victim's knowledge, so that the operation under the permission protection is performed without authorization, it is harmful.
Php csrf Guard
function csrfguard_generate_token($unique_form_name){if (function_exists("hash_algos") and in_array("sha512",hash_algos())){$token=hash("sha512",mt_rand(0,mt_getrandmax()));}else{$token=' ';for ($i=0;$i<128;++$i){$r=mt_rand(0,35);if ($r<26){$c=chr(ord('a')+$r);}else{ $c=chr(ord('0')+$r-26);} $token.=$c;}}store_in_session($unique_form_name,$token);return $token;}function csrfguard_validate_token($unique_form_name,$token_value){$token=get_from_session($unique_form_name);if ($token===false){return false;}elseif ($token===$token_value){$result=true;}else{ $result=false;} unset_session($unique_form_name);return $result;}function csrfguard_replace_forms($form_data_html){$count=preg_match_all("/<form(.*?)>(.*?)<\\/form>/is",$form_data_html,$matches,PREG_SET_ORDER);if (is_array($matches)){foreach ($matches as $m){if (strpos($m[1],"nocsrf")!==false) { continue; }$name="CSRFGuard_".mt_rand(0,mt_getrandmax());$token=csrfguard_generate_token($name);$form_data_html=str_replace($m[0],"<form{$m[1]}><input type='hidden' name='CSRFName' value='{$name}' /><input type='hidden' name='CSRFToken' value='{$token}' />{$m[2]}</form>",$form_data_html);}}return $form_data_html;}function csrfguard_inject(){$data=ob_get_clean();$data=csrfguard_replace_forms($data);echo $data;}function csrfguard_start(){if (count($_POST)){if ( !isset($_POST['CSRFName']) or !isset($_POST['CSRFToken']) ){trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);} $name =$_POST['CSRFName'];$token=$_POST['CSRFToken'];if (!csrfguard_validate_token($name, $token)){ trigger_error("Invalid CSRF token.",E_USER_ERROR);}}ob_start();/* adding double quotes for "csrfguard_inject" to prevent: Notice: Use of undefined constant csrfguard_inject - assumed 'csrfguard_inject' */register_shutdown_function("csrfguard_inject");}csrfguard_start();
The first three functions are abstract concepts about how to store session variables. If you do not use PHP session replacement. Creates a random security one-time CSRF token. If SHA512 is available, it is used. Otherwise, a 512-bit random string is generated in the same format. This function will also generate a token with a unique name in the session variable. Verify the token. There are three steps:
Failed session: Verification Successful (no risk of CSRF)
Session discovery but not the same, or token not found: Verification Failed
Session discovery is the same: Verification Successful
In any case, this function deletes the session token to ensure that one example
The replacement function receives part of HTML data, discovers all <form> events, and adds two hidden domains: csrfname and csrftoken. If any of these forms has an attribute or value of nocsrf, it will not be executed except (note that the default injection time is used for this detection ).
The other two functions will start with a demonstration of how to use other functions. Using the output buffer is not recommended for your entire output (some libraries may dump the output buffer ). By default, the POST method is used to execute the CSRF token in all forms. It is assumed that no sensitive operation method is executed in the application, as required by RFC 2616
To test the code, add the following HTML:
<form method='post'><input type='text' name='test' value='<?php echo "testing"?>' /><input type='submit' /></form><form class='nocsrf'></form>