Skip to content

Instantly share code, notes, and snippets.

@ziadoz ziadoz/index.php
Last active Nov 24, 2019

Embed
What would you like to do?
Simple PHP / jQuery CSRF Protection
<?php
// See: http://blog.ircmaxell.com/2013/02/preventing-csrf-attacks.html
// Start a session (which should use cookies over HTTP only).
session_start();
// Create a new CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>PHP CSRF Protection</title>
<script>
window.csrf = { csrf_token: '<?php echo $_SESSION['csrf_token']; ?>' };
$.ajaxSetup({
data: window.csrf
});
$(document).ready(function() {
// CSRF token is now automatically merged in AJAX request data.
$.post('/awesome/ajax/url', { foo: 'bar' }, function(data) {
console.log(data);
});
});
</script>
</head>
<body>
<form action="index.php" method="post" accept-charset="utf-8">
<input type="text" name="foo" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
@energylevels

This comment has been minimized.

Copy link

energylevels commented Jan 8, 2016

I'm not using JQuery Library, how to send CSRF token in standard Javascript ?? ... Thanks

@pvictorlv

This comment has been minimized.

Copy link

pvictorlv commented Aug 10, 2016

thank you!

@ao

This comment has been minimized.

Copy link

ao commented Sep 17, 2016

Simple and effective, thanks!

@sinkaszab

This comment has been minimized.

Copy link

sinkaszab commented Sep 24, 2016

Maybe I am wrong, but:

  • If I can steal your cookie => I can steal your session (Session will set a session cookie, that's how you are connected to a server session, remember?)
  • If I can steal your session, I can steal your "hidden" token.

Instead

  • Regenerate session_id on a regular basis.
  • Delete obsolete sessions so that they cannot be revived.

I would not suggest relying on this code to anyone.

Some starting point

http://eddmann.com/posts/securing-sessions-in-php/

http://resources.infosecinstitute.com/fixing-csrf-vulnerability-in-php-application/

@idangoldman

This comment has been minimized.

Copy link

idangoldman commented Feb 28, 2017

@sinkaszab your starting points are using session cookies....

@ziadoz, thanks looks good! :)

@AlekseyKorzun

This comment has been minimized.

Copy link

AlekseyKorzun commented Apr 21, 2018

This implementation is missing a big security feature. The token must be cleared post validation, you can achieve that by executing unset($_SESSION['csrf_token']).

@sinkaszab your concerns are valid but what you are referring to is usually done upon privilege escalation. This doesn't apply here since the token is one-time use.

@AkinOlawale

This comment has been minimized.

Copy link

AkinOlawale commented Jul 19, 2018

also you should use php's hash_equals to compare. Do not use ==. This is to prevent the timing attack

@banujan6

This comment has been minimized.

@hdyangy

This comment has been minimized.

Copy link

hdyangy commented Aug 22, 2018

thank you

@OscarKolsrud

This comment has been minimized.

Copy link

OscarKolsrud commented Mar 10, 2019

Maybe I am wrong, but:

  • If I can steal your cookie => I can steal your session (Session will set a session cookie, that's how you are connected to a server session, remember?)
  • If I can steal your session, I can steal your "hidden" token.

Instead

  • Regenerate session_id on a regular basis.
  • Delete obsolete sessions so that they cannot be revived.

I would not suggest relying on this code to anyone.

Some starting point

http://eddmann.com/posts/securing-sessions-in-php/

http://resources.infosecinstitute.com/fixing-csrf-vulnerability-in-php-application/

This is most likely a problem if you use correct time out of PHP sessions.

@omidgfx

This comment has been minimized.

Copy link

omidgfx commented Sep 25, 2019

Maybe I am wrong, but:

* If I can steal your cookie => I can steal your session (Session will set a session cookie, that's how you are connected to a server session, remember?)

* If I can steal your session, I can steal your "hidden" token.

Instead

* Regenerate session_id on a regular basis.

* Delete obsolete sessions so that they cannot be revived.

I would not suggest relying on this code to anyone.

Some starting point

http://eddmann.com/posts/securing-sessions-in-php/

http://resources.infosecinstitute.com/fixing-csrf-vulnerability-in-php-application/

I think there's a way:

function sess_start() {
    @session_set_cookie_params(3600 /* one hour */, '/', null, false, true);
    @session_start();
}

function sess_create() {
    @session_unset();
    @session_destroy();
    sess_start();
    $_SESSION['client_ip'] = $_SERVER['REMOTE_ADDR'];
}

function sess_init() {
    sess_start();
    if (!isset($_SESSION['client_ip']) || $_SESSION['client_ip'] != $_SERVER['REMOTE_ADDR'])
        sess_create();
}

// Start from here
sess_init();

// do the rest, now you can't steal this cookie / session
@ziadoz

This comment has been minimized.

Copy link
Owner Author

ziadoz commented Sep 30, 2019

You shouldn't be using this code (or any code you've just plucked off Gists for that matter). It's seven years old and has many issues (e.g. no session id regeneration, no timing safe comparison, doesn't clear tokens when used).

I recommend taking a look at this guide a starting point instead: https://paragonie.com/blog/2017/12/2018-guide-building-secure-php-software

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.