Form Token when Submit for Cross Platform Security ( Like CSRF )

basic PHP function to generate and validate CSRF tokens Code

28

Arun Kr.
08-Jun-24
<?php

function generate_csrf_token() {
	if (session_status() == PHP_SESSION_NONE) {
		session_start();
	}

// Generate a random token
	$token = bin2hex(random_bytes(32));

// Store the token in the session
	$_SESSION['csrf_token'] = $token;

	return $token;
}

function validate_csrf_token($token) {
	if (session_status() == PHP_SESSION_NONE) {
		session_start();
	}

// Check if the token exists in the session
	if (isset($_SESSION['csrf_token']) && $_SESSION['csrf_token'] === $token) {
// Token is valid, unset it to prevent replay attacks
		unset($_SESSION['csrf_token']);
		return true;
	}

	return false;
}

?>

Generate a token and include it in your form: 

<?php
	session_start();
	$csrf_token = generate_csrf_token();
?>

<form method="post" action="/submit">

	<!-- Other form fields -->
	<input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
	<button type="submit">Submit</button>

</form>

Validate the token on form submission: 

<?php

session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Validate CSRF token
	$csrf_token = $_POST['csrf_token'];
	if (!validate_csrf_token($csrf_token)) 
	{
		die("CSRF token validation failed.");
	}

// Process form data

// ...

}

?>

This code provides a basic implementation of CSRF protection using PHP sessions. Remember to include  session_start() at the beginning of your scripts if sessions are not already started. Also, consider adding additional security measures such as HTTPS, securing session cookies, and using other security headers to enhance protection further.

More Information  

Certainly! Let's break down the PHP functions and their usage:

1. **generate_csrf_token() Function**: 

- This function is responsible for generating a CSRF token.

- It starts a session if one isn't already active using `session_start()`.

- Generates a random token using `random_bytes()` function, which is then converted to hexadecimal format using `bin2hex()`.

- Stores the generated token in the session variable `$_SESSION['csrf_token']`.

- Finally, it returns the generated token.

2. **validate_csrf_token() Function**: 

- This function validates the submitted CSRF token against the token stored in the session.

- Similar to `generate_csrf_token()`, it starts a session if one isn't already active.

- It checks if the submitted token matches the token stored in the session (`$_SESSION['csrf_token']`).

- If the tokens match, it returns `true`, indicating the token is valid. It also unsets the token from the session to prevent replay attacks.

- If the tokens don't match or if the token is missing from the session, it returns `false`, indicating the token is invalid.

3. **Form Usage**: 

- When rendering a form, the PHP code calls `generate_csrf_token()` to generate a token.

- The generated token is then inserted into a hidden input field within the form.

- When the form is submitted, the CSRF token is sent along with the form data.

- On the server side, when processing the form submission (`$_SERVER["REQUEST_METHOD"] == "POST"`), the PHP code retrieves the submitted token.

- It then calls `validate_csrf_token()` to validate the token. If the token is valid, the form submission is considered legitimate, and the server can proceed with processing the form data. Otherwise, it indicates a CSRF attack.

4. **Security Considerations**: 

- These functions provide basic CSRF protection by generating and validating tokens. However, ensure that your entire application is secure by implementing other security measures such as using HTTPS, securing session cookies, and applying additional security headers.

- Regularly review and update your application's security practices to address new threats and vulnerabilities.

@Since 2024 Arun'Log Powered by Arun Git