Implementare un servizio web di firma digitale CAdES con Laravel

In questa puntata il servizio è scritto in Laravel 13 con un service provider per il nucleo crittografico, Form Request per la validazione degli upload, un middleware per le API key, Eloquent per il registro di audit e Pest per i test.

Laravel di Gabriele Romanato

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 Laravel 13 con un service provider per il nucleo crittografico, Form Request per la validazione degli upload, un middleware per le API key, Eloquent per il registro di audit e Pest per i test.

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 SignedData detached, 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, signingTime e signingCertificateV2. 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:

  1. si calcola l'hash SHA-256 del documento;
  2. si costruisce l'insieme degli attributi firmati, in cui l'attributo messageDigest contiene proprio quell'hash;
  3. si codifica l'insieme degli attributi in DER come SET OF Attribute, con gli elementi ordinati per codifica binaria;
  4. si firma con RSA quella codifica DER;
  5. 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 una SignedData e in una ContentInfo.

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 multipart file e restituisce la firma.
  • POST /api/verify: riceve il documento nel campo file e la firma nel campo signature, 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_PATH e SIGNER_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 coppie client:chiave separate da virgole, per esempio erp: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 Laravel

Il nucleo crittografico di questa implementazione è lo stesso della puntata dedicata a PHP senza framework: un codec DER minimale, l'estensione OpenSSL per le operazioni RSA e phpseclib 3 per la validazione della CRL. Le classi vengono spostate nel namespace App\Services\Cades e solo il client della TSA cambia, per usare l'HTTP client di Laravel. Tutto ciò che sta attorno al nucleo segue invece le convenzioni del framework:

  • un service provider registra Signer, CadesSigner e SignatureVerifier come singleton nel container;
  • le Form Request validano gli upload e traducono gli errori nel formato del contratto, distinguendo il file troppo grande (413) dal campo mancante (400);
  • un middleware autentica le richieste con l'intestazione X-API-Key;
  • il registro di audit è un modello Eloquent con la sua migrazione, sul database configurato dall'applicazione;
  • gli errori sono gestiti con render sulle eccezioni e con la configurazione di bootstrap/app.php;
  • i test sono feature test Pest che usano UploadedFile::fake() e il database in memoria.

Creazione del progetto

composer create-project laravel/laravel firma-laravel
cd firma-laravel
composer require phpseclib/phpseclib:^3.0
# Pest al posto di PHPUnit "puro"
composer remove phpunit/phpunit --dev
composer require pestphp/pest pestphp/pest-plugin-laravel --dev --with-all-dependencies
./vendor/bin/pest --init

Dalla versione 11 Laravel non crea più il file routes/api.php. Il comando php artisan install:api lo aggiungerebbe insieme a Sanctum, che qui non serve: basta creare il file a mano e registrarlo in bootstrap/app.php, come mostrato più avanti. I file aggiunti o modificati rispetto allo scheletro sono questi:

firma-laravel/
  app/
    Exceptions/ApiException.php
    Http/
      Controllers/SignatureController.php
      Middleware/AuthenticateApiKey.php
      Requests/UploadRequest.php
      Requests/SignRequest.php
      Requests/VerifyRequest.php
    Models/AuditEntry.php
    Providers/FirmaServiceProvider.php
    Services/Cades/              # nucleo CAdES (Der, Oid, Signer, CadesSigner, ...)
  bootstrap/app.php
  bootstrap/providers.php        # registrazione di FirmaServiceProvider
  config/firma.php
  database/migrations/2026_12_01_000000_create_audit_log_table.php
  routes/api.php
  routes/web.php
  tests/Feature/SignatureApiTest.php
  tests/Pest.php
  pki/setup.sh
  Dockerfile
  docker/php.ini
  docker/firma.conf

Configurazione

Il file config/firma.php legge le stesse variabili d'ambiente delle altre implementazioni, con percorsi predefiniti relativi alla radice del progetto grazie a base_path. Come sempre in Laravel, il resto del codice legge la configurazione con config() e mai direttamente con env(), così funziona anche dopo php artisan config:cache.

<?php

