FastSitePHP\Security\Web\CsrfStateless

‘Stateless’ CSRF Tokens

Stateless CSRF Tokens are not stored in Session but rather use a crypto keyed-hash message authentication code (HMAC) to create and verify the token.

Stateless Tokens work well if authentication happens with cookies that do not use standard PHP session functions, that said this class also works well with PHP Sessions and provides expiration time that can be changed per page.

If stateless authentication always happens through Request Headers for POST Requests and other transactions then CSRF attacks are prevented and CSRF Tokens are not needed. CSRF Tokens are generally needed if authentication happens with cookies (by default Session code always uses cookies).

If using PHP 5.3 then using this class will polyfill functions [bin2hex()] and [hex2bin()] and if using a version of PHP below 5.6 then this class will polyfill [hash_equals()].

For another Stateless CSRF Token implementation with NodeJS see the link below.

Código Fonte

GitHub

Código de Exemplo

Segurança - Stateless CSRF

// Tokens Stateless CSRF não são armazenados em Sessão, mas ao invés disso
// utilizam um código de autenticação de mensagem criptografada com hash
// (HMAC) para criar e verificar o token.

// Uma chave segura secreta é requerida.
// A chave seria tipicamente salva com seu app ou nas configurações.
$key = \FastSitePHP\Security\Web\CsrfStateless::generateKey();

// Para utilizar a Chave, essa deve ser salva em um valor de configuração ou
// em uma variável de ambiente antes de chamar [setup()].
$app->config['CSRF_KEY'] = $key;
// putenv("CSRF_KEY=${key}");

// Um identificador único para o usuário é também necessário. Isto não tem de
// ser um segredo e pode ser simplesmente um campo numérico em um banco de
// dados.
$user_id = 1;

// Configura e valida token stateless CSRF
\FastSitePHP\Security\Web\CsrfStateless::setup($app, $user_id);

// Opcionalmente adicione um tempo de expiração, este token CSRF expirará depois de 5 minutos
$expire_time = '+5 minutes';
\FastSitePHP\Security\Web\CsrfStateless::setup($app, $user_id, $expire_time);

// A mesma lógica é utilizada ao usar a classe [CsrfSession], então o token
// é atribuído um valor locals no Objeto da Aplicação permitindo que seja
// utilizado com código de modelo.
$token = $app->locals['csrf_token'];
//
// <meta name="X-CSRF-Token" content="{{ $csrf_token }}">
// <input name="X-CSRF-Token" value="{{ $csrf_token }}">

// Também da mesma forma que [CsrfSession] um bom lugar para chamar
// [setup()] é nas funções filtro de rota.
$csrf = function() use ($app, $user_id) {
    \FastSitePHP\Security\Web\CsrfStateless::setup($app, $user_id);
};

$app->get('/form', function() use ($app) {
    return $app->render('form.php');
})
->filter($csrf);

Métodos

generateKey()

Função Estática

Return a key that can be used to generate and validate Stateless CSRF Tokens. The key must be kept private and not shared with end users.

setup(Application $app, $user_id, $expire_time = null, $key = 'X-CSRF-Token')

Função Estática

Setup and validate stateless CSRF Tokens. A good place to call this function is on route filters of pages that use authentication.

This will assign the token to app property $app->locals['csrf_token'] which then must be included with the form or response. When using [$app->render()] the value will be available as variable [$csrf_token].

This function requires the App config value $app->config['CSRF_KEY'] or an Environment Variable of the same name with a key generated from the function [generateKey()].

For usage see demo code.