Cross Site Request forgery , Attack and Secure

Cross Site request forgery (CSRF) is an attack that forces users to do un wanted actions with out user interaction but with valid user authenticated Session .

Attacker is able to establish this attack with a help of Social Engineering to trick users to visit the malicious bad site which is responsible for executing CSRF HTML embedded code .

Exploitation Scenario

Lets consider that we have shop application written in PHP , authenticated user is able to mange his own profile settings like profile picture , address ,..etc

during intercepting the process while user delete his own items pictures , the form is submitted directly with image parameter as post request

<form id="delete" method="POST">
<input id="imgid" type="text" value="1" />
<input type="submit" />
</form>

so as we see before , executing HTML code above allows attackers to force authenticated user to delete his own image with parameter number ID with low interaction .

How To Secure against CSRF Attacks

We Can Protect Against CSRF attacks bu using tracking token sent to the user while generating / rendering Page . and sent back into browser in process of store item deletion .

there are many ways to implement CSRF token protection , but we are going to select one that doesn't require maintaining state on server side . here i am focusing on using HMAC which stands for hashing -based messaging authentication code.

HMAC take the value input and secret key to generate a fixed length output . so we can use it to generate CSRF token to validate every request .

so when a user try to submit the form again we found out that a hidden value as CSRF token generate each time the form is being requested .

<form id="delete" method="POST">
<input type="text" id="imgid" />
<input type="hidden" id="csrftoken" value="Lkh43dsdvcxx
Mn/nfhfyUikd/N6Q/OYYd=$5f/Poxfguyrhfnbv/$MUESXSRT+908/TYU=">
<input type="submit" />
</form>

and of course while loading Page , Java script code responsible to send the request by ajax is also provided on the page which will take that value of csrftoken and place it on X-CSRF-Token HTTP Header

function getitem(imgid,csrftoken) {
$.ajax({
url: "/img/delete/"+imgid,
beforesend : function (request) {
request.setrequestheader(
"X-CSRF-Token",
$("#csrftoken").val());
}
}).then( function (resp) {
$('.msg').text(resp);
});
}

the next thing to do is to make sure end point php funtion validate the the token inserted on the http header and check if is valid or not

$anticsrf = $this->request->header['X-CSRF-Token'];
$token = $this->input->get('csrftoken');
if ($token == $anticsrf ) {
//some function here to allow
else
echo("you are not allowed to do this , CSRF token is missing !");

References