While developing a secure PHP web application, we want to ensure all actions are authorized and requests are honored only when they’re received from our trusted end-users. A hacker can put together a URL with GET form data and somehow forwards it to the user, which can result in commands being executed using the credentials that the hacker has patched, and we want to make sure that won’t happen that’s why we can make use of PHP nonce and tokenize our web forms and URLs.

CSRF nonce – the idea

The idea of using a CSRF token is to validate the request (GET, POST, etc) to extract a nonce that we expect the user to send (since we add it to our links or forms), and validate this nonce using a user token.

The user token should be uniquely generated and stored, and therefore we can store it in a browser cookie and expect the user to maintain it for a given interval of time. We generate a random hash, store in the cookie, and use this hash to produce other hashes named nonces which can be put into our forms and URLs.

To validate these nonces then, it’s a simple process of reproducing these hashes again using the same CSRF token, and then compare the user-submitted nonce against the one we just created using the unique user CSRF token.

Now if a hacker patches a URL with query arguments and puts a random nonce or their own nonce (which we created for them), then the targeted user (say victim) will need the hacker’s own CSRF token as well in order for the operation to be successful, which should not happen at all, as the CSRF token cookie should be stored with httponly flag which means it cannot be accessed or manipulated from the front-end.

Using PHP nonce helper

This is a very simple open source library I took couple hours to write and document, it is hosted over Github, it makes it easy for you to produce anti-CSRF nonce and add them to your URLs and web forms, and validate these nonces to make sure everything’s right.

Installation

With composer:

To install this library and its dependencies when you are using composer, simply run this command:

composer require elhardoum/nonce-php

Without composer:

If you are not using composer, then you want to download the code from a latest release (currently 0.1) from Github releases page, and extract the code to your project directory.

Nonce library depends on this package: https://github.com/ircmaxell/RandomLib, which itself depends on another package called `ircmaxell/SecurityLib` as far as I know, so you’ll want to download those as well.

Loading the library into your project:

If you used composer, then simply require the autoload.php file:

require __DIR__ . '/vendor/autoload.php';

otherwise if you didn’t use composer, then you’ll have to load the PHP classes included in the `src/` directory, and the same goes for `ircmaxell/RandomLib` and `ircmaxell/SecurityLib` as well.

The hashes (nonces) by default are store over browser cookies, but you can configure Nonce to store them somewhere else.

If you keep it that way, storing hashes over cookies, then make sure you don’t run yourself into a 400 error due to a large number of cookies supplied each time to the request headers. We can make sure we don’t run into that by the following:

Make it so the hashes stored in the cookie are very small, use `Config::$HASH_NAME_LENGTH` for this.

Try not to store too many nonces in a large amount of time, you can either limit the amount of forms tokenised, or expire the nonce cookie in a short time interval (`Config::$NONCE_EXPIRE` 10 min by default).

Toggle the cookie directory every time related to your forms, if you are sure form A is located at `/test/auth/` directory, then toggle `Config::$COOKIE_PATH` to `/test/auth/` and restore it after. In other words, don’t store too many cookies on the global cookie space (root of your app).

Alright, given that we configured the most important part, let’s dive into the usage.

Create a new nonce:

To create a nonce for the user, we can make use of the `Nonce::create` method:

Nonce::create( string $action, int $expire = null )

The action should be something unique, because it plays an important role in generating the nonce hash, we can set it to `login-user` if we’re tokenizing a loging form, or “purchase-product-{$product_id}” if on a product form or URL. now it’s clearly obvious that a nonce produced with an action `test-action` should not be the same as another action tag `test-action2`. That’s the beauty of it.

The second argument is the nonce expiration, it’s not so important but if you want a nonce to live at X seconds then specify it, otherwise it will use the default `Config::$NONCE_EXPIRE` setting.

You can instantly delete the hash from the hash store (cookies, cache, or whatever you configure it to use), but it’s not that important as the tokens have a given lifetime and should be auto-deleted upon expiration.

Using Redis as the hash store

Redis is an awesome in-memory cache driver, can be used to store the hashes and expire them properly.

Using the database as the hash store

This is not recommended at all as you’d end up bloating your database with hashes, but if you’ll be running cron jobs or some script to delete expired hashes from the database then it’ll be fine to go with this.

You can simply alter the `Config::$STORE_CTX_*` callbacks, and Nonce will pass the arguments to them to get, set and delete hashes from the database.

I have previously wrote a meta-php class which helps you use the WordPress functions (update|get|delete)_(option|user_meta|post_meta), and it can be used here to store the hashes, get and delete them.

The keys expiration are stored in the meta database as `*_expire`, when you run the cleanup script you can then get all the keys with `*_expire` where the `meta_value` is greater than the current unix timestamp:

select `meta_key` from `mydb`.`meta` where `meta_key` like '%_expire' and `meta_value` > UNIX_TIMESTAMP(NOW())

Then iterate through the keys and delete the expiration and the hashes as well, so you’d be ending up deleting 2 rows per hash.

More documentation

This is a quick tutorial introducing this PHP Nonce tool, therefore not all the configuration and usage is covered, please see the project’s Github page for more information. Thank you!

Cheap Cloud SSD Hosting

Get a VPS now starting at $5/m, fast and perfect for WordPress and PHP applications