// Configurazione del servizio: stesse variabili d'ambiente delle altre implementazioni
return [
    'p12_path' => env('SIGNER_P12_PATH', base_path('pki/out/signer.p12')),
    'p12_password' => env('SIGNER_P12_PASSWORD', ''),
    'trust_anchor_path' => env('TRUST_ANCHOR_PATH', base_path('pki/out/ca.crt')),
    'crl_path' => env('CRL_PATH', base_path('pki/out/ca.crl')),
    'tsa_url' => env('TSA_URL', ''),
    'api_keys' => env('API_KEYS', ''),
    'max_upload_bytes' => (int) env('MAX_UPLOAD_BYTES', 10 * 1024 * 1024),
];

Il database di audit è quello dell'applicazione: nella configurazione predefinita di Laravel è un file SQLite in database/database.sqlite, e la variabile AUDIT_DB_PATH delle altre implementazioni corrisponde qui a DB_DATABASE.

Il nucleo crittografico

Il nucleo riprende integralmente le classi della puntata su PHP. Il codec DER costruisce e legge le strutture ASN.1; ogni nodo decodificato conserva la propria codifica originale nel campo raw, il che permette di riusare emittente, numero di serie e token senza mai ricodificarli.

<?php

declare(strict_types=1);

namespace App\Services\Cades;

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\Services\Cades;

/** 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';
}
<?php

declare(strict_types=1);

namespace App\Services\Cades;

use RuntimeException;

final class Asn1Exception extends RuntimeException
{
}

L'interfaccia Signer isola la custodia della chiave; Pkcs12Signer legge il keystore con l'estensione OpenSSL e firma con RSA PKCS#1 v1.5 e SHA-256.

<?php

declare(strict_types=1);

namespace App\Services\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\Services\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;
    }
}
<?php

declare(strict_types=1);

namespace App\Services\Cades;

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

Il client RFC 3161 è l'unica classe del nucleo che cambia rispetto alla versione senza framework: la richiesta viene inviata con Http::withBody, che imposta corpo binario e tipo di contenuto in un colpo solo. Il resto, cioè costruzione della TimeStampReq, controllo dello stato, del nonce e dell'impronta, è identico. Un vantaggio concreto del client di Laravel è Http::fake, che nei test permette di simulare la TSA senza servizi esterni.

<?php

declare(strict_types=1);

namespace App\Services\Cades;

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\Services\Cades;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;

/** Client RFC 3161 basato sull'HTTP client di Laravel. */
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
        );

        try {
            $response = Http::timeout($this->timeoutSeconds)
                ->withBody($request, 'application/timestamp-query')
                ->post($this->url);
        } catch (ConnectionException $exception) {
            throw new TsaException('TSA non raggiungibile: ' . $exception->getMessage());
        }
        if ($response->status() !== 200) {
            throw new TsaException("la TSA ha risposto con HTTP {$response->status()}");
        }

        try {
            $reply = Der::decode($response->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\Services\Cades;

use RuntimeException;

final class TsaException extends RuntimeException
{
}

La firma CAdES

<?php

declare(strict_types=1);

namespace App\Services\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\Services\Cades;

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,
        );
    }
}

Gli attributi firmati vengono creati e ordinati una sola volta, poi usati sia per calcolare la firma sulla codifica con tag SET (0x31) sia per scriverli nel SignerInfo con tag [0]: le due codifiche contengono così esattamente gli stessi byte nello stesso ordine, condizione necessaria perché la firma sia verificabile. signingCertificateV2 contiene l'hash SHA-256 del certificato DER, senza hashAlgorithm perché SHA-256 è il valore predefinito. L'encapContentInfo senza contenuto rende la firma detached, e la marca temporale, se configurata, viene aggiunta come attributo non firmato [1].

Revoca e verifica

<?php

declare(strict_types=1);

namespace App\Services\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';
    }
}
<?php

declare(strict_types=1);

namespace App\Services\Cades;

use RuntimeException;

final class MalformedSignatureException extends RuntimeException
{
}
<?php

declare(strict_types=1);

namespace App\Services\Cades;

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');
    }
}

CrlChecker delega a phpseclib la validazione della CRL: validateSignature trova tra le CA caricate quella che ha emesso la CRL e ne verifica la firma. SignatureVerifier controlla nell'ordine messageDigest, firma RSA sugli attributi ritaggati con il tag SET, signingCertificateV2, catena verso la CA fidata con openssl_x509_verify, stato di revoca e marca temporale, riusando per quest'ultima la stessa funzione verifySignedData applicata al TSTInfo. Il risultato è un array che il controller restituisce così com'è.

