Coder Social home page Coder Social logo

pedroac / nonce4php Goto Github PK

View Code? Open in Web Editor NEW
4.0 1.0 1.0 115 KB

A nonce manager PHP library useful for preventing CSRF and replay attacks.

License: MIT License

PHP 98.13% Shell 0.24% HTML 1.62%
nonces security csrf-tokens replay-attack php-library nonces-generator php

nonce4php's Introduction

pedroac/nonce for PHP

Build Status Codacy Badge Support via PayPal

A nonce manager PHP library useful for preventing CSRF and replay attacks.

We may find several articles and videos explaining the vulnerabilities that nonces try to prevent:

It seems, though, that many PHP nonces libraries are too restrictive, coupled with some framework, hard to use or hard to understand how they work.

pedroac/nonce tries to solve those issues.

It allows choosing any PSR-16 implementation to store temporarily the nonces, nonces values generators, expiration intervals and even a DateTime provider to override the clock system (this feature is used for unit tests).

It also provides helpers to manage input, generate random nonces names and values, verify submitted tokens against the nonce and generate HTML elements.

Prerequisites

Installing

Run the command:

composer require pedroac/nonce

Usage

Examples

The HTML forms can be tested using a PHP built-in web server.
From the php/examples folder run the command:

php -S localhost:8000

Use the URL http://localhost:8000/ in a browser.

HTML form with a token

  1. Create a nonce form helper:
<?php
require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;
use \pedroac\nonce\Form\HtmlNonceField;
use \pedroac\nonce\Form\NonceForm;

// this handles automatically the input and nonce management
$form = new NonceForm(
    'token', // the HTML input name
    new NoncesManager(
      new FilesystemCache // a \Psr\SimpleCache\CacheInterface implementation
    )
);
// this will be used to generate a HTML input element
$htmlField = new HtmlNonceField($form);
  1. Check if a valid token was submitted:
if ($form->isSubmittedValid()) {
  /**
   * handle the success:
   * - if all form input is valid, show success page;
   * - otherwise, show an error page and the form again;
   */
}
  1. Check if an invalid token was submitted:
if ($form->isSubmittedInvalid()) {
  /**
   * handle failure:
   * - don't show the form again;
   * - show an error message;
   */
}
  1. Implement the HTML form:
<form method="POST">
    <?= $htmlField ?>
    <!-- more HTML -->
    <input type="submit" name="myform" value="Submit" />
</form>

The nonce is expired automatically when the token is verified with the NonceForm class.

General usage

  1. Instantiate a nonce manager:
<?php
require __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Cache\Simple\FilesystemCache;
use \pedroac\nonce\NoncesManager;

$manager = new NoncesManager(new FilesystemCache);
  1. When a request is submitted, validate the submitted token and remove the nonce:
$isValidToken = false;
$isValidForm = false;
$wasSubmitted = filter_has_var(INPUT_POST, 'myform');
$tokenName = filter_input(INPUT_POST, 'token_name');
$tokenValue = filter_input(INPUT_POST, 'token_value') ?? '';

if ($tokenName) {
    $isValidToken = $manager->verifyAndExpire($tokenName, $tokenValue);
}
if ($wasSubmitted && $isValidToken) {
    // validate input
}
  1. Generate a nonce when appropriate:
if (!$wasSubmitted || (!$isValidForm && $isValidToken)) {
  $nonce = $manager->create();
}
  1. Use the nonce name and value to build, for instance, a HTML form:
<?php if ($nonce) : ?>
  <input type="hidden"
        name="token_name"
        value="<?= htmlspecialchars($nonce->getName()) ?>" />
  <input type="hidden"
        name="token_value"
        value="<?= htmlspecialchars($nonce->getValue()) ?>" />
  <input type="submit" name="myform" value="Submit" />
<?php endif; >

Options

Besides the nonces cache storage, it's possible to select the random nonce value generator and the expiration interval:

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

use Symfony\Component\Cache\Simple\ArrayCache;
use \pedroac\nonce\NoncesManager;
use \pedroac\nonce\Random\HexRandomizer;

$manager = new NoncesManager(
    new ArrayCache(60),
    new HexRandomizer(32), // a \pedroac\nonce\Random implementation
    new \DateInterval('PT3H')
);

It's also possible to create a nonce with a specified name:

$user_id = $_SESSION['user_id'];
$tokenName = "{$user_id}_form";
$nonce = $manager->create($tokenName);

NonceForm default input source is $_POST, but it accepts any array input:

$form = new NonceForm(
    'token',
    new NoncesManager(
      new FilesystemCache
    ),
    filter_input_array(INPUT_GET) // use $_GET
);

Running the tests

Run from the library root folder:

php/vendor/bin/phpunit php/tests/ -c php/tests/configuration.xml

If the tests were successful, php/tests/coverage-html should have the code coverage report.

Generating the HTML documentation

Run from the library root folder:

sh scripts/generate-docs.sh

The generated documentation should be inside the folder docs.

Versioning

It should be used SemVer for versioning.

Authors

License

pedroac/nonce is released under the MIT public license.
See the enclosed LICENSE for details.

Acknowledgments

The library was developed as a private request response made by a Stackoverflow user.

nonce4php's People

Contributors

codacy-badger avatar pedroac avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

gtbu

nonce4php's Issues

Example for Symphony

Are Your examples for Symphony ?

use Symfony\Component\Cache\Simple\FilesystemCache;

How to implement in normal php ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.