PHP form token usage and handling

dave picture dave · Jan 9, 2010 · Viewed 43.5k times · Source

I'm a beginner working on a login script in PHP. This is the form token statement that I have so far:

$_SESSION["form_token"] = md5(rand(time (), true)) ;

The statement is issued just after the user indicates that he/she wants to login.

My limited understanding is that the tokens purpose is to identify a unique user at a unique point in time and to disguise the form token information.

Then everything becomes fuzzy. Here are my 3 open questions:

  1. When is the best time to "check" the form token for security purposes?

  2. How do I check it?

  3. When, if ever, do I "destroy" the form token? (IOW, would the form token stay "active" until the user logs out?

Answer

jspcal picture jspcal · Jan 9, 2010

this is to prevent CSRF attacks

http://en.wikipedia.org/wiki/Cross-site_request_forgery

a malicious site could theoretically display a form that posts to your application. the form might contain instructions that cause a data breach or some unwanted action. the user might be deceived into submitting the form which the app would accept because the user is already logged in. a form token ensures the form was created by your site and not some other site.

checking the HTTP_REFERER is often good enough, but not as complete a solution (https for instance won't send the referrer string).

if you really want to secure all forms with a token, you can create some convenience functions like emitToken() and checkToken() that will make it work site-wide.

some examples:

http://phpsec.org/projects/guide/2.html

http://www.rodsdot.com/php/CSRF_Form_Protection.php