Il service provider

Il service provider è il punto in cui il nucleo, che non conosce Laravel, incontra il framework. I servizi sono registrati come singleton: in PHP tradizionale l'applicazione viene ricreata a ogni richiesta, quindi il keystore viene comunque decifrato una volta per richiesta, ma con Octane l'oggetto sopravvive tra una richiesta e l'altra.

<?php

namespace App\Providers;

use App\Services\Cades\CadesSigner;
use App\Services\Cades\CrlChecker;
use App\Services\Cades\Pkcs12Signer;
use App\Services\Cades\SignatureVerifier;
use App\Services\Cades\Signer;
use App\Services\Cades\TsaClient;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;

class FirmaServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Singleton: il keystore viene letto una sola volta per processo
        $this->app->singleton(Signer::class, fn () => new Pkcs12Signer(
            config('firma.p12_path'),
            config('firma.p12_password'),
        ));

        $this->app->singleton(CadesSigner::class, function (Application $app) {
            $tsaUrl = config('firma.tsa_url');
            return new CadesSigner($app->make(Signer::class), $tsaUrl ? new TsaClient($tsaUrl) : null);
        });

        $this->app->singleton(SignatureVerifier::class, function () {
            $trustAnchorPem = file_get_contents(config('firma.trust_anchor_path'));
            return new SignatureVerifier($trustAnchorPem, new CrlChecker(config('firma.crl_path'), $trustAnchorPem));
        });
    }
}
<?php

// bootstrap/providers.php
return [
    App\Providers\AppServiceProvider::class,
    App\Providers\FirmaServiceProvider::class,
];

Le classi vengono risolte dal container tramite type hint: il controller dichiara Signer, CadesSigner o SignatureVerifier tra i parametri dei metodi e Laravel le inietta. Sostituire il PKCS#12 con un HSM significa cambiare una sola riga, il binding di Signer.

Autenticazione ed errori

<?php

namespace App\Exceptions;

use Illuminate\Http\JsonResponse;
use RuntimeException;

class ApiException extends RuntimeException
{
    public function __construct(public readonly int $status, public readonly string $errorCode, string $message)
    {
        parent::__construct($message);
    }

    public static function response(int $status, string $code, string $message): JsonResponse
    {
        return response()->json(['error' => ['code' => $code, 'message' => $message]], $status);
    }

    /** Laravel invoca render() automaticamente quando l'eccezione non viene gestita. */
    public function render(): JsonResponse
    {
        return self::response($this->status, $this->errorCode, $this->getMessage());
    }
}
<?php

namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use Closure;
use Illuminate\Http\Request;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateApiKey
{
    /** @return array<int, array{client: string, digest: string}> */
    private function entries(): array
    {
        $entries = [];
        foreach (array_filter(array_map('trim', explode(',', config('firma.api_keys')))) as $item) {
            [$client, $key] = array_pad(explode(':', $item, 2), 2, '');
            if ($client === '' || $key === '') {
                throw new InvalidArgumentException("voce API_KEYS non valida: {$item}");
            }
            // Si confrontano i digest: lunghezza fissa, nessuna informazione sulla lunghezza della chiave
            $entries[] = ['client' => $client, 'digest' => hash('sha256', $key, true)];
        }
        return $entries;
    }

    public function handle(Request $request, Closure $next): Response
    {
        $provided = (string) $request->header('X-API-Key', '');
        $matched = null;
        if ($provided !== '') {
            $digest = hash('sha256', $provided, true);
            // Nessuna uscita anticipata: si confrontano sempre tutte le chiavi
            foreach ($this->entries() as $entry) {
                if (hash_equals($entry['digest'], $digest)) {
                    $matched = $entry['client'];
                }
            }
        }
        if ($matched === null) {
            return ApiException::response(401, 'UNAUTHORIZED', 'API key mancante o non valida');
        }
        $request->attributes->set('client', $matched);
        return $next($request);
    }
}

Il middleware confronta gli hash SHA-256 delle chiavi con hash_equals, scorrendo sempre l'intero elenco, e salva il nome del client negli attributi della richiesta, da dove il controller lo legge per l'audit. ApiException sfrutta una convenzione di Laravel: un'eccezione con un metodo render viene trasformata automaticamente nella risposta restituita da quel metodo, senza registrare gestori dedicati.

