Home > Uncategorized > Simple #CSRF protection in PHP

Simple #CSRF protection in PHP

CSRF of Cross Site Request Forgery is like a layer of security that you can apply to your site that protects adequately against simple attacks on your website. It’s weak security against bot attacks, but when combined with a properly configured CDN, it does help a little.

Think of it like a plastic padlock. It’s enough to stop a light fingered kid, but not enough to stop anyone who really wants to steal your stuff.

Anyway, here’s a simple CSRF script for PHP. It’s not standardised, so anyone who sees it, has to figure it out (or read this post).

First, on the Javascript side, add the code;

  var _0x1933=["","\x6A\x6F\x69\x6E","\x6D\x61\x74\x63\x68","\x75\x73\x65\x72\x41\x67\x65\x6E\x74"];
  var csrf = navigator[_0x1933[3]][_0x1933[2]](/\d+/g)[_0x1933[1]](_0x1933[0]);

Post the CSRF along with your AJAX request, and then on the PHP side add the check;

  $csrf = $_GET["csrf"];
  $ua = $_SERVER['HTTP_USER_AGENT'];
  preg_match_all('!\d!', $ua, $matches);
  $csrfCheck = implode($matches[0]);
  if ($csrf == "" || $ua == "" || $csrfCheck != $csrf) die('csrf mismatch');

What does it do? – well it’s rather cryptic on the JS side, but on the PHP side, you can see that it is just the numerical part of the User Agent, which can be read by both client and server without any modification.

Again, If I did not have to restate this again. This is weak protection, but it may frustrate a would be attacker just enough to make him move along to the next victim, and leave you alone.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: