https://wiki.owasp.org/api.php?action=feedcontributions&user=Akam+Omer&feedformat=atomOWASP - User contributions [en]2024-03-28T21:24:35ZUser contributionsMediaWiki 1.27.2https://wiki.owasp.org/index.php?title=PHP_CSRF_Guard&diff=161368PHP CSRF Guard2013-10-23T19:52:13Z<p>Akam Omer: </p>
<hr />
<div>=Code Snippet=<br />
'''CAUTION:''' This code snippet below is segmented intentionally. You are not supposed to copy paste this code, unless you understand its risks and how it operates. It is not verified by OWASP professional, just composed by them. Up until now two small flaws have been reported and fixed in this code. Also it uses regular expressions which are not even close to a good solution for parsing HTML ([http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags see why]), it is just there to give you an insight on what should be done. See the discussion page for more details.<br />
<br />
If you need to protect against CSRF attacks in your code, this little helper can reduce the risk:<br />
<br />
session_start(); //if you are copying this code, this line makes it work.<br />
<br />
function store_in_session($key,$value)<br />
{<br />
if (isset($_SESSION))<br />
{<br />
$_SESSION[$key]=$value;<br />
}<br />
}<br />
function unset_session($key)<br />
{<br />
$_SESSION[$key]=' ';<br />
unset($_SESSION[$key]);<br />
}<br />
function get_from_session($key)<br />
{<br />
if (isset($_SESSION))<br />
{<br />
return $_SESSION[$key];<br />
}<br />
else { return false; } //no session data, no CSRF risk<br />
}<br />
<br />
function csrfguard_generate_token($unique_form_name)<br />
{<br />
if (function_exists("hash_algos") and in_array("sha512",hash_algos()))<br />
{<br />
$token=hash("sha512",mt_rand(0,mt_getrandmax()));<br />
}<br />
else<br />
{<br />
$token=' ';<br />
for ($i=0;$i<128;++$i)<br />
{<br />
$r=mt_rand(0,35);<br />
if ($r<26)<br />
{<br />
$c=chr(ord('a')+$r);<br />
}<br />
else<br />
{ <br />
$c=chr(ord('0')+$r-26);<br />
} <br />
$token.=$c;<br />
}<br />
}<br />
store_in_session($unique_form_name,$token);<br />
return $token;<br />
}<br />
function csrfguard_validate_token($unique_form_name,$token_value)<br />
{<br />
$token=get_from_session($unique_form_name);<br />
if ($token===false)<br />
{<br />
return true;<br />
}<br />
elseif ($token===$token_value)<br />
{<br />
$result=true;<br />
}<br />
else<br />
{ <br />
$result=false;<br />
} <br />
unset_session($unique_form_name);<br />
return $result;<br />
}<br />
<br />
function csrfguard_replace_forms($form_data_html)<br />
{<br />
$count=preg_match_all("/<form(.*?)>(.*?)<\\/form>/is",$form_data_html,$matches,PREG_SET_ORDER);<br />
if (is_array($matches))<br />
{<br />
foreach ($matches as $m)<br />
{<br />
if (strpos($m[1],"nocsrf")!==false) { continue; }<br />
$name="CSRFGuard_".mt_rand(0,mt_getrandmax());<br />
$token=csrfguard_generate_token($name);<br />
$form_data_html=str_replace($m[0],<br />
"<form{$m[1]}><br />
<input type='hidden' name='CSRFName' value='{$name}' /><br />
<input type='hidden' name='CSRFToken' value='{$token}' />{$m[2]}</form>",$form_data_html);<br />
}<br />
}<br />
return $form_data_html;<br />
}<br />
<br />
function csrfguard_inject()<br />
{<br />
$data=ob_get_clean();<br />
$data=csrfguard_replace_forms($data);<br />
echo $data;<br />
}<br />
function csrfguard_start()<br />
{<br />
if (count($_POST))<br />
{<br />
if ( !isset($_POST['CSRFName']) or !isset($_POST['CSRFToken']) )<br />
{<br />
trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR); <br />
} <br />
$name =$_POST['CSRFName'];<br />
$token=$_POST['CSRFToken'];<br />
if (!csrfguard_validate_token($name, $token))<br />
{ <br />
trigger_error("Invalid CSRF token.",E_USER_ERROR);<br />
}<br />
}<br />
ob_start();<br />
/* adding double quotes for "csrfguard_inject" to prevent: <br />
Notice: Use of undefined constant csrfguard_inject - assumed 'csrfguard_inject' */<br />
register_shutdown_function("csrfguard_inject"); <br />
}<br />
csrfguard_start();<br />
<br />
=Description and Usage=<br />
The first three functions, are an abstraction over how session variables are stored. Replace them if you don't use native PHP sessions.<br />
<br />
The '''generate''' function, creates a random secure one-time CSRF token. If SHA512 is available, it is used, otherwise a 512 bit random string in the same format is generated. This function also stores the generated token under a unique name in session variable.<br />
<br />
The '''validate''' function, checks under the unique name for the token. There are three states:<br />
* Sessions not active: validate succeeds (no CSRF risk)<br />
* Token found but not the same, or token not found: validation fails<br />
* Token found and the same: validation succeeds<br />
Either case, this function removes the token from sessions, ensuring one-timeness.<br />
<br />
The '''replace''' function, receives a portion of html data, finds all <form> occurrences and adds two hidden fields to them: CSRFName and CSRFToken. If any of these forms has an attribute or value '''''nocsrf'''''', the addition won't be performed (note that using default inject and detect breaks with this).<br />
<br />
The other two functions, '''inject''' and '''start''' are a demonstration of how to use the other functions. Using output buffering on your entire output is not recommended (some libraries might dump output buffering). This default behavior, enforces CSRF tokens on all forms using POST method. It is assumed that no sensitive operations with GET method are performed in the application, as required by [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616].<br />
<br />
To test this code, append the following HTML to it:<br />
<br />
<form method='post'><br />
<input type='text' name='test' value='<?php echo "testing"?>' /><br />
<input type='submit' /><br />
</form><br />
<br />
<form class='nocsrf'><br />
</form><br />
<br />
=Author and License=<br />
This piece of code is by [mailto:abbas.naderi@owasp.org Abbas Naderi Afooshteh] from OWASP under Creative Commons 3.0 License.<br />
<br />
Contributions from Krzysztof Kotowicz <krzysztof.kotowicz at securing.pl>, Jakub Kałużny <jakub.artur.kaluzny at g></div>Akam Omerhttps://wiki.owasp.org/index.php?title=PHP_CSRF_Guard&diff=161367PHP CSRF Guard2013-10-23T19:51:33Z<p>Akam Omer: adding double quotes for "csrfguard_inject" to prevent: Notice: Use of undefined constant csrfguard_inject - assumed 'csrfguard_inject'</p>
<hr />
<div>=Code Snippet=<br />
'''CAUTION:''' This code snippet below is segmented intentionally. You are not supposed to copy paste this code, unless you understand its risks and how it operates. It is not verified by OWASP professional, just composed by them. Up until now two small flaws have been reported and fixed in this code. Also it uses regular expressions which are not even close to a good solution for parsing HTML ([http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags see why]), it is just there to give you an insight on what should be done. See the discussion page for more details.<br />
<br />
If you need to protect against CSRF attacks in your code, this little helper can reduce the risk:<br />
<br />
session_start(); //if you are copying this code, this line makes it work.<br />
<br />
function store_in_session($key,$value)<br />
{<br />
if (isset($_SESSION))<br />
{<br />
$_SESSION[$key]=$value;<br />
}<br />
}<br />
function unset_session($key)<br />
{<br />
$_SESSION[$key]=' ';<br />
unset($_SESSION[$key]);<br />
}<br />
function get_from_session($key)<br />
{<br />
if (isset($_SESSION))<br />
{<br />
return $_SESSION[$key];<br />
}<br />
else { return false; } //no session data, no CSRF risk<br />
}<br />
<br />
function csrfguard_generate_token($unique_form_name)<br />
{<br />
if (function_exists("hash_algos") and in_array("sha512",hash_algos()))<br />
{<br />
$token=hash("sha512",mt_rand(0,mt_getrandmax()));<br />
}<br />
else<br />
{<br />
$token=' ';<br />
for ($i=0;$i<128;++$i)<br />
{<br />
$r=mt_rand(0,35);<br />
if ($r<26)<br />
{<br />
$c=chr(ord('a')+$r);<br />
}<br />
else<br />
{ <br />
$c=chr(ord('0')+$r-26);<br />
} <br />
$token.=$c;<br />
}<br />
}<br />
store_in_session($unique_form_name,$token);<br />
return $token;<br />
}<br />
function csrfguard_validate_token($unique_form_name,$token_value)<br />
{<br />
$token=get_from_session($unique_form_name);<br />
if ($token===false)<br />
{<br />
return true;<br />
}<br />
elseif ($token===$token_value)<br />
{<br />
$result=true;<br />
}<br />
else<br />
{ <br />
$result=false;<br />
} <br />
unset_session($unique_form_name);<br />
return $result;<br />
}<br />
<br />
function csrfguard_replace_forms($form_data_html)<br />
{<br />
$count=preg_match_all("/<form(.*?)>(.*?)<\\/form>/is",$form_data_html,$matches,PREG_SET_ORDER);<br />
if (is_array($matches))<br />
{<br />
foreach ($matches as $m)<br />
{<br />
if (strpos($m[1],"nocsrf")!==false) { continue; }<br />
$name="CSRFGuard_".mt_rand(0,mt_getrandmax());<br />
$token=csrfguard_generate_token($name);<br />
$form_data_html=str_replace($m[0],<br />
"<form{$m[1]}><br />
<input type='hidden' name='CSRFName' value='{$name}' /><br />
<input type='hidden' name='CSRFToken' value='{$token}' />{$m[2]}</form>",$form_data_html);<br />
}<br />
}<br />
return $form_data_html;<br />
}<br />
<br />
function csrfguard_inject()<br />
{<br />
$data=ob_get_clean();<br />
$data=csrfguard_replace_forms($data);<br />
echo $data;<br />
}<br />
function csrfguard_start()<br />
{<br />
if (count($_POST))<br />
{<br />
if ( !isset($_POST['CSRFName']) or !isset($_POST['CSRFToken']) )<br />
{<br />
trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR); <br />
} <br />
$name =$_POST['CSRFName'];<br />
$token=$_POST['CSRFToken'];<br />
if (!csrfguard_validate_token($name, $token))<br />
{ <br />
trigger_error("Invalid CSRF token.",E_USER_ERROR);<br />
}<br />
}<br />
ob_start();<br />
/* adding double quotes for "csrfguard_inject" to prevent: Notice: Use of undefined constant csrfguard_inject - assumed 'csrfguard_inject' */<br />
register_shutdown_function("csrfguard_inject"); <br />
}<br />
csrfguard_start();<br />
<br />
=Description and Usage=<br />
The first three functions, are an abstraction over how session variables are stored. Replace them if you don't use native PHP sessions.<br />
<br />
The '''generate''' function, creates a random secure one-time CSRF token. If SHA512 is available, it is used, otherwise a 512 bit random string in the same format is generated. This function also stores the generated token under a unique name in session variable.<br />
<br />
The '''validate''' function, checks under the unique name for the token. There are three states:<br />
* Sessions not active: validate succeeds (no CSRF risk)<br />
* Token found but not the same, or token not found: validation fails<br />
* Token found and the same: validation succeeds<br />
Either case, this function removes the token from sessions, ensuring one-timeness.<br />
<br />
The '''replace''' function, receives a portion of html data, finds all <form> occurrences and adds two hidden fields to them: CSRFName and CSRFToken. If any of these forms has an attribute or value '''''nocsrf'''''', the addition won't be performed (note that using default inject and detect breaks with this).<br />
<br />
The other two functions, '''inject''' and '''start''' are a demonstration of how to use the other functions. Using output buffering on your entire output is not recommended (some libraries might dump output buffering). This default behavior, enforces CSRF tokens on all forms using POST method. It is assumed that no sensitive operations with GET method are performed in the application, as required by [http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 RFC 2616].<br />
<br />
To test this code, append the following HTML to it:<br />
<br />
<form method='post'><br />
<input type='text' name='test' value='<?php echo "testing"?>' /><br />
<input type='submit' /><br />
</form><br />
<br />
<form class='nocsrf'><br />
</form><br />
<br />
=Author and License=<br />
This piece of code is by [mailto:abbas.naderi@owasp.org Abbas Naderi Afooshteh] from OWASP under Creative Commons 3.0 License.<br />
<br />
Contributions from Krzysztof Kotowicz <krzysztof.kotowicz at securing.pl>, Jakub Kałużny <jakub.artur.kaluzny at g></div>Akam Omer