Validazione degli upload con le Form Request

Le due rotte di firma e verifica ricevono file diversi ma condividono le regole, quindi le Form Request derivano da una classe base astratta che genera le regole a partire dall'elenco dei campi.

<?php

namespace App\Http\Requests;

use App\Exceptions\ApiException;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

/** Base comune: valida i file caricati e traduce gli errori nel formato dell'API. */
abstract class UploadRequest extends FormRequest
{
    /** @return list<string> nomi dei campi file richiesti */
    abstract protected function fileFields(): array;

    public function authorize(): bool
    {
        return true; // l'autenticazione e' gestita dal middleware della API key
    }

    public function rules(): array
    {
        // La regola max di Laravel si esprime in kilobyte
        $maxKilobytes = intdiv(config('firma.max_upload_bytes'), 1024);
        return collect($this->fileFields())
            ->mapWithKeys(fn (string $field) => [$field => ['required', 'file', "max:{$maxKilobytes}"]])
            ->all();
    }

    protected function failedValidation(Validator $validator): never
    {
        foreach ($validator->failed() as $rules) {
            if (array_key_exists('Max', $rules)) {
                throw new ApiException(413, 'PAYLOAD_TOO_LARGE', 'file troppo grande');
            }
        }
        throw new ApiException(400, 'BAD_REQUEST', $validator->errors()->first());
    }
}
<?php

namespace App\Http\Requests;

class SignRequest extends UploadRequest
{
    protected function fileFields(): array
    {
        return ['file'];
    }
}
<?php

namespace App\Http\Requests;

class VerifyRequest extends UploadRequest
{
    protected function fileFields(): array
    {
        return ['file', 'signature'];
    }
}

La regola max di Laravel, applicata a un file, si esprime in kilobyte, da cui la divisione per 1024. Il punto più interessante è failedValidation: per impostazione predefinita Laravel risponderebbe con un 422 e il proprio formato d'errore. L'override esamina $validator->failed(), che restituisce le regole fallite per ogni campo: se è fallita Max la risposta è 413 PAYLOAD_TOO_LARGE, altrimenti 400 BAD_REQUEST con il primo messaggio di validazione.

Audit con Eloquent

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audit_log', function (Blueprint $table) {
            $table->id();
            $table->timestamp('created_at')->useCurrent();
            $table->string('client');
            $table->string('operation', 16);
            $table->char('document_sha256', 64);
            $table->string('certificate_serial')->nullable();
            $table->string('outcome', 16);
            $table->string('remote_addr', 45)->nullable();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('audit_log');
    }
};
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/** Voce del registro di audit: solo metadati, mai il documento. */
class AuditEntry extends Model
{
    protected $table = 'audit_log';

    // La tabella ha solo created_at, valorizzato da Eloquent
    const UPDATED_AT = null;

    protected $fillable = [
        'client',
        'operation',
        'document_sha256',
        'certificate_serial',
        'outcome',
        'remote_addr',
    ];
}

La tabella ha solo created_at: un registro di audit è append-only e una colonna updated_at non avrebbe senso. Impostare UPDATED_AT a null dice a Eloquent di non gestirla, mentre created_at viene valorizzato automaticamente all'inserimento.

php artisan migrate

Controller e rotte

