Pink Code Pink Code - 5 months ago 35
PHP Question

php prevent csrf attacks in mutiple submit

I work with this PHP class for prevent CSRF from attack.

CODE:

$token = NoCSRF::generate( 'csrf_token' );

<form name="csrf_form" action="#" method="post">
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
...Other form inputs...
<input type="submit" value="Send form">
</form>


for check csrf:

try
{
// Run CSRF check, on POST data, in exception mode, with a validity of 10 minutes, in one-time mode.
NoCSRF::check( 'csrf_token', $_POST, true, 60*10, false );
// form parsing, DB inserts, etc.
}
catch ( Exception $e )
{
// CSRF attack detected
}


this worked for me when i have one from in my page But when i have two form in my page only work with one form and in other form submit always show
CSRF attack detected
.

php check FORM 1:

if($_POST['submit'] == "from") && !empty($_POST['username'])){

try
{
// Run CSRF check, on POST data, in exception mode, with a validity of 10 minutes, in one-time mode.
NoCSRF::check( 'csrf_token', $_POST, true, 60*10, false );
// form parsing, DB inserts, etc.
}
catch ( Exception $e )
{
// CSRF attack detected
}
}


php check FORM 2:

if($_POST['submit'] == "from2") && !empty($_POST['username'])){

try
{
// Run CSRF check, on POST data, in exception mode, with a validity of 10 minutes, in one-time mode.
NoCSRF::check( 'csrf_token', $_POST, true, 60*10, false );
// form parsing, DB inserts, etc.
}
catch ( Exception $e )
{
// CSRF attack detected
}
}


HTML FORM:

<form name="csrf_form" action="#" method="post">
<?PHP $token = NoCSRF::generate( 'csrf_token' );?>
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
<input type="text" name="username">
<input type="submit" value="form">
</form>
<form name="csrf_form" action="#" method="post">
<?PHP $token = NoCSRF::generate( 'csrf_token' );?>
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
<input type="text" name="badname">
<input type="submit" value="form2">
</form>


how do fix this OR how do work this class for multiple form?!

class source here

Answer

Make sure that you are only calling NoCSRF::generate() once. If it's called more than once, data for the old token will be overwritten, making it invalid.

Alternatively, use a different key for the two tokens (instead of using "csrf_token" for both).