0
0
PHPprogramming~10 mins

CSRF attacks and token protection in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to start a session in PHP.

PHP
<?php
[1];
?>
Drag options to blanks, or click blank then click option'
Asession_start()
Bstart_session()
Csession()
Dbegin_session()
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function name that does not exist like start_session()
Forgetting the parentheses () after the function name
2fill in blank
medium

Complete the code to generate a CSRF token using PHP's random_bytes function.

PHP
<?php
$token = bin2hex([1](32));
?>
Drag options to blanks, or click blank then click option'
Arandom_bytes
Bmt_rand
Crandom_int
Dopenssl_random_pseudo_bytes
Attempts:
3 left
💡 Hint
Common Mistakes
Using random_int which returns integers, not bytes
Using mt_rand which is not cryptographically secure
3fill in blank
hard

Fix the error in the code that checks if the CSRF token from POST matches the session token.

PHP
<?php
if (isset($_POST['csrf_token']) && hash_equals($_SESSION['csrf_token'], [1])) {
    // Valid token
}
?>
Drag options to blanks, or click blank then click option'
A$_COOKIE['csrf_token']
B$_GET['csrf_token']
C$_SESSION['csrf_token']
D$_POST['csrf_token']
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing the session token to itself
Using $_GET or $_COOKIE instead of $_POST
4fill in blank
hard

Fill both blanks to create a hidden input field in an HTML form that sends the CSRF token stored in PHP session.

PHP
<input type="hidden" name="csrf_token" value="<?php echo [1]; ?>">
<?php echo [2]; ?>
Drag options to blanks, or click blank then click option'
A$_SESSION['csrf_token']
B$token
Chtmlspecialchars($token)
Dhtmlspecialchars($_SESSION['csrf_token'])
Attempts:
3 left
💡 Hint
Common Mistakes
Not escaping the token before output
Using a variable that is not defined
5fill in blank
hard

Fill all three blanks to store a new CSRF token in session, generate it securely, and include it in a form.

PHP
<?php
session_start();
$_SESSION['csrf_token'] = [1];
?>
<form method="post">
  <input type="hidden" name="csrf_token" value="<?php echo [2]; ?>">
  <button type="submit">Submit</button>
</form>
<?php
echo [3];
?>
Drag options to blanks, or click blank then click option'
Abin2hex(random_bytes(16))
Bhtmlspecialchars($_SESSION['csrf_token'])
C$_SESSION['csrf_token']
Drandom_bytes(16)
Attempts:
3 left
💡 Hint
Common Mistakes
Not generating the token securely
Not escaping output when echoing
Using the wrong variable in the form value