<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\SignRequest;
use App\Http\Requests\VerifyRequest;
use App\Models\AuditEntry;
use App\Services\Cades\CadesSigner;
use App\Services\Cades\Certificates;
use App\Services\Cades\MalformedSignatureException;
use App\Services\Cades\SignatureVerifier;
use App\Services\Cades\Signer;
use App\Services\Cades\TsaException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class SignatureController extends Controller
{
    private const PKCS7_MEDIA_TYPE = 'application/pkcs7-signature';

    public function certificate(Signer $signer): JsonResponse
    {
        $der = $signer->certificateDer();
        return response()->json(Certificates::describe($der) + [
            'sha256Fingerprint' => hash('sha256', $der),
            'pem' => Certificates::derToPem($der),
        ]);
    }

    public function sign(SignRequest $request, CadesSigner $cades): JsonResponse|Response
    {
        $file = $request->file('file');
        $content = $file->getContent();
        try {
            $result = $cades->sign($content);
        } catch (TsaException $exception) {
            $this->audit($request, 'sign', hash('sha256', $content), null, 'error');
            throw new ApiException(502, 'TSA_UNAVAILABLE', $exception->getMessage());
        }
        $this->audit($request, 'sign', $result->documentSha256, $result->certificateSerial, 'ok');

        if (str_contains((string) $request->header('Accept'), self::PKCS7_MEDIA_TYPE)) {
            $filename = preg_replace('/["\\\\\r\n]/', '_', ($file->getClientOriginalName() ?: 'document') . '.p7s');
            return response($result->der, 200, [
                '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),
        ]);
    }

    public function verify(VerifyRequest $request, SignatureVerifier $verifier): JsonResponse
    {
        $content = $request->file('file')->getContent();
        $signature = self::decodeSignature($request->file('signature')->getContent());
        $documentSha256 = hash('sha256', $content);
        try {
            $result = $verifier->verify($content, $signature);
        } catch (MalformedSignatureException $exception) {
            $this->audit($request, 'verify', $documentSha256, null, 'error');
            throw new ApiException(400, 'MALFORMED_SIGNATURE', $exception->getMessage());
        }
        $this->audit($request, 'verify', $documentSha256, $result['signer']['serialNumber'],
            $result['valid'] ? 'valid' : 'invalid');
        return response()->json($result);
    }

    private function audit(Request $request, string $operation, string $sha256, ?string $serial, string $outcome): void
    {
        AuditEntry::create([
            'client' => $request->attributes->get('client'),
            'operation' => $operation,
            'document_sha256' => $sha256,
            'certificate_serial' => $serial,
            'outcome' => $outcome,
            'remote_addr' => $request->ip(),
        ]);
    }

    /** DER binario (SEQUENCE, 0x30) oppure base64 come restituito da /api/sign. */
    private static function decodeSignature(string $raw): string
    {
        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;
    }
}

Il controller è sottile: riceve richieste già validate, delega al nucleo crittografico, registra l'audit e compone le risposte. Le dipendenze arrivano come parametri dei metodi, risolti dal container. Se la richiesta accetta application/pkcs7-signature, la risposta è la busta DER con un nome di file ripulito dai caratteri che potrebbero alterare l'intestazione Content-Disposition.

<?php

use App\Http\Controllers\SignatureController;
use App\Http\Middleware\AuthenticateApiKey;
use Illuminate\Support\Facades\Route;

// Il prefisso /api viene aggiunto da bootstrap/app.php
Route::middleware(AuthenticateApiKey::class)->group(function () {
    Route::get('/certificate', [SignatureController::class, 'certificate']);
    Route::post('/sign', [SignatureController::class, 'sign']);
    Route::post('/verify', [SignatureController::class, 'verify']);
});
<?php

use Illuminate\Support\Facades\Route;

Route::get('/health', fn () => response()->json(['status' => 'ok']));
<?php

use App\Exceptions\ApiException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Exceptions\PostTooLargeException;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // Corpo oltre post_max_size: PHP scarta i file e Laravel solleva PostTooLargeException
        $exceptions->render(fn (PostTooLargeException $e, Request $request) =>
            ApiException::response(413, 'PAYLOAD_TOO_LARGE', 'richiesta troppo grande'));

        // Per le rotte /api ogni altro errore diventa JSON nel formato comune.
        // Laravel registra comunque l'eccezione nei log prima di renderizzarla.
        $exceptions->render(function (Throwable $e, Request $request) {
            if (!$request->is('api/*') || $e instanceof ApiException) {
                return null;
            }
            if ($e instanceof HttpExceptionInterface && $e->getStatusCode() < 500) {
                return ApiException::response($e->getStatusCode(), 'BAD_REQUEST', $e->getMessage() ?: 'richiesta non valida');
            }
            return ApiException::response(500, 'INTERNAL', 'errore interno');
        });
    })->create();

In bootstrap/app.php la chiave api di withRouting registra routes/api.php con il prefisso /api e il gruppo di middleware api, che non include sessioni né protezione CSRF. Il controllo /health del contratto è definito in routes/web.php, accanto a /up che Laravel offre di serie. Due gestori di rendering completano il formato d'errore comune: PostTooLargeException, sollevata quando il corpo supera post_max_size, diventa un 413, le eccezioni HTTP del framework con stato 4xx (rotta inesistente, metodo non ammesso) mantengono il proprio stato con il codice BAD_REQUEST, e ogni altro errore sulle rotte /api diventa un 500 in JSON. Non serve chiamare report: Laravel registra l'eccezione nei log prima di passarla ai gestori di rendering. Restituire null lascia a Laravel la gestione predefinita, che per ApiException consiste nel chiamare il suo metodo render.

