1

I was reading up on some PHP PDO data sanitization, and came accross this post:

PDO & Sanitize Date/Remove HTML

I'm confident that my code uses PDOStatement bindParam to prevent SQL Injections, However i read this comment ( paraphrased )

'using $_POST with tokens will help to avoid CSRF'

and I am curious, what is meant by a token and how do I implement it?

Community
  • 1
  • 1
AlexMorley-Finch
  • 6,785
  • 15
  • 68
  • 103
  • 3
    @Melvin OP asked a very specific question and all you can provide is a LMGTFY for "CSRF" hidden behind a URL shortening service? –  Jul 12 '12 at 22:53
  • CRSF is a very specific topic, searching google would give you not only in-depth information but also tutorials on how to protect your forms. The poster is just curious on how to implement it, he is not having any troubles actually implementing it, which is exactly the kind of information you can find on the internet very easily yourself. Take wikipedia for example, im sure it'll be in the top 3 in the search results and it covers almost everything you need to know to understand the concept behind CSRF. I also just could've dropped a wikipedia link here but i think this was more appropriate. – Melvin Jul 12 '12 at 23:29
  • My question was more along the lines of 'What is a token', not really about CRSF – AlexMorley-Finch Jul 12 '12 at 23:36
  • If you understand the idea behind CRSF then you know a token can be anything you want as long as it has some kind of randomness in it. A token does not need to be cryptographly secure as it does not contain any sensitive information. – Melvin Jul 12 '12 at 23:45

1 Answers1

0

A token may be some hash, you store it in a session and also send it with via the form. Before validating the form-data you check if:

  1. a token has been sended and
  2. the token is stored in the session

A simple implementation:


<?php
  session_start();
  if(!isset($_SESSION['token']))
  {
    $_SESSION['token']=uniqid();
  }
?>

<form method="post">
    <input name="token" type="hidden" value="<?php echo $_SESSION['token'];?>">
    <input name="something"  value="some data to send">
    <input type="submit">
</form>

<?php
  if(isset($_POST['something']))
  {
    if(!isset($_POST['token']) || $_POST['token']!==$_SESSION['token'])
    {
      echo 'missing a valid token';
    }
    else
    {
      echo 'got a valid token, I will use the data';
    }
  }
?>

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • 1
    and how exactly does this prevent cross site scripting? I just want to understand it, not just accept it:) – AlexMorley-Finch Jul 12 '12 at 22:48
  • CSRF is not Cross-Site-Scripting, see http://en.wikipedia.org/wiki/Cross-site_request_forgery . Simple example: Assume you are logged-In somewhere, and there is a simple logout-page. Without a token anybody may place a form or a link on any page, when you use it, you are logged out(of course the "attacker" wouldn't tell you that you will logout). – Dr.Molle Jul 12 '12 at 23:00