Implementare un servizio web di firma digitale CAdES con PHP
In questa puntata il servizio è scritto in PHP 8.4 senza framework con l'estensione OpenSSL per le operazioni RSA, phpseclib 3 per la validazione della CRL e un piccolo codec DER scritto da zero per costruire e leggere le strutture CMS.
Questo articolo fa parte di una serie in sette puntate in cui lo stesso servizio web di firma digitale viene implementato in Node.js, PHP, Go, Python, Laravel, Java e C#. Le sette implementazioni espongono la stessa API, usano la stessa infrastruttura di chiavi di test e producono firme intercambiabili: una firma creata da un servizio può essere verificata da qualunque altro e da OpenSSL. In questa puntata il servizio è scritto in PHP 8.4 senza framework con l'estensione OpenSSL per le operazioni RSA, phpseclib 3 per la validazione della CRL e un piccolo codec DER scritto da zero per costruire e leggere le strutture CMS.
Il risultato è un servizio completo: firma file arbitrari producendo buste CMS detached con profilo CAdES, aggiunge facoltativamente una marca temporale RFC 3161, verifica firma, catena di certificazione e revoca tramite CRL, autentica i client con API key e registra ogni operazione in un log di audit su SQLite senza mai conservare i documenti.
Che cosa significa "firma digitale" in questo servizio
Il termine "firma digitale" viene usato con significati diversi, quindi conviene chiarire subito il perimetro. Dal punto di vista crittografico una firma è il risultato di un'operazione con una chiave privata su un'impronta dei dati, verificabile con la chiave pubblica corrispondente. Dal punto di vista giuridico, invece, il regolamento europeo eIDAS (Regolamento UE 910/2014, aggiornato dal Regolamento UE 2024/1183) distingue tra firma elettronica semplice, avanzata e qualificata. In Italia la "firma digitale" definita dal Codice dell'Amministrazione Digitale (D.Lgs. 82/2005) è una firma qualificata: richiede un certificato qualificato rilasciato da un prestatore di servizi fiduciari qualificato e una chiave custodita in un dispositivo sicuro, come una smart card, un token o un HSM remoto gestito dal prestatore.
Il servizio descritto qui sta a metà strada. Produce firme con lo stesso formato tecnico usato dalle firme qualificate, cioè CMS (Cryptographic Message Syntax, RFC 5652) secondo il profilo CAdES (ETSI EN 319 122), ma usa certificati emessi da una CA interna e una chiave software. Non è quindi una firma qualificata eIDAS e non ha il valore legale di una firma digitale apposta con un dispositivo qualificato. È invece la base corretta per tutti i casi in cui serve una firma verificabile, standard e interoperabile: sigillare documenti generati da un gestionale, garantire l'integrità di esportazioni e report, firmare file scambiati tra sistemi interni, oppure preparare l'architettura che in seguito delegherà la chiave a un HSM o a un prestatore qualificato.
Le scelte tecniche, comuni a tutta la serie, sono queste:
- Formato: busta CMS
SignedDatadetached, cioè senza il documento al suo interno. Il documento resta com'è e la firma viaggia in un file separato con estensione.p7s. - Algoritmi: RSA a 3072 bit con padding PKCS#1 v1.5 e SHA-256, la combinazione supportata in modo uniforme da tutte le librerie usate nella serie.
- Attributi firmati:
contentType,messageDigest,signingTimeesigningCertificateV2. L'ultimo lega la firma al certificato del firmatario tramite il suo hash e distingue una firma CAdES-BES da una semplice firma CMS. - Marca temporale: facoltativa, ottenuta da una TSA RFC 3161 e inserita come attributo non firmato
signatureTimeStampToken. Con la marca il profilo diventa CAdES-T, che nella nomenclatura ETSI più recente corrisponde al livello B-T. - Revoca: verificata tramite una CRL locale firmata dalla CA. OCSP resta tra le evoluzioni possibili.
Come funziona una firma CAdES detached
Una firma CMS con attributi firmati non si calcola direttamente sul documento. Il procedimento è il seguente:
- si calcola l'hash SHA-256 del documento;
- si costruisce l'insieme degli attributi firmati, in cui l'attributo
messageDigestcontiene proprio quell'hash; - si codifica l'insieme degli attributi in DER come
SET OF Attribute, con gli elementi ordinati per codifica binaria; - si firma con RSA quella codifica DER;
- si inseriscono attributi, firma, identificativo del firmatario (emittente e numero di serie del certificato) e certificato in una struttura
SignerInfo, a sua volta contenuta in unaSignedDatae in unaContentInfo.
Due dettagli causano la maggior parte degli errori quando si costruisce CMS a mano. Il primo: nella struttura finale gli attributi firmati compaiono con il tag implicito [0] (byte 0xA0), ma la firma va calcolata sulla codifica con il tag universale SET (byte 0x31). Il secondo: in DER gli elementi di un SET OF devono essere ordinati, e l'ordine usato per firmare deve essere identico a quello scritto nella busta.
La verifica percorre la strada inversa: ricalcola l'hash del documento e lo confronta con messageDigest, ricodifica gli attributi con il tag SET e verifica la firma RSA con la chiave pubblica del certificato. A quel punto la firma è crittograficamente corretta, ma restano da controllare la catena di certificazione verso una CA fidata, la validità temporale del certificato, il suo stato di revoca e la corrispondenza dell'attributo signingCertificateV2.
La marca temporale si aggiunge dopo la firma. Alla TSA si invia l'hash del valore della firma, non del documento, e la TSA restituisce un token che è a sua volta una busta CMS firmata contenente una struttura TSTInfo con l'istante certificato. Il token viene inserito tra gli attributi non firmati del firmatario: dato che quegli attributi non sono coperti dalla firma, aggiungerli non la invalida.
Il contratto dell'API
Tutte le implementazioni della serie espongono le stesse quattro rotte, con lo stesso formato di richiesta e di risposta. Un client scritto per una di esse funziona senza modifiche con tutte le altre.
GET /health: controllo di disponibilità, pubblico, risponde{"status":"ok"}.GET /api/certificate: restituisce i dati del certificato di firma e il certificato in formato PEM.POST /api/sign: riceve un file nel campo multipartfilee restituisce la firma.POST /api/verify: riceve il documento nel campofilee la firma nel camposignature, e restituisce l'esito dettagliato della verifica.
Tutte le rotte sotto /api richiedono l'intestazione X-API-Key. Per impostazione predefinita /api/sign risponde in JSON, con la busta CMS codificata in base64:
{
"signature": "MIIL...",
"encoding": "base64-der",
"profile": "CAdES-BES",
"sha256": "d47e50a171dd4a56e6358002c9feb662a0366c...",
"certificateSerial": "1000",
"signingTime": "2026-12-04T12:45:24Z",
"timestamp": null
}
Se la richiesta contiene Accept: application/pkcs7-signature, la risposta è invece direttamente il file .p7s in DER, con un'intestazione Content-Disposition che ne suggerisce il nome. Il campo signature di /api/verify accetta entrambe le forme: DER binario, riconoscibile dal primo byte 0x30 che apre una SEQUENCE, oppure il base64 restituito dalla risposta JSON.
La verifica risponde sempre con HTTP 200 quando la busta è leggibile, anche se la firma non è valida. L'esito è nel corpo:
{
"valid": true,
"profile": "CAdES-T",
"signer": {
"subject": "CN=Servizio di firma,O=Firma Demo,C=IT",
"issuer": "CN=Firma Demo Root CA,O=Firma Demo,C=IT",
"serialNumber": "1000",
"notBefore": "2026-12-04T12:29:54Z",
"notAfter": "2028-12-03T12:29:54Z"
},
"signingTime": "2026-12-04T12:45:24Z",
"timestamp": { "time": "2026-12-04T12:45:24Z", "tsa": "CN=Dev TSA", "valid": true },
"checks": {
"signature": true,
"signingCertificate": true,
"chain": true,
"revocation": "good"
},
"errors": []
}
Il campo valid è vero solo se lo sono tutti i controlli: firma crittografica e messageDigest, attributo signingCertificateV2, catena verso la CA fidata con certificato nel periodo di validità, stato di revoca good ed eventuale marca temporale valida. Lo stato di revoca può valere good, revoked oppure unknown; quest'ultimo valore indica, per esempio, una CRL scaduta o illeggibile e rende la firma non valida, perché in assenza di informazioni affidabili il servizio non può garantire che il certificato fosse ancora valido.
Gli errori usano un formato unico:
{ "error": { "code": "PAYLOAD_TOO_LARGE", "message": "file troppo grande" } }
I codici previsti sono UNAUTHORIZED (401), BAD_REQUEST (400), MALFORMED_SIGNATURE (400, busta CMS illeggibile o non detached), PAYLOAD_TOO_LARGE (413), TSA_UNAVAILABLE (502) e INTERNAL (500).
La configurazione avviene con le stesse variabili d'ambiente in tutte le implementazioni:
SIGNER_P12_PATHeSIGNER_P12_PASSWORD: keystore PKCS#12 con chiave e certificato di firma;TRUST_ANCHOR_PATH: certificato PEM della CA considerata fidata in fase di verifica;CRL_PATH: CRL in formato DER emessa dalla stessa CA;TSA_URL: URL della TSA RFC 3161; se vuota, la marca temporale è disattivata;API_KEYS: elenco di coppieclient:chiaveseparate da virgole, per esempioerp:3f9c...,crm:a71b...;AUDIT_DB_PATH: percorso del database SQLite di audit;MAX_UPLOAD_BYTES: dimensione massima di ciascun file caricato, 10 MiB se non specificata.
Una PKI di test
Per firmare servono una chiave privata e un certificato; per verificare servono una CA fidata e una CRL. Lo script seguente, identico in tutta la serie, genera con OpenSSL una CA radice, il certificato del servizio di firma, un secondo certificato che viene subito revocato (utile nei test) e la CRL corrispondente. Va salvato come pki/setup.sh nella radice del progetto.
#!/usr/bin/env bash
# Genera una PKI di test: CA radice, certificato del servizio di firma,
# un certificato revocato e la relativa CRL.
# NON usare questi materiali in produzione.
set -euo pipefail
PKI_DIR="$(cd "$(dirname "$0")" && pwd)"
P12_PASSWORD="${SIGNER_P12_PASSWORD:-changeit}"
cd "$PKI_DIR"
rm -rf ca out
mkdir -p ca/newcerts out
touch ca/index.txt
echo 1000 > ca/serial
echo 1000 > ca/crlnumber
# Configurazione minimale per "openssl ca"
cat > ca/openssl.cnf <<CNF
[ ca ]
default_ca = test_ca
[ test_ca ]
dir = ${PKI_DIR}/ca
database = \$dir/index.txt
new_certs_dir = \$dir/newcerts
serial = \$dir/serial
crlnumber = \$dir/crlnumber
certificate = \$dir/ca.crt
private_key = \$dir/ca.key
default_md = sha256
default_days = 730
default_crl_days = 30
policy = policy_any
unique_subject = no
[ policy_any ]
countryName = optional
organizationName = optional
commonName = supplied
[ req ]
distinguished_name = dn
prompt = no
[ dn ]
CN = placeholder
[ v3_ca ]
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, keyCertSign, cRLSign
subjectKeyIdentifier = hash
[ v3_signer ]
basicConstraints = critical, CA:false
keyUsage = critical, digitalSignature, nonRepudiation
extendedKeyUsage = emailProtection
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid
CNF
# 1. CA radice autofirmata (RSA 3072, 10 anni)
openssl req -x509 -new -newkey rsa:3072 -nodes -sha256 -days 3650 \
-keyout ca/ca.key -out ca/ca.crt \
-subj "/C=IT/O=Firma Demo/CN=Firma Demo Root CA" \
-config ca/openssl.cnf -extensions v3_ca
# Emette un certificato di firma e lo impacchetta in un PKCS#12
issue() {
local name="$1" subject="$2"
openssl req -new -newkey rsa:3072 -nodes \
-keyout "out/${name}.key" -out "out/${name}.csr" \
-subj "$subject" -config ca/openssl.cnf
openssl ca -batch -notext -config ca/openssl.cnf -extensions v3_signer \
-in "out/${name}.csr" -out "out/${name}.crt"
openssl pkcs12 -export -name "$name" \
-inkey "out/${name}.key" -in "out/${name}.crt" -certfile ca/ca.crt \
-keypbe AES-256-CBC -certpbe AES-256-CBC -macalg sha256 \
-passout "pass:${P12_PASSWORD}" -out "out/${name}.p12"
rm -f "out/${name}.csr" "out/${name}.key"
}
# 2. Certificato del servizio e certificato destinato alla revoca
issue signer "/C=IT/O=Firma Demo/CN=Servizio di firma"
issue revoked "/C=IT/O=Firma Demo/CN=Firmatario revocato"
# 3. Revoca del secondo certificato e generazione della CRL (PEM e DER)
openssl ca -config ca/openssl.cnf -revoke out/revoked.crt -crl_reason keyCompromise
openssl ca -config ca/openssl.cnf -gencrl -out out/ca.crl.pem
openssl crl -in out/ca.crl.pem -outform DER -out out/ca.crl
cp ca/ca.crt out/ca.crt
echo "PKI di test generata in ${PKI_DIR}/out"
ls -1 out
Alcuni dettagli meritano attenzione. Il certificato di firma ha keyUsage critico con digitalSignature e nonRepudiation, come si usa per i certificati destinati alla firma di documenti, e extendedKeyUsage impostato a emailProtection: in questo modo openssl cms -verify, che per impostazione predefinita applica lo scopo S/MIME, accetta le firme senza opzioni aggiuntive. Il keystore PKCS#12 è cifrato con AES-256-CBC e PBKDF2 (le impostazioni predefinite di OpenSSL 3), ed è protetto dalla password letta da SIGNER_P12_PASSWORD, con changeit come valore di ripiego per lo sviluppo. Le chiavi private in chiaro vengono cancellate subito dopo la creazione dei PKCS#12, mentre la chiave della CA resta in pki/ca perché serve per revocare certificati e rigenerare la CRL.
chmod +x pki/setup.sh
SIGNER_P12_PASSWORD=changeit ./pki/setup.sh
# Controllo del contenuto della CRL: deve elencare il seriale 1001
openssl crl -in pki/out/ca.crl -inform DER -noout -text | grep -A1 "Serial Number"
La CRL ha una validità di 30 giorni (default_crl_days). Il servizio considera unknown lo stato di revoca quando la data nextUpdate è passata: in un ambiente reale la CRL va quindi rigenerata periodicamente, per esempio con un job pianificato che esegue openssl ca -gencrl e sovrascrive il file. Il servizio rilegge la CRL automaticamente quando cambia la data di modifica del file, senza bisogno di riavvio.
Le scelte per PHP
L'estensione OpenSSL di PHP offre openssl_cms_sign e openssl_cms_verify, che a prima vista sembrano sufficienti. Hanno però due limiti decisivi per questo servizio: non permettono di aggiungere attributi firmati personalizzati come signingCertificateV2, né attributi non firmati come la marca temporale, e lavorano solo su file su disco. Inoltre la verifica restituisce un esito unico, senza distinguere tra documento alterato, catena non valida e certificato revocato.
La soluzione adottata usa OpenSSL solo per ciò che sa fare meglio, cioè le operazioni RSA e la verifica delle firme sui certificati, e costruisce la busta CMS con un codec DER minimale, circa duecento righe che coprono i tipi ASN.1 necessari a CMS e a RFC 3161. Per la CRL, che l'estensione OpenSSL non sa leggere, si usa la classe X509 di phpseclib 3, che ne verifica la firma ed espone l'elenco dei certificati revocati. phpseclib include anche un proprio motore ASN.1, ma richiede di descrivere ogni struttura con una mappa: per le poche strutture che servono qui un codec dedicato è più breve e più leggibile.
Il servizio non usa framework: un front controller, un kernel che instrada le richieste e oggetti Request e Response immutabili. Questo lo rende facile da testare e mostra senza filtri come PHP gestisce upload e limiti. L'implementazione con Laravel è l'oggetto di un'altra puntata della serie.
Struttura del progetto
firma-php/
public/index.php # front controller
src/
Config.php # variabili d'ambiente
ApiKeyAuthenticator.php # autenticazione con API key
AuditLog.php # log di audit con PDO e SQLite
Asn1/
Der.php # codec DER minimale
Oid.php # object identifier
Asn1Exception.php
Cades/
Signer.php # interfaccia Signer
Pkcs12Signer.php # implementazione PKCS#12
Certificates.php # utilita' sui certificati
TimeStampToken.php # lettura dei token RFC 3161
TsaClient.php # client RFC 3161
CadesSigner.php # costruzione della busta CAdES
SignatureResult.php
CrlChecker.php # controllo di revoca tramite CRL
SignatureVerifier.php # verifica completa di una firma
TsaException.php
MalformedSignatureException.php
Http/
Request.php
Response.php
ApiException.php
Kernel.php # routing e handler
tests/ApiTest.php
pki/setup.sh
composer.json
phpunit.xml
Dockerfile
docker/php.ini
docker/firma.conf
{
"name": "demo/firma-php",
"description": "Servizio web di firma digitale CAdES in PHP senza framework",
"type": "project",
"license": "MIT",
"require": {
"php": ">=8.4",
"ext-curl": "*",
"ext-openssl": "*",
"ext-pdo_sqlite": "*",
"phpseclib/phpseclib": "^3.0"
},
"require-dev": {
"phpunit/phpunit": "^12.5"
},
"autoload": {
"psr-4": { "App\\": "src/" }
},
"autoload-dev": {
"psr-4": { "Tests\\": "tests/" }
},
"scripts": {
"serve": "php -S 0.0.0.0:8080 -t public",
"test": "phpunit tests"
}
}
composer install
Un codec DER minimale
La classe Der è il fondamento del servizio. La parte di codifica produce stringhe binarie, che in PHP sono semplici sequenze di byte; la parte di decodifica trasforma un DER in un albero di array, in cui ogni nodo conserva classe, tag, contenuto, figli e soprattutto raw, la codifica originale completa del nodo.
<?php
declare(strict_types=1);
namespace App\Asn1;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
/**
* Codifica e decodifica DER minimale, sufficiente per CMS, CAdES e RFC 3161.
* Un nodo decodificato e' un array con: class, tag, constructed, content, raw, children.
*/
final class Der
{
public const CLASS_UNIVERSAL = 0;
public const CLASS_CONTEXT = 2;
public const BOOLEAN = 0x01;
public const INTEGER = 0x02;
public const BIT_STRING = 0x03;
public const OCTET_STRING = 0x04;
public const NULL = 0x05;
public const OID = 0x06;
public const SEQUENCE = 0x10;
public const SET = 0x11;
public const UTC_TIME = 0x17;
public const GENERALIZED_TIME = 0x18;
// --- Codifica -------------------------------------------------------
public static function tlv(int $identifier, string $content): string
{
return chr($identifier) . self::encodeLength(strlen($content)) . $content;
}
private static function encodeLength(int $length): string
{
if ($length < 0x80) {
return chr($length);
}
$bytes = ltrim(pack('J', $length), "\0");
return chr(0x80 | strlen($bytes)) . $bytes;
}
public static function sequence(string ...$items): string
{
return self::tlv(0x30, implode('', $items));
}
/** In DER gli elementi di un SET OF sono ordinati per codifica binaria. */
public static function sortSet(array $items): array
{
sort($items, SORT_STRING);
return $items;
}
public static function set(string ...$items): string
{
return self::tlv(0x31, implode('', self::sortSet($items)));
}
public static function oid(string $dotted): string
{
$arcs = array_map('intval', explode('.', $dotted));
$content = chr(40 * $arcs[0] + $arcs[1]);
foreach (array_slice($arcs, 2) as $arc) {
$chunk = chr($arc & 0x7f);
while (($arc >>= 7) > 0) {
$chunk = chr(0x80 | ($arc & 0x7f)) . $chunk;
}
$content .= $chunk;
}
return self::tlv(self::OID, $content);
}
public static function octetString(string $bytes): string
{
return self::tlv(self::OCTET_STRING, $bytes);
}
/** INTEGER positivo a partire dai byte senza segno (big-endian). */
public static function unsignedInteger(string $bytes): string
{
$bytes = ltrim($bytes, "\0");
if ($bytes === '' || (ord($bytes[0]) & 0x80) !== 0) {
$bytes = "\0" . $bytes;
}
return self::tlv(self::INTEGER, $bytes);
}
public static function integer(int $value): string
{
return self::unsignedInteger(pack('J', $value));
}
public static function null(): string
{
return "\x05\x00";
}
public static function boolean(bool $value): string
{
return self::tlv(self::BOOLEAN, $value ? "\xff" : "\x00");
}
public static function utcTime(DateTimeInterface $time): string
{
$utc = DateTimeImmutable::createFromInterface($time)->setTimezone(new DateTimeZone('UTC'));
return self::tlv(self::UTC_TIME, $utc->format('ymdHis') . 'Z');
}
public static function explicit(int $tagNumber, string $inner): string
{
return self::tlv(0xa0 | $tagNumber, $inner);
}
/** [n] IMPLICIT di un tipo costruito (es. SET OF): gli elementi non vengono riordinati. */
public static function implicitConstructed(int $tagNumber, array $items): string
{
return self::tlv(0xa0 | $tagNumber, implode('', $items));
}
// --- Decodifica -----------------------------------------------------
public static function decode(string $der): array
{
$offset = 0;
$node = self::read($der, $offset);
if ($offset !== strlen($der)) {
throw new Asn1Exception('byte in eccesso dopo la struttura DER');
}
return $node;
}
private static function read(string $data, int &$offset): array
{
$start = $offset;
$size = strlen($data);
if ($offset + 2 > $size) {
throw new Asn1Exception('struttura DER troncata');
}
$identifier = ord($data[$offset++]);
if (($identifier & 0x1f) === 0x1f) {
throw new Asn1Exception('tag in forma estesa non supportati');
}
$length = ord($data[$offset++]);
if ($length >= 0x80) {
$count = $length & 0x7f;
if ($count === 0 || $count > 4 || $offset + $count > $size) {
throw new Asn1Exception('lunghezza DER non valida');
}
$length = 0;
for ($i = 0; $i < $count; $i++) {
$length = ($length << 8) | ord($data[$offset++]);
}
}
if ($offset + $length > $size) {
throw new Asn1Exception('struttura DER troncata');
}
$content = substr($data, $offset, $length);
$node = [
'class' => $identifier >> 6,
'tag' => $identifier & 0x1f,
'constructed' => ($identifier & 0x20) !== 0,
'content' => $content,
'raw' => substr($data, $start, $offset - $start + $length),
'children' => [],
];
if ($node['constructed']) {
$inner = 0;
while ($inner < $length) {
$node['children'][] = self::read($content, $inner);
}
}
$offset += $length;
return $node;
}
public static function isUniversal(?array $node, int $tag): bool
{
return $node !== null && $node['class'] === self::CLASS_UNIVERSAL && $node['tag'] === $tag;
}
public static function isContext(?array $node, int $tagNumber): bool
{
return $node !== null && $node['class'] === self::CLASS_CONTEXT && $node['tag'] === $tagNumber;
}
public static function decodeOid(array $node): string
{
$bytes = $node['content'];
$first = ord($bytes[0]);
$arcs = [intdiv($first, 40), $first % 40];
$value = 0;
for ($i = 1, $n = strlen($bytes); $i < $n; $i++) {
$byte = ord($bytes[$i]);
$value = ($value << 7) | ($byte & 0x7f);
if (($byte & 0x80) === 0) {
$arcs[] = $value;
$value = 0;
}
}
return implode('.', $arcs);
}
public static function decodeTime(array $node): DateTimeImmutable
{
$utc = new DateTimeZone('UTC');
$text = $node['content'];
$parsed = match ($node['tag']) {
self::UTC_TIME => DateTimeImmutable::createFromFormat('ymdHis\Z', $text, $utc),
// Le eventuali frazioni di secondo vengono ignorate
self::GENERALIZED_TIME => DateTimeImmutable::createFromFormat(
'YmdHis', substr(preg_replace('/[.,]\d+/', '', $text), 0, 14), $utc
),
default => false,
};
if ($parsed === false) {
throw new Asn1Exception('valore temporale ASN.1 non valido');
}
return $parsed;
}
/** Contenuto di un INTEGER positivo, senza lo zero iniziale di segno. */
public static function integerBytes(array $node): string
{
$bytes = ltrim($node['content'], "\0");
return $bytes === '' ? "\0" : $bytes;
}
}
<?php
declare(strict_types=1);
namespace App\Asn1;
use RuntimeException;
final class Asn1Exception extends RuntimeException
{
}
<?php
declare(strict_types=1);
namespace App\Asn1;
/** Object identifier usati da CMS, CAdES e RFC 3161. */
final class Oid
{
public const DATA = '1.2.840.113549.1.7.1';
public const SIGNED_DATA = '1.2.840.113549.1.7.2';
public const TST_INFO = '1.2.840.113549.1.9.16.1.4';
public const CONTENT_TYPE = '1.2.840.113549.1.9.3';
public const MESSAGE_DIGEST = '1.2.840.113549.1.9.4';
public const SIGNING_TIME = '1.2.840.113549.1.9.5';
public const SIGNING_CERTIFICATE_V2 = '1.2.840.113549.1.9.16.2.47';
public const SIGNATURE_TIME_STAMP_TOKEN = '1.2.840.113549.1.9.16.2.14';
public const SHA256 = '2.16.840.1.101.3.4.2.1';
public const RSA_ENCRYPTION = '1.2.840.113549.1.1.1';
public const SHA256_WITH_RSA = '1.2.840.113549.1.1.11';
}
Alcune scelte sono dettate dalle regole DER. encodeLength usa la forma breve sotto i 128 byte e la forma lunga negli altri casi. set ordina gli elementi con SORT_STRING, che in PHP confronta le stringhe byte per byte, cioè l'ordinamento richiesto per un SET OF. unsignedInteger aggiunge uno zero iniziale quando il primo byte ha il bit alto impostato, altrimenti l'intero verrebbe interpretato come negativo. implicitConstructed non riordina nulla: serve per scrivere gli attributi firmati con il tag [0] mantenendo l'ordine già usato per firmarli.
Il decodificatore è volutamente rigido: rifiuta i tag in forma estesa, la lunghezza indefinita ammessa solo in BER e i byte in eccesso dopo la struttura. Le buste prodotte dalle altre implementazioni della serie e da OpenSSL sono tutte DER valido, e un servizio di verifica non ha motivo di accettare codifiche ambigue.
Configurazione e autenticazione
<?php
declare(strict_types=1);
namespace App;
use InvalidArgumentException;
final readonly class Config
{
/** @param array<int, array{client: string, key: string}> $apiKeys */
public function __construct(
public string $p12Path,
public string $p12Password,
public string $trustAnchorPath,
public string $crlPath,
public string $tsaUrl,
public array $apiKeys,
public string $auditDbPath,
public int $maxUploadBytes,
) {
}
public static function fromEnvironment(array $env): self
{
return new self(
p12Path: $env['SIGNER_P12_PATH'] ?? 'pki/out/signer.p12',
p12Password: $env['SIGNER_P12_PASSWORD'] ?? '',
trustAnchorPath: $env['TRUST_ANCHOR_PATH'] ?? 'pki/out/ca.crt',
crlPath: $env['CRL_PATH'] ?? 'pki/out/ca.crl',
tsaUrl: $env['TSA_URL'] ?? '',
apiKeys: self::parseApiKeys($env['API_KEYS'] ?? ''),
auditDbPath: $env['AUDIT_DB_PATH'] ?? 'data/audit.db',
maxUploadBytes: (int) ($env['MAX_UPLOAD_BYTES'] ?? 10 * 1024 * 1024),
);
}
/** Formato atteso: "client1:chiave1,client2:chiave2" */
public static function parseApiKeys(string $raw): array
{
$keys = [];
foreach (explode(',', $raw) as $item) {
$item = trim($item);
if ($item === '') {
continue;
}
$parts = explode(':', $item, 2);
if (count($parts) !== 2 || $parts[0] === '' || $parts[1] === '') {
throw new InvalidArgumentException("voce API_KEYS non valida: {$item}");
}
$keys[] = ['client' => $parts[0], 'key' => $parts[1]];
}
if ($keys === []) {
throw new InvalidArgumentException('API_KEYS deve contenere almeno una chiave');
}
return $keys;
}
}
Config è una classe readonly con argomenti nominati, il che rende leggibile anche la sua costruzione nei test. L'autenticatore confronta gli hash SHA-256 delle chiavi con hash_equals, che ha tempo costante, e scorre sempre l'intero elenco.
<?php
declare(strict_types=1);
namespace App;
final class ApiKeyAuthenticator
{
/** @var array<int, array{client: string, digest: string}> */
private array $keys = [];
public function __construct(array $keys)
{
// Si confrontano i digest: lunghezza fissa, nessuna informazione sulla lunghezza della chiave
foreach ($keys as $entry) {
$this->keys[] = ['client' => $entry['client'], 'digest' => hash('sha256', $entry['key'], true)];
}
}
public function authenticate(?string $provided): ?string
{
if ($provided === null || $provided === '') {
return null;
}
$digest = hash('sha256', $provided, true);
$matched = null;
// Nessuna uscita anticipata: si confrontano sempre tutte le chiavi
foreach ($this->keys as $entry) {
if (hash_equals($entry['digest'], $digest)) {
$matched = $entry['client'];
}
}
return $matched;
}
}
Il Signer: dove vive la chiave privata
<?php
declare(strict_types=1);
namespace App\Cades;
/** Astrazione sulla chiave privata: PKCS#12, PKCS#11 o KMS. */
interface Signer
{
/** Certificato del firmatario in formato DER. */
public function certificateDer(): string;
/** Firma RSA PKCS#1 v1.5 con SHA-256 di $data. */
public function sign(string $data): string;
}
<?php
declare(strict_types=1);
namespace App\Cades;
use OpenSSLAsymmetricKey;
use RuntimeException;
final class Pkcs12Signer implements Signer
{
private OpenSSLAsymmetricKey $key;
private string $certificateDer;
public function __construct(string $path, string $password)
{
$data = @file_get_contents($path);
if ($data === false || !openssl_pkcs12_read($data, $bundle, $password)) {
throw new RuntimeException('impossibile leggere il keystore PKCS#12: ' . openssl_error_string());
}
$key = openssl_pkey_get_private($bundle['pkey']);
if ($key === false || openssl_pkey_get_details($key)['type'] !== OPENSSL_KEYTYPE_RSA) {
throw new RuntimeException('il servizio supporta solo chiavi RSA');
}
$this->key = $key;
$this->certificateDer = Certificates::pemToDer($bundle['cert']);
}
public function certificateDer(): string
{
return $this->certificateDer;
}
public function sign(string $data): string
{
if (!openssl_sign($data, $signature, $this->key, OPENSSL_ALGO_SHA256)) {
throw new RuntimeException('firma RSA non riuscita: ' . openssl_error_string());
}
return $signature;
}
}
openssl_pkcs12_read decifra il keystore e restituisce chiave e certificato in PEM. Il certificato viene convertito subito in DER, il formato che serve sia per la busta CMS sia per l'hash di signingCertificateV2. openssl_sign con OPENSSL_ALGO_SHA256 produce una firma RSA PKCS#1 v1.5 calcolando internamente l'hash dei dati ricevuti.
La classe Certificates raccoglie le operazioni sui certificati. fields estrae dal DER i nodi di numero di serie, emittente e soggetto, saltando il campo version se presente: servono nella forma originale per l'IssuerAndSerialNumber e per riconoscere il certificato del firmatario. describe usa openssl_x509_parse per i nomi e le date; i nomi vengono composti in ordine RFC 4514, dal più specifico al più generale.
<?php
declare(strict_types=1);
namespace App\Cades;
use App\Asn1\Der;
use RuntimeException;
final class Certificates
{
public static function pemToDer(string $pem): string
{
if (!preg_match('/-----BEGIN CERTIFICATE-----(.+?)-----END CERTIFICATE-----/s', $pem, $match)) {
throw new RuntimeException('certificato PEM non valido');
}
return base64_decode(preg_replace('/\s+/', '', $match[1]), true);
}
public static function derToPem(string $der): string
{
return "-----BEGIN CERTIFICATE-----\n" . chunk_split(base64_encode($der), 64, "\n") . "-----END CERTIFICATE-----\n";
}
/** Nodi DER di serialNumber, issuer e subject. */
public static function fields(string $der): array
{
$tbs = Der::decode($der)['children'][0]['children'];
// Il campo version e' facoltativo ed e' marcato con [0] EXPLICIT
$offset = Der::isContext($tbs[0], 0) ? 1 : 0;
return [
'serial' => $tbs[$offset],
'issuer' => $tbs[$offset + 2],
'subject' => $tbs[$offset + 4],
];
}
public static function normalizeSerial(string $hex): string
{
$hex = ltrim(strtolower($hex), '0');
return $hex === '' ? '0' : $hex;
}
public static function serialHex(string $der): string
{
return self::normalizeSerial(bin2hex(Der::integerBytes(self::fields($der)['serial'])));
}
/** "CN=...,O=...,C=IT" (ordine RFC 4514) */
public static function formatName(array $name): string
{
$parts = [];
foreach ($name as $attribute => $value) {
foreach ((array) $value as $item) {
$parts[] = "{$attribute}={$item}";
}
}
return implode(',', array_reverse($parts));
}
public static function describe(string $der): array
{
$info = openssl_x509_parse(self::derToPem($der));
return [
'subject' => self::formatName($info['subject']),
'issuer' => self::formatName($info['issuer']),
'serialNumber' => self::serialHex($der),
'notBefore' => gmdate('Y-m-d\TH:i:s\Z', $info['validFrom_time_t']),
'notAfter' => gmdate('Y-m-d\TH:i:s\Z', $info['validTo_time_t']),
];
}
}
Il client della TSA
<?php
declare(strict_types=1);
namespace App\Cades;
use App\Asn1\Der;
use App\Asn1\Oid;
use DateTimeImmutable;
/** Lettura di un TimeStampToken RFC 3161 (ContentInfo -> SignedData -> TSTInfo). */
final readonly class TimeStampToken
{
private function __construct(
public array $signedData,
public string $tstInfoDer,
public string $hashAlgorithm,
public string $hashedMessage,
public DateTimeImmutable $genTime,
public ?string $nonce,
) {
}
public static function fromNode(array $contentInfo): self
{
$signedData = $contentInfo['children'][1]['children'][0];
$encapContentInfo = $signedData['children'][2];
if (Der::decodeOid($encapContentInfo['children'][0]) !== Oid::TST_INFO) {
throw new TsaException('il token non contiene un TSTInfo');
}
$tstInfoDer = $encapContentInfo['children'][1]['children'][0]['content'];
$fields = Der::decode($tstInfoDer)['children'];
// TSTInfo: version, policy, messageImprint, serialNumber, genTime, [accuracy], [ordering], [nonce], ...
$nonce = null;
foreach (array_slice($fields, 5) as $field) {
if (Der::isUniversal($field, Der::INTEGER)) {
$nonce = Der::integerBytes($field);
break;
}
}
return new self(
signedData: $signedData,
tstInfoDer: $tstInfoDer,
hashAlgorithm: Der::decodeOid($fields[2]['children'][0]['children'][0]),
hashedMessage: $fields[2]['children'][1]['content'],
genTime: Der::decodeTime($fields[4]),
nonce: $nonce,
);
}
}
<?php
declare(strict_types=1);
namespace App\Cades;
use App\Asn1\Asn1Exception;
use App\Asn1\Der;
use App\Asn1\Oid;
/** Client RFC 3161 minimale: invia una TimeStampReq e restituisce il token DER. */
final class TsaClient
{
public function __construct(private string $url, private int $timeoutSeconds = 10)
{
}
/** @return array{token: string, genTime: \DateTimeImmutable} */
public function timestamp(string $data): array
{
$digest = hash('sha256', $data, true);
// Nonce positivo a 64 bit: primo byte con bit alto a zero e diverso da zero
$nonce = random_bytes(8);
$nonce[0] = chr((ord($nonce[0]) & 0x7f) | 0x40);
$request = Der::sequence(
Der::integer(1),
Der::sequence(Der::sequence(Der::oid(Oid::SHA256)), Der::octetString($digest)),
Der::unsignedInteger($nonce),
Der::boolean(true), // certReq: la TSA deve includere il proprio certificato
);
$curl = curl_init($this->url);
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $request,
CURLOPT_HTTPHEADER => ['Content-Type: application/timestamp-query'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeoutSeconds,
]);
$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
$error = curl_error($curl);
if ($body === false) {
throw new TsaException("TSA non raggiungibile: {$error}");
}
if ($status !== 200) {
throw new TsaException("la TSA ha risposto con HTTP {$status}");
}
try {
$reply = Der::decode($body);
// PKIStatus: 0 = granted, 1 = grantedWithMods
$pkiStatus = ord(Der::integerBytes($reply['children'][0]['children'][0]));
if ($pkiStatus > 1 || count($reply['children']) < 2) {
throw new TsaException("richiesta rifiutata dalla TSA (status {$pkiStatus})");
}
$tokenNode = $reply['children'][1];
$token = TimeStampToken::fromNode($tokenNode);
} catch (Asn1Exception $exception) {
throw new TsaException('risposta della TSA non valida: ' . $exception->getMessage());
}
if ($token->nonce === null || !hash_equals($token->nonce, $nonce)) {
throw new TsaException('nonce della TSA non corrispondente');
}
if (!hash_equals($token->hashedMessage, $digest)) {
throw new TsaException('impronta della TSA non corrispondente');
}
return ['token' => $tokenNode['raw'], 'genTime' => $token->genTime];
}
}
<?php
declare(strict_types=1);
namespace App\Cades;
use RuntimeException;
final class TsaException extends RuntimeException
{
}
La richiesta RFC 3161 si scrive in poche righe con il codec: versione, impronta, nonce e certReq. Il nonce è di 8 byte casuali con il primo byte forzato tra 0x40 e 0x7f, così l'intero è positivo e la codifica minima. La chiamata usa cURL con un timeout esplicito; la risposta viene decodificata e il token letto con TimeStampToken::fromNode, che percorre ContentInfo, SignedData ed EncapsulatedContentInfo fino al TSTInfo. Il nonce è il primo INTEGER dopo genTime, perché i campi intermedi sono facoltativi. Il client restituisce il campo raw del token, cioè i suoi byte originali: ricodificarlo rischierebbe di invalidare la firma della TSA.
La costruzione della firma CAdES
<?php
declare(strict_types=1);
namespace App\Cades;
use DateTimeImmutable;
final readonly class SignatureResult
{
public function __construct(
public string $der,
public string $profile,
public string $documentSha256,
public string $certificateSerial,
public DateTimeImmutable $signingTime,
public ?DateTimeImmutable $timestamp,
) {
}
}
<?php
declare(strict_types=1);
namespace App\Cades;
use App\Asn1\Der;
use App\Asn1\Oid;
use DateTimeImmutable;
final class CadesSigner
{
public function __construct(private Signer $signer, private ?TsaClient $tsa = null)
{
}
private static function attribute(string $type, string $value): string
{
return Der::sequence(Der::oid($type), Der::set($value));
}
/** @return list<string> attributi firmati gia' ordinati secondo DER */
public static function signedAttributes(string $contentDigest, string $certificateDer, DateTimeImmutable $signingTime): array
{
return Der::sortSet([
self::attribute(Oid::CONTENT_TYPE, Der::oid(Oid::DATA)),
self::attribute(Oid::SIGNING_TIME, Der::utcTime($signingTime)),
self::attribute(Oid::MESSAGE_DIGEST, Der::octetString($contentDigest)),
// SigningCertificateV2 { certs: [ ESSCertIDv2 { certHash } ] }, hashAlgorithm di default SHA-256
self::attribute(Oid::SIGNING_CERTIFICATE_V2, Der::sequence(Der::sequence(Der::sequence(
Der::octetString(hash('sha256', $certificateDer, true))
)))),
]);
}
public function sign(string $content): SignatureResult
{
$certificateDer = $this->signer->certificateDer();
$contentDigest = hash('sha256', $content, true);
// Precisione al secondo, come richiesto da UTCTime
$signingTime = new DateTimeImmutable('@' . time());
$attributes = self::signedAttributes($contentDigest, $certificateDer, $signingTime);
// Si firma il SET OF con tag universale (0x31), poi lo si inserisce come [0] IMPLICIT
$signature = $this->signer->sign(Der::tlv(0x31, implode('', $attributes)));
$fields = Certificates::fields($certificateDer);
$signerInfo = [
Der::integer(1),
Der::sequence($fields['issuer']['raw'], $fields['serial']['raw']), // IssuerAndSerialNumber
Der::sequence(Der::oid(Oid::SHA256)),
Der::implicitConstructed(0, $attributes),
Der::sequence(Der::oid(Oid::RSA_ENCRYPTION), Der::null()),
Der::octetString($signature),
];
$profile = 'CAdES-BES';
$timestamp = null;
if ($this->tsa !== null) {
// CAdES-T: la marca temporale copre il valore della firma
$result = $this->tsa->timestamp($signature);
$signerInfo[] = Der::implicitConstructed(1, [
self::attribute(Oid::SIGNATURE_TIME_STAMP_TOKEN, $result['token']),
]);
$profile = 'CAdES-T';
$timestamp = $result['genTime'];
}
$signedData = Der::sequence(
Der::integer(1),
Der::set(Der::sequence(Der::oid(Oid::SHA256))),
Der::sequence(Der::oid(Oid::DATA)), // eContent assente: firma detached
Der::implicitConstructed(0, [$certificateDer]),
Der::set(Der::sequence(...$signerInfo)),
);
$contentInfo = Der::sequence(Der::oid(Oid::SIGNED_DATA), Der::explicit(0, $signedData));
return new SignatureResult(
der: $contentInfo,
profile: $profile,
documentSha256: bin2hex($contentDigest),
certificateSerial: Certificates::serialHex($certificateDer),
signingTime: $signingTime,
timestamp: $timestamp,
);
}
}
signedAttributes crea i quattro attributi e li restituisce già ordinati con Der::sortSet. Lo stesso array viene usato due volte: con Der::tlv(0x31, ...) per calcolare la firma sulla codifica con tag SET, e con Der::implicitConstructed(0, ...) per scriverlo nel SignerInfo con tag [0]. Avere un'unica fonte per entrambe le codifiche elimina alla radice il rischio di un disallineamento.
L'IssuerAndSerialNumber riusa i byte raw dell'emittente e del numero di serie letti dal certificato, senza ricodificarli. L'algoritmo di hash è dichiarato senza parametri, come raccomanda RFC 5754 per SHA-2, quello di firma come rsaEncryption con il NULL previsto da PKCS#1. L'encapContentInfo contiene solo il tipo data: la firma è detached. Il signingTime nasce da time(), quindi è già troncato al secondo come UTCTime richiede.
Il controllo di revoca
<?php
declare(strict_types=1);
namespace App\Cades;
use DateTimeImmutable;
use phpseclib3\File\X509;
use phpseclib3\Math\BigInteger;
use RuntimeException;
/** Controllo di revoca basato su una CRL locale, ricaricata quando il file cambia. */
final class CrlChecker
{
private ?X509 $crl = null;
private int $mtime = 0;
public function __construct(private string $path, private string $issuerPem)
{
$this->reload();
}
private function reload(): void
{
clearstatcache(true, $this->path);
$mtime = @filemtime($this->path);
if ($mtime === false) {
throw new RuntimeException('CRL non trovata');
}
if ($this->crl !== null && $mtime === $this->mtime) {
return;
}
$x509 = new X509();
$x509->loadCA($this->issuerPem);
// loadCRL riconosce automaticamente DER e PEM
if ($x509->loadCRL(file_get_contents($this->path)) === false) {
throw new RuntimeException('CRL non leggibile');
}
// validateSignature cerca tra le CA caricate quella che ha emesso la CRL
if ($x509->validateSignature() !== true) {
throw new RuntimeException('firma della CRL non valida o emittente non fidato');
}
$this->crl = $x509;
$this->mtime = $mtime;
}
/** @return 'good'|'revoked'|'unknown' */
public function status(string $certificateDer, DateTimeImmutable $now): string
{
try {
$this->reload();
} catch (RuntimeException) {
return 'unknown';
}
$tbs = $this->crl->getCurrentCert()['tbsCertList'];
if (isset($tbs['nextUpdate'])) {
$nextUpdate = new DateTimeImmutable($tbs['nextUpdate']['utcTime'] ?? $tbs['nextUpdate']['generalTime']);
if ($now > $nextUpdate) {
// CRL scaduta: non si puo' affermare che il certificato sia valido
return 'unknown';
}
}
$serial = new BigInteger(Certificates::serialHex($certificateDer), 16);
return $this->crl->getRevoked($serial->toString()) !== false ? 'revoked' : 'good';
}
}
phpseclib semplifica molto questa parte. loadCA registra la CA fidata, loadCRL riconosce automaticamente DER e PEM e validateSignature cerca tra le CA caricate quella il cui soggetto coincide con l'emittente della CRL, verificandone la firma. Una CRL di un'altra CA o con una firma non valida viene quindi rifiutata. getRevoked si aspetta il numero di serie in forma decimale, ottenuto convertendo l'esadecimale con BigInteger. La data nextUpdate arriva da phpseclib come stringa nel formato RFC 2822, che DateTimeImmutable legge direttamente.
Prima di leggere la data di modifica viene chiamato clearstatcache: PHP memorizza i risultati di filemtime durante la richiesta, e con un processo persistente il ricaricamento della CRL non funzionerebbe senza questa chiamata.
La verifica
<?php
declare(strict_types=1);
namespace App\Cades;
use RuntimeException;
final class MalformedSignatureException extends RuntimeException
{
}
<?php
declare(strict_types=1);
namespace App\Cades;
use App\Asn1\Der;
use App\Asn1\Oid;
use DateTimeImmutable;
use DateTimeZone;
use Throwable;
final class SignatureVerifier
{
private const RSA_SIGNATURE_OIDS = [Oid::RSA_ENCRYPTION, Oid::SHA256_WITH_RSA];
private string $trustAnchorPem;
public function __construct(string $trustAnchorPem, private CrlChecker $crlChecker)
{
$this->trustAnchorPem = $trustAnchorPem;
}
/** Converte un elenco di Attribute in una mappa OID => primo valore. */
private static function attributeMap(?array $node): array
{
$map = [];
foreach ($node['children'] ?? [] as $attribute) {
$map[Der::decodeOid($attribute['children'][0])] = $attribute['children'][1]['children'][0];
}
return $map;
}
/** Scompone un SignerInfo nei suoi campi, gestendo quelli facoltativi. */
private static function readSignerInfo(array $node): array
{
$fields = $node['children'];
$index = 2;
$info = ['sid' => $fields[1], 'digestAlgorithm' => Der::decodeOid($fields[$index++]['children'][0])];
$info['signedAttrs'] = Der::isContext($fields[$index], 0) ? $fields[$index++] : null;
$info['signatureAlgorithm'] = Der::decodeOid($fields[$index++]['children'][0]);
$info['signature'] = $fields[$index++]['content'];
$info['unsignedAttrs'] = Der::isContext($fields[$index] ?? null, 1) ? $fields[$index] : null;
return $info;
}
private static function findCertificate(array $signedData, array $sid): string
{
foreach ($signedData['children'] as $child) {
if (!Der::isContext($child, 0)) {
continue;
}
foreach ($child['children'] as $certificate) {
$fields = Certificates::fields($certificate['raw']);
if ($fields['issuer']['raw'] === $sid['children'][0]['raw']
&& $fields['serial']['raw'] === $sid['children'][1]['raw']) {
return $certificate['raw'];
}
}
}
throw new MalformedSignatureException('certificato del firmatario non presente nella busta CMS');
}
/**
* Verifica messageDigest e firma dell'unico SignerInfo rispetto a $content.
*
* @return array{certificate: string, signerInfo: array, ok: bool, errors: list<string>}
*/
public static function verifySignedData(array $signedData, string $content): array
{
$signerInfos = end($signedData['children']);
if (count($signerInfos['children']) !== 1) {
throw new MalformedSignatureException("e' atteso esattamente un firmatario");
}
$signerInfo = self::readSignerInfo($signerInfos['children'][0]);
$certificate = self::findCertificate($signedData, $signerInfo['sid']);
$result = ['certificate' => $certificate, 'signerInfo' => $signerInfo, 'ok' => false, 'errors' => []];
if ($signerInfo['digestAlgorithm'] !== Oid::SHA256) {
$result['errors'][] = 'algoritmo di digest non supportato';
return $result;
}
if ($signerInfo['signedAttrs'] === null) {
$result['errors'][] = 'attributi firmati assenti';
return $result;
}
$attributes = self::attributeMap($signerInfo['signedAttrs']);
$messageDigest = $attributes[Oid::MESSAGE_DIGEST]['content'] ?? null;
if ($messageDigest === null || !hash_equals($messageDigest, hash('sha256', $content, true))) {
$result['errors'][] = 'il documento non corrisponde alla firma (messageDigest)';
return $result;
}
if (!in_array($signerInfo['signatureAlgorithm'], self::RSA_SIGNATURE_OIDS, true)) {
$result['errors'][] = 'algoritmo di firma non supportato';
return $result;
}
// La firma copre gli attributi codificati come SET OF (tag 0x31), non come [0]
$signedBytes = Der::tlv(0x31, $signerInfo['signedAttrs']['content']);
$publicKey = openssl_pkey_get_public(Certificates::derToPem($certificate));
if (openssl_verify($signedBytes, $signerInfo['signature'], $publicKey, OPENSSL_ALGO_SHA256) !== 1) {
$result['errors'][] = 'firma crittografica non valida';
return $result;
}
$result['ok'] = true;
return $result;
}
public function verify(string $content, string $signatureDer): array
{
try {
$contentInfo = Der::decode($signatureDer);
if (Der::decodeOid($contentInfo['children'][0]) !== Oid::SIGNED_DATA) {
throw new MalformedSignatureException("la busta non e' una SignedData");
}
$signedData = $contentInfo['children'][1]['children'][0];
if (count($signedData['children'][2]['children']) > 1) {
throw new MalformedSignatureException('attesa una firma detached');
}
$verified = self::verifySignedData($signedData, $content);
} catch (MalformedSignatureException $exception) {
throw $exception;
} catch (Throwable $exception) {
throw new MalformedSignatureException('busta CMS non leggibile: ' . $exception->getMessage(), 0, $exception);
}
$now = new DateTimeImmutable('now', new DateTimeZone('UTC'));
$certificate = $verified['certificate'];
$signerInfo = $verified['signerInfo'];
$attributes = self::attributeMap($signerInfo['signedAttrs']);
$result = [
'valid' => false,
'profile' => 'CAdES-BES',
'signer' => Certificates::describe($certificate),
'signingTime' => isset($attributes[Oid::SIGNING_TIME])
? self::iso(Der::decodeTime($attributes[Oid::SIGNING_TIME])) : null,
'timestamp' => null,
'checks' => [
'signature' => $verified['ok'],
'signingCertificate' => self::checkSigningCertificate($attributes, $certificate),
'chain' => $this->checkChain($certificate, $now),
'revocation' => $this->crlChecker->status($certificate, $now),
],
'errors' => $verified['errors'],
];
if (!$result['checks']['signingCertificate']) {
$result['errors'][] = 'attributo signingCertificateV2 assente o non corrispondente';
}
if (!$result['checks']['chain']) {
$result['errors'][] = "certificato non emesso dalla CA fidata o fuori validita'";
}
if ($result['checks']['revocation'] !== 'good') {
$result['errors'][] = 'stato di revoca: ' . $result['checks']['revocation'];
}
$token = self::attributeMap($signerInfo['unsignedAttrs'])[Oid::SIGNATURE_TIME_STAMP_TOKEN] ?? null;
if ($token !== null) {
$result['profile'] = 'CAdES-T';
$result['timestamp'] = self::checkTimestamp($token, $signerInfo['signature']);
if (!$result['timestamp']['valid']) {
$result['errors'][] = 'marca temporale non valida';
}
}
$result['valid'] = $result['checks']['signature']
&& $result['checks']['signingCertificate']
&& $result['checks']['chain']
&& $result['checks']['revocation'] === 'good'
&& ($result['timestamp'] === null || $result['timestamp']['valid']);
return $result;
}
private static function checkSigningCertificate(array $attributes, string $certificate): bool
{
$essCertId = $attributes[Oid::SIGNING_CERTIFICATE_V2]['children'][0]['children'][0] ?? null;
if ($essCertId === null) {
return false;
}
$index = 0;
// hashAlgorithm e' facoltativo: se presente deve essere SHA-256
if (Der::isUniversal($essCertId['children'][0], Der::SEQUENCE)) {
if (Der::decodeOid($essCertId['children'][0]['children'][0]) !== Oid::SHA256) {
return false;
}
$index = 1;
}
return hash_equals($essCertId['children'][$index]['content'], hash('sha256', $certificate, true));
}
private function checkChain(string $certificate, DateTimeImmutable $now): bool
{
$pem = Certificates::derToPem($certificate);
$info = openssl_x509_parse($pem);
$anchor = openssl_x509_parse($this->trustAnchorPem);
if ($info === false || $anchor === false || $info['issuer'] !== $anchor['subject']) {
return false;
}
// openssl_x509_verify restituisce 1 se la firma della CA sul certificato e' valida
if (openssl_x509_verify($pem, openssl_pkey_get_public($this->trustAnchorPem)) !== 1) {
return false;
}
$timestamp = $now->getTimestamp();
return $timestamp >= $info['validFrom_time_t'] && $timestamp <= $info['validTo_time_t'];
}
private static function checkTimestamp(array $tokenNode, string $signatureValue): array
{
$info = ['time' => null, 'tsa' => null, 'valid' => false];
try {
$token = TimeStampToken::fromNode($tokenNode);
$info['time'] = self::iso($token->genTime);
$verified = self::verifySignedData($token->signedData, $token->tstInfoDer);
$info['tsa'] = Certificates::describe($verified['certificate'])['subject'];
$info['valid'] = $verified['ok']
&& $token->hashAlgorithm === Oid::SHA256
&& hash_equals($token->hashedMessage, hash('sha256', $signatureValue, true));
} catch (Throwable) {
$info['valid'] = false;
}
return $info;
}
public static function iso(?DateTimeImmutable $time): ?string
{
return $time?->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d\TH:i:s\Z');
}
}
Il metodo statico verifySignedData è il cuore della verifica ed è usato sia per la firma principale sia per il token della TSA. Legge il SignerInfo gestendo i campi facoltativi tramite i tag di contesto, cerca il certificato confrontando emittente e numero di serie in forma binaria, controlla messageDigest e infine verifica la firma con openssl_verify.
La ricodifica degli attributi firmati è un'unica riga: Der::tlv(0x31, $signerInfo['signedAttrs']['content']). Il nodo [0] conserva il contenuto originale, e basta riavvolgerlo con il tag SET per ottenere esattamente i byte firmati, senza alcuna ricodifica dei singoli attributi.
La catena viene controllata in tre passi: l'emittente del certificato deve coincidere con il soggetto della CA, openssl_x509_verify deve confermare la firma della CA sul certificato e l'istante corrente deve cadere nel periodo di validità. Il controllo di signingCertificateV2 tiene conto del campo hashAlgorithm facoltativo, e quello della marca temporale riusa verifySignedData sul TSTInfo prima di confrontare l'impronta con l'hash del valore della firma. Ogni eccezione inattesa durante il parsing diventa una MalformedSignatureException, che il kernel traduce in un 400.
Audit
<?php
declare(strict_types=1);
namespace App;
use PDO;
/** Registro append-only: si salvano solo metadati, mai il documento. */
final class AuditLog
{
private const SCHEMA = <<<'SQL'
CREATE TABLE IF NOT EXISTS audit_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TEXT NOT NULL,
client TEXT NOT NULL,
operation TEXT NOT NULL,
document_sha256 TEXT NOT NULL,
certificate_serial TEXT,
outcome TEXT NOT NULL,
remote_addr TEXT
)
SQL;
private PDO $db;
public function __construct(string $path)
{
if ($path !== ':memory:' && !is_dir(dirname($path))) {
mkdir(dirname($path), 0750, true);
}
$this->db = new PDO('sqlite:' . $path, options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$this->db->exec('PRAGMA journal_mode = WAL');
$this->db->exec(self::SCHEMA);
}
public function record(
string $client,
string $operation,
string $documentSha256,
?string $certificateSerial,
string $outcome,
?string $remoteAddr,
): void {
$statement = $this->db->prepare(
'INSERT INTO audit_log (created_at, client, operation, document_sha256, certificate_serial, outcome, remote_addr)
VALUES (?, ?, ?, ?, ?, ?, ?)'
);
$statement->execute([
gmdate('Y-m-d\TH:i:s\Z'), $client, $operation, $documentSha256, $certificateSerial, $outcome, $remoteAddr,
]);
}
public function count(): int
{
return (int) $this->db->query('SELECT COUNT(*) FROM audit_log')->fetchColumn();
}
}
PDO con SQLite è più che sufficiente per un registro append-only. La modalità WAL permette letture concorrenti alle scritture, utile quando più processi PHP scrivono sullo stesso file. Come nelle altre implementazioni, nel registro finiscono solo metadati.
Lo strato HTTP
Le richieste sono rappresentate da un oggetto immutabile costruito dalle superglobali. Avere una Request separata da $_SERVER e $_FILES è ciò che permette di testare il kernel senza un server web.
<?php
declare(strict_types=1);
namespace App\Http;
/** Rappresentazione minimale e testabile di una richiesta HTTP. */
final readonly class Request
{
/**
* @param array<string, string> $headers intestazioni con nome in minuscolo
* @param array<string, array{name: string, tmp_name: string, size: int, error: int}> $files
*/
public function __construct(
public string $method,
public string $path,
public array $headers = [],
public array $files = [],
public ?string $remoteAddr = null,
) {
}
public static function fromGlobals(): self
{
$headers = [];
foreach ($_SERVER as $name => $value) {
if (str_starts_with($name, 'HTTP_')) {
$headers[strtolower(str_replace('_', '-', substr($name, 5)))] = (string) $value;
}
}
if (isset($_SERVER['CONTENT_LENGTH'])) {
$headers['content-length'] = (string) $_SERVER['CONTENT_LENGTH'];
}
if (isset($_SERVER['CONTENT_TYPE'])) {
$headers['content-type'] = (string) $_SERVER['CONTENT_TYPE'];
}
return new self(
method: $_SERVER['REQUEST_METHOD'] ?? 'GET',
path: parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/',
headers: $headers,
files: $_FILES,
remoteAddr: $_SERVER['REMOTE_ADDR'] ?? null,
);
}
public function header(string $name): ?string
{
return $this->headers[strtolower($name)] ?? null;
}
}
<?php
declare(strict_types=1);
namespace App\Http;
final readonly class Response
{
public function __construct(
public int $status,
public string $body,
public array $headers = [],
) {
}
public static function json(array $data, int $status = 200): self
{
$body = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
return new self($status, $body, ['Content-Type' => 'application/json; charset=utf-8']);
}
public static function error(int $status, string $code, string $message): self
{
return self::json(['error' => ['code' => $code, 'message' => $message]], $status);
}
public function send(): void
{
http_response_code($this->status);
foreach ($this->headers as $name => $value) {
header("{$name}: {$value}");
}
echo $this->body;
}
}
<?php
declare(strict_types=1);
namespace App\Http;
use RuntimeException;
final class ApiException extends RuntimeException
{
public function __construct(public readonly int $status, public readonly string $errorCode, string $message)
{
parent::__construct($message);
}
}
<?php
declare(strict_types=1);
namespace App\Http;
use App\ApiKeyAuthenticator;
use App\AuditLog;
use App\Cades\CadesSigner;
use App\Cades\Certificates;
use App\Cades\CrlChecker;
use App\Cades\MalformedSignatureException;
use App\Cades\Pkcs12Signer;
use App\Cades\SignatureVerifier;
use App\Cades\Signer;
use App\Cades\TsaClient;
use App\Cades\TsaException;
use App\Config;
use Throwable;
final class Kernel
{
private const PKCS7_MEDIA_TYPE = 'application/pkcs7-signature';
private Signer $signer;
private CadesSigner $cades;
private SignatureVerifier $verifier;
private ApiKeyAuthenticator $auth;
public readonly AuditLog $audit;
public function __construct(private Config $config)
{
$this->signer = new Pkcs12Signer($config->p12Path, $config->p12Password);
$trustAnchorPem = file_get_contents($config->trustAnchorPath);
$tsa = $config->tsaUrl !== '' ? new TsaClient($config->tsaUrl) : null;
$this->cades = new CadesSigner($this->signer, $tsa);
$this->verifier = new SignatureVerifier($trustAnchorPem, new CrlChecker($config->crlPath, $trustAnchorPem));
$this->auth = new ApiKeyAuthenticator($config->apiKeys);
$this->audit = new AuditLog($config->auditDbPath);
}
public function handle(Request $request): Response
{
try {
return match ([$request->method, $request->path]) {
['GET', '/health'] => Response::json(['status' => 'ok']),
['GET', '/api/certificate'] => $this->certificate($request),
['POST', '/api/sign'] => $this->sign($request),
['POST', '/api/verify'] => $this->verify($request),
default => Response::error(404, 'NOT_FOUND', 'risorsa non trovata'),
};
} catch (ApiException $exception) {
return Response::error($exception->status, $exception->errorCode, $exception->getMessage());
} catch (Throwable $exception) {
error_log((string) $exception);
return Response::error(500, 'INTERNAL', 'errore interno');
}
}
private function authenticate(Request $request): string
{
$client = $this->auth->authenticate($request->header('X-API-Key'));
if ($client === null) {
throw new ApiException(401, 'UNAUTHORIZED', 'API key mancante o non valida');
}
return $client;
}
/** Legge un file caricato verificando errori e limite di dimensione. */
private function readUpload(Request $request, string $field): array
{
$contentLength = (int) ($request->header('Content-Length') ?? 0);
$upload = $request->files[$field] ?? null;
if ($upload === null) {
// Se il corpo supera post_max_size PHP scarta silenziosamente tutti i file
if ($contentLength > $this->config->maxUploadBytes) {
throw new ApiException(413, 'PAYLOAD_TOO_LARGE', 'richiesta troppo grande');
}
throw new ApiException(400, 'BAD_REQUEST', "campo \"{$field}\" mancante");
}
if (is_array($upload['error'])) {
throw new ApiException(400, 'BAD_REQUEST', "campo \"{$field}\" duplicato");
}
if (in_array($upload['error'], [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE], true)
|| $upload['size'] > $this->config->maxUploadBytes) {
throw new ApiException(413, 'PAYLOAD_TOO_LARGE', 'file troppo grande');
}
if ($upload['error'] !== UPLOAD_ERR_OK) {
throw new ApiException(400, 'BAD_REQUEST', "caricamento di \"{$field}\" non riuscito");
}
return ['name' => $upload['name'], 'data' => file_get_contents($upload['tmp_name'])];
}
private function certificate(Request $request): Response
{
$this->authenticate($request);
$der = $this->signer->certificateDer();
return Response::json(Certificates::describe($der) + [
'sha256Fingerprint' => hash('sha256', $der),
'pem' => Certificates::derToPem($der),
]);
}
private function sign(Request $request): Response
{
$client = $this->authenticate($request);
$file = $this->readUpload($request, 'file');
try {
$result = $this->cades->sign($file['data']);
} catch (TsaException $exception) {
$this->audit->record($client, 'sign', hash('sha256', $file['data']), null, 'error', $request->remoteAddr);
throw new ApiException(502, 'TSA_UNAVAILABLE', $exception->getMessage());
}
$this->audit->record(
$client, 'sign', $result->documentSha256, $result->certificateSerial, 'ok', $request->remoteAddr
);
if (str_contains($request->header('Accept') ?? '', self::PKCS7_MEDIA_TYPE)) {
$filename = preg_replace('/["\\\\\r\n]/', '_', ($file['name'] ?: 'document') . '.p7s');
return new Response(200, $result->der, [
'Content-Type' => self::PKCS7_MEDIA_TYPE,
'Content-Disposition' => "attachment; filename=\"{$filename}\"",
]);
}
return Response::json([
'signature' => base64_encode($result->der),
'encoding' => 'base64-der',
'profile' => $result->profile,
'sha256' => $result->documentSha256,
'certificateSerial' => $result->certificateSerial,
'signingTime' => SignatureVerifier::iso($result->signingTime),
'timestamp' => SignatureVerifier::iso($result->timestamp),
]);
}
private function verify(Request $request): Response
{
$client = $this->authenticate($request);
$file = $this->readUpload($request, 'file');
$signature = self::decodeSignature($this->readUpload($request, 'signature')['data']);
$documentSha256 = hash('sha256', $file['data']);
try {
$result = $this->verifier->verify($file['data'], $signature);
} catch (MalformedSignatureException $exception) {
$this->audit->record($client, 'verify', $documentSha256, null, 'error', $request->remoteAddr);
throw new ApiException(400, 'MALFORMED_SIGNATURE', $exception->getMessage());
}
$this->audit->record(
$client, 'verify', $documentSha256, $result['signer']['serialNumber'],
$result['valid'] ? 'valid' : 'invalid', $request->remoteAddr,
);
return Response::json($result);
}
private static function decodeSignature(string $raw): string
{
// DER binario (SEQUENCE, 0x30) oppure base64 come restituito da /api/sign
if ($raw !== '' && $raw[0] === "\x30") {
return $raw;
}
$decoded = base64_decode(preg_replace('/\s+/', '', $raw), true);
if ($decoded === false || $decoded === '') {
throw new ApiException(400, 'MALFORMED_SIGNATURE', 'firma non in formato DER o base64');
}
return $decoded;
}
}
<?php
declare(strict_types=1);
use App\Config;
use App\Http\Kernel;
use App\Http\Request;
require dirname(__DIR__) . '/vendor/autoload.php';
// I percorsi relativi della configurazione si risolvono dalla radice del progetto
chdir(dirname(__DIR__));
// Come di consueto in PHP il kernel nasce e muore con la richiesta.
// Con Apache le variabili passate con PassEnv compaiono in $_SERVER.
$kernel = new Kernel(Config::fromEnvironment(getenv() + $_SERVER));
$kernel->handle(Request::fromGlobals())->send();
Il kernel instrada con un match sulla coppia metodo e percorso: con quattro rotte non serve un router. Ogni handler autentica la richiesta, legge gli upload, invoca il nucleo crittografico, registra l'audit e costruisce la risposta.
La gestione degli upload richiede attenzione in PHP, perché i limiti sono distribuiti su più livelli. Se il corpo supera post_max_size, PHP scarta silenziosamente tutti i file e $_FILES arriva vuoto: per questo readUpload, quando un campo manca, controlla Content-Length e risponde 413 invece di 400. Se un singolo file supera upload_max_filesize, l'errore è UPLOAD_ERR_INI_SIZE. Infine il servizio applica il proprio limite MAX_UPLOAD_BYTES, indipendente dalla configurazione di PHP. Un campo inviato due volte con lo stesso nome produce in $_FILES array annidati, e viene rifiutato esplicitamente.
Il front controller cambia la directory corrente nella radice del progetto, così i percorsi relativi della configurazione funzionano sia con il server di sviluppo sia con Apache, e legge le variabili d'ambiente da getenv() e da $_SERVER: con Apache, le variabili passate con la direttiva PassEnv sono disponibili in $_SERVER.
Test
I test PHPUnit costruiscono il kernel con una Config esplicita e simulano gli upload scrivendo file temporanei con la stessa forma degli elementi di $_FILES.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="api">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
<?php
declare(strict_types=1);
namespace Tests;
use App\Config;
use App\Http\Kernel;
use App\Http\Request;
use PHPUnit\Framework\TestCase;
final class ApiTest extends TestCase
{
private const API_KEY = 'test-key-123';
private const DOCUMENT = "Contratto di prova\nImporto: 1000 EUR\n";
private static function pki(): string
{
return getenv('PKI_DIR') ?: dirname(__DIR__) . '/pki/out';
}
private function kernel(string $p12 = 'signer.p12'): Kernel
{
return new Kernel(new Config(
p12Path: self::pki() . "/{$p12}",
p12Password: getenv('SIGNER_P12_PASSWORD') ?: 'changeit',
trustAnchorPath: self::pki() . '/ca.crt',
crlPath: self::pki() . '/ca.crl',
tsaUrl: '',
apiKeys: [['client' => 'tests', 'key' => self::API_KEY]],
auditDbPath: ':memory:',
maxUploadBytes: 1024 * 1024,
));
}
/** Simula un file caricato come farebbe PHP in $_FILES. */
private static function upload(string $name, string $content): array
{
$path = tempnam(sys_get_temp_dir(), 'upl');
file_put_contents($path, $content);
return ['name' => $name, 'tmp_name' => $path, 'size' => strlen($content), 'error' => UPLOAD_ERR_OK];
}
private function post(Kernel $kernel, string $path, array $files, array $headers = []): array
{
$request = new Request('POST', $path, ['x-api-key' => self::API_KEY] + $headers, $files, '127.0.0.1');
$response = $kernel->handle($request);
return [$response, json_decode($response->body, true)];
}
private function signDocument(Kernel $kernel, string $content = self::DOCUMENT): array
{
[$response, $json] = $this->post($kernel, '/api/sign', ['file' => self::upload('contratto.txt', $content)]);
$this->assertSame(200, $response->status, $response->body);
return $json;
}
private function verifyDocument(Kernel $kernel, string $content, string $signature): array
{
[$response, $json] = $this->post($kernel, '/api/verify', [
'file' => self::upload('contratto.txt', $content),
'signature' => self::upload('contratto.txt.p7s', $signature),
]);
$this->assertSame(200, $response->status, $response->body);
return $json;
}
public function testHealthIsPublic(): void
{
$response = $this->kernel()->handle(new Request('GET', '/health'));
$this->assertSame('{"status":"ok"}', $response->body);
}
public function testMissingApiKeyIsRejected(): void
{
$request = new Request('POST', '/api/sign', [], ['file' => self::upload('a.txt', 'x')]);
$response = $this->kernel()->handle($request);
$this->assertSame(401, $response->status);
$this->assertSame('UNAUTHORIZED', json_decode($response->body, true)['error']['code']);
}
public function testSignAndVerifyRoundtrip(): void
{
$kernel = $this->kernel();
$signed = $this->signDocument($kernel);
$this->assertSame('CAdES-BES', $signed['profile']);
$result = $this->verifyDocument($kernel, self::DOCUMENT, $signed['signature']);
$this->assertTrue($result['valid'], implode('; ', $result['errors']));
$this->assertSame(
['signature' => true, 'signingCertificate' => true, 'chain' => true, 'revocation' => 'good'],
$result['checks'],
);
$this->assertStringContainsString('CN=Servizio di firma', $result['signer']['subject']);
}
public function testTamperedDocumentIsInvalid(): void
{
$kernel = $this->kernel();
$signed = $this->signDocument($kernel);
$result = $this->verifyDocument($kernel, self::DOCUMENT . '!', $signed['signature']);
$this->assertFalse($result['valid']);
$this->assertFalse($result['checks']['signature']);
}
public function testDerOutputIsAcceptedByOpenssl(): void
{
[$response] = $this->post(
$this->kernel(), '/api/sign', ['file' => self::upload('contratto.txt', self::DOCUMENT)],
['accept' => 'application/pkcs7-signature'],
);
$this->assertSame('application/pkcs7-signature', $response->headers['Content-Type']);
$dir = sys_get_temp_dir() . '/firma-' . bin2hex(random_bytes(4));
mkdir($dir);
file_put_contents("{$dir}/doc.txt", self::DOCUMENT);
file_put_contents("{$dir}/doc.p7s", $response->body);
exec(sprintf(
'openssl cms -verify -binary -inform DER -in %s -content %s -CAfile %s -purpose smimesign -out /dev/null 2>&1',
escapeshellarg("{$dir}/doc.p7s"), escapeshellarg("{$dir}/doc.txt"), escapeshellarg(self::pki() . '/ca.crt'),
), $output, $exitCode);
$this->assertSame(0, $exitCode, implode("\n", $output));
}
public function testRevokedCertificateIsReported(): void
{
$kernel = $this->kernel('revoked.p12');
$signed = $this->signDocument($kernel);
$result = $this->verifyDocument($kernel, self::DOCUMENT, base64_decode($signed['signature']));
$this->assertTrue($result['checks']['signature']);
$this->assertSame('revoked', $result['checks']['revocation']);
$this->assertFalse($result['valid']);
}
public function testUploadLimit(): void
{
[$response] = $this->post($this->kernel(), '/api/sign', [
'file' => self::upload('big.bin', str_repeat('0', 1024 * 1024 + 1)),
]);
$this->assertSame(413, $response->status);
}
public function testOperationsAreAudited(): void
{
$kernel = $this->kernel();
$this->signDocument($kernel);
$this->assertSame(1, $kernel->audit->count());
}
}
./pki/setup.sh
composer test
# OK (8 tests)
Esecuzione e Docker
In sviluppo basta il server integrato di PHP, con lo script definito in composer.json:
export SIGNER_P12_PASSWORD=changeit
export API_KEYS="erp:$(openssl rand -hex 24)"
composer serve
Per la produzione l'immagine usa Apache con mod_php. Le dipendenze vengono installate in una fase separata con l'immagine ufficiale di Composer, la document root viene spostata su public, e due file di configurazione impostano i limiti di PHP e la gestione delle richieste.
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader
FROM php:8.4-apache
# Document root su public/ e variabili d'ambiente visibili a PHP
ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf \
&& a2enmod rewrite
COPY docker/php.ini /usr/local/etc/php/conf.d/firma.ini
COPY docker/firma.conf /etc/apache2/conf-enabled/firma.conf
WORKDIR /var/www/html
COPY --from=vendor /app/vendor ./vendor
COPY public ./public
COPY src ./src
RUN mkdir -p data && chown www-data data
EXPOSE 80
; Limiti coerenti con MAX_UPLOAD_BYTES (10 MiB) e con il margine per due file in /api/verify
upload_max_filesize = 10M
post_max_size = 21M
memory_limit = 256M
expose_php = Off
# Tutte le richieste passano dal front controller
<Directory /var/www/html/public>
AllowOverride None
FallbackResource /index.php
</Directory>
# Rende disponibili a PHP le variabili d'ambiente del container
PassEnv SIGNER_P12_PATH SIGNER_P12_PASSWORD TRUST_ANCHOR_PATH CRL_PATH TSA_URL API_KEYS AUDIT_DB_PATH MAX_UPLOAD_BYTES
post_max_size è poco più del doppio di upload_max_filesize, perché /api/verify riceve due file. FallbackResource invia al front controller tutte le richieste che non corrispondono a un file esistente, senza bisogno di regole di rewrite. PassEnv rende le variabili d'ambiente del container visibili a PHP.
docker build -t firma-php .
# Il PKCS#12 deve essere leggibile dall'utente www-data del container (uid 33)
docker run --rm -p 8080:80 \
-v "$PWD/pki/out:/run/pki:ro" -v firma-data:/var/www/html/data \
-e SIGNER_P12_PATH=/run/pki/signer.p12 -e SIGNER_P12_PASSWORD=changeit \
-e TRUST_ANCHOR_PATH=/run/pki/ca.crt -e CRL_PATH=/run/pki/ca.crl \
-e API_KEYS="erp:una-chiave-lunga-e-casuale" \
firma-php
Verifica incrociata
Il primo controllo indipendente è OpenSSL. Con il servizio in esecuzione su localhost:8080, si firma un documento chiedendo direttamente il file .p7s e lo si verifica con openssl cms. Per includere il controllo di revoca basta concatenare CA e CRL in un unico file e aggiungere -crl_check:
export API_KEY=una-chiave-lunga-e-casuale
echo "Contratto di prova" > contratto.txt
curl -s -H "X-API-Key: $API_KEY" -H "Accept: application/pkcs7-signature" \
-F file=@contratto.txt http://localhost:8080/api/sign -o contratto.txt.p7s
cat pki/out/ca.crt pki/out/ca.crl.pem > /tmp/ca-con-crl.pem
openssl cms -verify -binary -inform DER -in contratto.txt.p7s -content contratto.txt \
-CAfile /tmp/ca-con-crl.pem -crl_check -purpose smimesign -out /dev/null
# CMS Verification successful
# Struttura della busta: attributi firmati e, se presente, la marca temporale
openssl cms -cmsout -print -inform DER -in contratto.txt.p7s | grep -E "object:|UTCTIME"
Il secondo controllo riguarda l'interoperabilità all'interno della serie. Dato che tutte le implementazioni condividono PKI e contratto, si può firmare con questo servizio e verificare con quello di un'altra puntata, avviato su una porta diversa, o viceversa:
# Questo servizio su 8080, l'implementazione di un'altra puntata su 8081
curl -s -H "X-API-Key: $API_KEY" -F file=@contratto.txt -F signature=@contratto.txt.p7s \
http://localhost:8081/api/verify
# Firma in JSON con l'altro servizio e verifica con questo: il base64 e' accettato cosi' com'e'
curl -s -H "X-API-Key: $API_KEY" -F file=@contratto.txt http://localhost:8081/api/sign \
| jq -r .signature > firma.b64
curl -s -H "X-API-Key: $API_KEY" -F file=@contratto.txt -F signature=@firma.b64 \
http://localhost:8080/api/verify | jq '.valid, .checks'
Le buste prodotte dalle diverse implementazioni non sono identiche byte per byte: alcune librerie aggiungono attributi propri (Bouncy Castle, per esempio, inserisce anche cmsAlgorithmProtect), altre codificano l'algoritmo di firma come rsaEncryption invece che come sha256WithRSAEncryption, e la marca temporale cambia a ogni firma. Sono differenze ammesse dallo standard, e ogni verificatore della serie le accetta entrambe. Proprio per questo la verifica incrociata, eseguita su firme CAdES-BES e CAdES-T, è il test più utile da automatizzare in una pipeline che coinvolge più sistemi.
Per provare la marca temporale in locale senza dipendere da un servizio esterno si può usare FreeTSA impostando TSA_URL=https://freetsa.org/tsr, oppure una TSA di sviluppo basata su openssl ts -reply. Una TSA restituisce token firmati con un certificato che deve avere l'uso esteso timeStamping marcato come critico.
Evoluzioni
Il servizio è completo per l'uso con una CA interna, ma ci sono diverse direzioni in cui farlo crescere.
- Chiave in un HSM o in un KMS: l'interfaccia
Signersepara la logica CAdES dalla custodia della chiave. Un'implementazione PKCS#11 (con SoftHSM in sviluppo e un HSM di rete in produzione) o basata su un KMS cloud deve solo restituire il certificato e firmare dati con RSA PKCS#1 v1.5 e SHA-256: il resto del servizio non cambia. È anche il passo necessario per avvicinarsi a una firma qualificata, in cui la chiave non deve mai lasciare un dispositivo certificato. - OCSP: la CRL locale è semplice e funziona anche offline, ma con CA che revocano spesso diventa voluminosa. OCSP (RFC 6960) permette di interrogare lo stato di un singolo certificato; conviene comunque mantenere la CRL come fallback quando il responder non è raggiungibile.
- Verifica della catena della TSA: il servizio verifica la firma del token e la corrispondenza dell'impronta, ma non la catena del certificato della TSA. In produzione va aggiunto un insieme separato di CA fidate per le TSA.
- Livelli LT e LTA: per conservare la verificabilità nel lungo periodo, anche dopo la scadenza dei certificati, i profili CAdES-B-LT e B-LTA aggiungono alla busta i dati di validazione (certificati, CRL o risposte OCSP) e marche temporali di archivio.
- Buste attached (.p7m): molti flussi italiani usano file
.p7mche contengono il documento. Il passaggio da detached ad attached richiede solo di includere il contenuto ineContent, ma comporta buste grandi quanto i documenti. - ECDSA e RSA-PSS: sono algoritmi più moderni di RSA PKCS#1 v1.5, ma il loro supporto nelle librerie CMS è meno uniforme; prima di adottarli conviene verificare l'interoperabilità con tutti i sistemi che dovranno leggere le firme.
- Firma di un hash invece del documento: per file molto grandi il client può calcolare l'hash localmente e inviare solo quello, riducendo traffico e superficie d'attacco. L'API andrebbe estesa con un endpoint che accetta un digest.
- Processo persistente: nel modello classico di PHP il keystore PKCS#12 viene decifrato a ogni richiesta, con un costo di pochi millisecondi dovuto a PBKDF2. Con un runtime persistente come FrankenPHP in worker mode, o con RoadRunner, il kernel e la chiave restano in memoria tra una richiesta e l'altra.
Conclusioni
PHP senza framework si rivela adatto a un servizio di firma più di quanto si potrebbe pensare. L'estensione OpenSSL copre tutte le operazioni crittografiche, phpseclib risolve la CRL, e un codec DER di poche centinaia di righe dà il pieno controllo sulla busta CMS, compresi gli attributi che openssl_cms_sign non sa gestire. Il nucleo crittografico non dipende in alcun modo dallo strato HTTP: è lo stesso codice che, con un namespace diverso, viene riutilizzato nella puntata dedicata a Laravel.