Test con Pest

I feature test usano il database SQLite in memoria configurato dallo scheletro di Laravel in phpunit.xml e il trait RefreshDatabase, che esegue le migrazioni prima di ogni test. Gli upload vengono simulati con UploadedFile::fake()->createWithContent.

<?php

use Illuminate\Foundation\Testing\RefreshDatabase;

pest()->extend(Tests\TestCase::class)
    ->use(RefreshDatabase::class)
    ->in('Feature');
<?php

use App\Models\AuditEntry;
use App\Services\Cades\CadesSigner;
use App\Services\Cades\Pkcs12Signer;
use Illuminate\Http\UploadedFile;

const API_KEY = 'test-key-123';
const DOCUMENT = "Contratto di prova\nImporto: 1000 EUR\n";

beforeEach(function () {
    config([
        'firma.api_keys' => 'tests:' . API_KEY,
        'firma.p12_password' => env('SIGNER_P12_PASSWORD', 'changeit'),
        'firma.tsa_url' => '',
        'firma.max_upload_bytes' => 1024 * 1024,
    ]);
});

function upload(string $name, string $content): UploadedFile
{
    return UploadedFile::fake()->createWithContent($name, $content);
}

function signDocument(string $content = DOCUMENT): array
{
    return test()->post('/api/sign', ['file' => upload('contratto.txt', $content)], ['X-API-Key' => API_KEY])
        ->assertOk()
        ->json();
}

function verifyDocument(string $content, string $signature): array
{
    return test()->post('/api/verify', [
        'file' => upload('contratto.txt', $content),
        'signature' => upload('contratto.txt.p7s', $signature),
    ], ['X-API-Key' => API_KEY])->assertOk()->json();
}

it('espone /health senza autenticazione', function () {
    $this->get('/health')->assertOk()->assertExactJson(['status' => 'ok']);
});

it('rifiuta le richieste senza API key', function () {
    $this->post('/api/sign', ['file' => upload('a.txt', 'x')])
        ->assertUnauthorized()
        ->assertJsonPath('error.code', 'UNAUTHORIZED');
});

it('firma e verifica un documento', function () {
    $signed = signDocument();
    expect($signed['profile'])->toBe('CAdES-BES');

    $result = verifyDocument(DOCUMENT, $signed['signature']);
    expect($result['valid'])->toBeTrue()
        ->and($result['checks'])->toBe([
            'signature' => true, 'signingCertificate' => true, 'chain' => true, 'revocation' => 'good',
        ])
        ->and($result['signer']['subject'])->toContain('CN=Servizio di firma')
        ->and(AuditEntry::count())->toBe(2);
});

it('rileva un documento alterato', function () {
    $signed = signDocument();
    $result = verifyDocument(DOCUMENT . '!', $signed['signature']);
    expect($result['valid'])->toBeFalse()
        ->and($result['checks']['signature'])->toBeFalse();
});

it('produce DER accettato da openssl cms', function () {
    $response = $this->post('/api/sign', ['file' => upload('contratto.txt', DOCUMENT)], [
        'X-API-Key' => API_KEY,
        'Accept' => 'application/pkcs7-signature',
    ]);
    expect($response->headers->get('Content-Type'))->toBe('application/pkcs7-signature');

    $dir = sys_get_temp_dir() . '/firma-' . bin2hex(random_bytes(4));
    mkdir($dir);
    file_put_contents("{$dir}/doc.txt", DOCUMENT);
    file_put_contents("{$dir}/doc.p7s", $response->getContent());
    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(base_path('pki/out/ca.crt')),
    ), $output, $exitCode);
    expect($exitCode)->toBe(0, implode("\n", $output));
});

it('segnala un certificato revocato', function () {
    // Firma prodotta direttamente con il certificato revocato, verificata tramite l'API
    $revoked = new Pkcs12Signer(base_path('pki/out/revoked.p12'), env('SIGNER_P12_PASSWORD', 'changeit'));
    $der = (new CadesSigner($revoked))->sign(DOCUMENT)->der;

    $result = verifyDocument(DOCUMENT, $der);
    expect($result['checks']['signature'])->toBeTrue()
        ->and($result['checks']['revocation'])->toBe('revoked')
        ->and($result['valid'])->toBeFalse();
});

