Cross Site Request Forgery(CSRF)

Cross Site Request Forgery or CSRF is an attack that forces a malicious action to an innocent website.

A cross-site request forgery (CSRF) vulnerability occurs when:
1. A Web application uses session cookies.
2. The application acts on an HTTP request without verifying that the request was made with the user’s consent.

Imagine a Web application
that allows administrators to create new accounts by submitting this form:

<form method="POST" action="/new_user.php" name="usr_form">
	Name of new user:
	<input type="text" name=”username”>
	Password for new user:
	<input type="password" name="user_passwd">
	<input type="submit" name="action" value="Create User">
</form>

An attacker might set up a Web site with the following:

<form method="POST" action="http://www.example.com/new_user.php" name="usr_form">
	<input type="hidden" name="username" value="hacker">
	<input type="hidden" name="user_passwd" value="hacked">
</form>
<script>
	document.usr_form.submit();
</script>

If an administrator for example.com visits the malicious page while she has an active session on the site, she will unwittingly create an account for the attacker.This is a CSRF attack.

Recommendations:
Applications that use session cookies must include some piece of information in every form post that the back-end code can use to validate the provenance of the request.
Firstly create random value and put into session
$_SESSION[‘token’]=md5(uniqid(mt_rand(), true));

<form method="POST" action="/new_user.php" name="usr_form">
	Name of new user:
	<input type="text" name="username">
	Password for new user:
	<input type="password" name="user_passwd">
	<input type="hidden" name="csrf" id="csrf" value="<?php echo $_SESSION['token'];?>" />
	<input type="submit" name="action" value="Create User">
</form>

Now newuser.php

if (isset($_POST['action']) && $_REQUEST['csrf'] == $_SESSION['token']) {
//put add user code here
}