Conn2Flow
Docs navigation

Reference / Libraries

seguranca.php library

Admin panel CSRF, CAPTCHA verification (reCAPTCHA and Turnstile), session User-Agent and IP checks, random tokens and normalization of the post-login return path.

Path in the Gestor bibliotecas/seguranca.php

It gathers the Gestor's request defenses. The router loads it on every request, to validate CSRF before any module runs (request lifecycle).

CSRF

seguranca_csrf_requisicao_validar() runs in gestor_start() and only requires the token when all these conditions hold:

  • the method is POST, PUT, PATCH or DELETE;

  • the request carries the authentication cookie (COOKIE_AUTHNAME): visitors' public forms do not go through here and are protected by CAPTCHA;

  • the route is not exempt: _api/…, api/… and _gestor-csrf-token, plus the admin-atualizacoes transition exceptions for clients older than 2.9.25.

On failure, the answer is 403 with {"status":"error","code":"CSRF_INVALID_OR_EXPIRED",…}.

Function
gestor_csrf_token() The session token (64 hex), created on the first call. It goes into <meta name="csrf-token"> and gestor.csrfToken
seguranca_csrf_token_requisicao() Reads the token from the X-CSRF-Token header, the _csrf_token POST field or $_REQUEST
gestor_csrf_validar($token, $expected = null) Compares with hash_equals()
seguranca_csrf_token_resposta($ctx) Decides the answer of the _gestor-csrf-token/ route (global.js uses it to renew an expired token): 200 with the token, or 401 AUTH_EXPIRED with X-Gestor-Auth-Redirect if the login expired
seguranca_csrf_retorno_normalizar($r) Accepts only a relative path (no scheme, //, :, .. even encoded, or control characters) to return to after login

In your own code, forms sent with fetch/$.ajax already carry the token (global.js attaches it). In a plain HTML <form>, include the field:

<input type="hidden" name="_csrf_token" value="…value of gestor_csrf_token()…">

CAPTCHA

gestor_captcha_validar($token = null, $options = []) checks the token with the CAPTCHA_PROVIDER provider (google-recaptcha, cloudflare-turnstile or none, which always approves).

  • Without $token, it reads cf-turnstile-response, g-recaptcha-response or token from POST.

  • Options: provider, secret, v2 (uses the reCAPTCHA v2 key), action (required in v3: checks the action and a minimum score of 0.5), return_response, transport (injection for tests).

  • It returns the provider's response array on success, or false. 5 s timeout.

In reCAPTCHA v3, the score is only checked when action is passed: without it, any valid token passes, even a bot's.

Session: User-Agent and IP

At login, seguranca_sessao_registrar() stores in the session the User-Agent (255 characters) and the IP block (/24 for IPv4; the full address for IPv6). On every authenticated request, gestor_permissao_token() calls seguranca_sessao_validar(); on a mismatch, seguranca_sessao_invalidar() deletes the token from usuarios_tokens and the user goes back to the login.

The IP used is the raw REMOTE_ADDR, not the one from ip_get(): behind a reverse proxy, it is always the proxy's IP and the IP check tells nobody apart.

Utilities

  • seguranca_token_aleatorio($bytes = 32): hexadecimal from random_bytes(), at least 16 bytes.

  • seguranca_ip_bloco($ip = null), seguranca_user_agent().

Internal helpers (used by the functions above; rarely called directly): seguranca_csrf_rota_isenta(), seguranca_csrf_resposta_invalida_corpo(), seguranca_csrf_atualizador_transicao_isento(), seguranca_csrf_atualizador_status_isento(), seguranca_csrf_atualizador_sessao_legada_isento().

Functions

Generated from gestor/bibliotecas/seguranca.php · 18 functions

18 of 18

gestor_captcha_validar

view source · line 23 ↗
gestor_captcha_validar(?string $token = null, array $opcoes = []): array|bool

Valida o provedor configurado. O transporte pode ser injetado nos testes.

Parameters

$token?string
$opcoesarray

Returns

array|bool

seguranca_token_aleatorio

view source · line 78 ↗
seguranca_token_aleatorio(int $bytes = 32): string

Gera um identificador hexadecimal com entropia criptograficamente segura.

Parameters

$bytesint
Quantidade de bytes aleatórios (mínimo: 16 / 128 bits).

Returns

string

seguranca_ip_bloco

view source · line 91 ↗
seguranca_ip_bloco(string|null $ip = null): string

Retorna o bloco de rede do IP (3 primeiros octetos no IPv4).

Parameters

$ipstring|null
IP a avaliar (padrão: REMOTE_ADDR).

Returns

string
Bloco de rede (ex.: "200.100.50") ou o IP original.

gestor_csrf_validar

view source · line 185 ↗
gestor_csrf_validar(string $token, $esperado = null): bool

Valida um token CSRF recebido contra o armazenado na sessão.

Parameters

$tokenstring
Token recebido na requisição.
$esperado

Returns

bool

seguranca_csrf_rota_isenta

view source · line 213 ↗
seguranca_csrf_rota_isenta(array $caminho): bool

Informa se a rota usa autenticação M2M/Bearer e, portanto, não usa cookie de sessão. O canal distribuído é protegido por HMAC dentro do controlador da API.

Parameters

$caminhoarray
Segmentos normalizados da rota.

Returns

bool

seguranca_csrf_token_resposta

view source · line 260 ↗
seguranca_csrf_token_resposta(array $contexto): array

Decide a resposta da rota _gestor-csrf-token (req-175). Função PURA: o roteador só emite.

Parameters

$contextoarray
token, tem_cookie_auth, autenticado, url_raiz.

Returns

array
['http' => int, 'headers' => array, 'corpo' => array]

seguranca_csrf_atualizador_status_isento

view source · line 360 ↗
seguranca_csrf_atualizador_status_isento(array $caminho, array $requisicao): bool

Reconhece a consulta de status do autoatualizador como operação de leitura.

Parameters

$caminhoarray
Segmentos normalizados da rota.
$requisicaoarray
Parâmetros recebidos pela requisição.

Returns

bool

seguranca_csrf_atualizador_sessao_legada_isento

view source · line 381 ↗
seguranca_csrf_atualizador_sessao_legada_isento(array $caminho, array $requisicao, string|null $rootPath = null, int|null $agora = null): bool

Permite concluir uma sessao do autoatualizador iniciada por um cliente anterior ao CSRF. O SID aleatorio e o estado persistido limitam a isencao a uma transicao real, recente, inacabada e na etapa esperada.

Parameters

$caminhoarray
Segmentos normalizados da rota.
$requisicaoarray
Parametros recebidos pela requisicao.
$rootPathstring|null
Raiz fisica do Gestor (injetavel nos testes).
$agoraint|null
Timestamp atual (injetavel nos testes).

Returns

bool

The Future is Hybrid: Human + AI.

Conn2Flow is the tool. If you need the Architect to design your company's strategy using this technology...

Hire Specialized Consulting