it('applica il limite sugli upload', function () {
    $this->post('/api/sign', ['file' => upload('big.bin', str_repeat('0', 1024 * 1024 + 1))], ['X-API-Key' => API_KEY])
        ->assertStatus(413)
        ->assertJsonPath('error.code', 'PAYLOAD_TOO_LARGE');
});
./pki/setup.sh
./vendor/bin/pest
#   PASS  Tests\Feature\SignatureApiTest
#   Tests:    8 passed

I valori di configurazione specifici dei test vengono impostati in beforeEach con config(), così non dipendono dal file .env dello sviluppatore. Il test sul certificato revocato costruisce la firma direttamente con le classi del nucleo, perché l'applicazione in esecuzione usa il certificato valido, e poi la verifica tramite l'API.

Esecuzione e Docker

export SIGNER_P12_PASSWORD=changeit
export API_KEYS="erp:$(openssl rand -hex 24)"
php artisan serve --port=8080

L'immagine di produzione installa le dipendenze con Composer in una fase separata e usa Apache con mod_php. All'avvio esegue le migrazioni, sistema i permessi del database e mette in cache configurazione e rotte, quindi avvia Apache in primo piano.

FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-interaction --prefer-dist --no-scripts --no-autoloader
COPY . .
RUN composer dump-autoload --optimize --no-dev

FROM php:8.4-apache
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 ./
# /var/lib/firma ospita il database SQLite di audit (volume persistente)
RUN mkdir -p /var/lib/firma \
    && chown -R www-data storage bootstrap/cache /var/lib/firma
ENV DB_CONNECTION=sqlite DB_DATABASE=/var/lib/firma/audit.sqlite

# All'avvio: migrazioni, permessi sul database, cache di configurazione e rotte, poi Apache
CMD ["sh", "-c", "php artisan migrate --force && chown -R www-data /var/lib/firma && php artisan config:cache && php artisan route:cache && apache2-foreground"]
EXPOSE 80
<Directory /var/www/html/public>
    AllowOverride All
</Directory>

# Rende disponibili a Laravel le variabili d'ambiente del container
PassEnv APP_KEY SIGNER_P12_PATH SIGNER_P12_PASSWORD TRUST_ANCHOR_PATH CRL_PATH TSA_URL API_KEYS MAX_UPLOAD_BYTES DB_CONNECTION DB_DATABASE

Il file docker/php.ini è lo stesso della versione senza framework: upload_max_filesize a 10 MB e post_max_size poco più del doppio, perché la verifica riceve due file. La configurazione di Apache abilita il file .htaccess fornito da Laravel in public e rende visibili a PHP le variabili d'ambiente del container. Laravel richiede anche una APP_KEY, che si genera una volta con php artisan key:generate --show.

docker build -t firma-laravel .
# 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/lib/firma \
  -e APP_KEY="base64:..." \
  -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-laravel

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 Signer separa 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 .p7m che contengono il documento. Il passaggio da detached ad attached richiede solo di includere il contenuto in eContent, 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.
  • Octane: con Laravel Octane (FrankenPHP, Swoole o RoadRunner) l'applicazione resta in memoria tra le richieste e i singleton registrati dal service provider, compreso il keystore già decifrato, vengono creati una sola volta per worker. Il CrlChecker è già pronto per questo scenario, perché ricarica la CRL quando il file cambia.
  • Code e firme massive: per firmare lotti di documenti generati dall'applicazione si può incapsulare CadesSigner in un job in coda, salvando le buste su un disco di Laravel e registrando l'esito nello stesso modello di audit.

Conclusioni

Laravel non aggiunge nulla alla crittografia, ed è proprio questo il punto: il nucleo CAdES resta un insieme di classi PHP indipendenti, testabili e riutilizzabili, mentre il framework si occupa di ciò che sa fare meglio. Container e service provider rendono sostituibile la custodia della chiave, le Form Request centralizzano la validazione degli upload, Eloquent e le migrazioni gestiscono il registro di audit, e Pest permette di descrivere il comportamento del servizio in test brevi e leggibili.