Aere Quantum: a post-quantum TLS 1.3 gateway (X25519MLKEM768, optional ML-DSA client authentication), a hybrid KMS (X25519 + ML-KEM-768, Ed25519 + ML-DSA-65; root key from the environment or sealed by an HSM through PKCS#11) and an ML-DSA private CA (X.509 v3, RFC 9881). Zero dependencies, Node.js 24 with OpenSSL 3.5. Each with its test suite and a negative control.

This commit is contained in:
Aere Network committed 2026-09-29 16:24:04 +03:00
commit 7d814d1bb8
24 files changed
+7004

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# dosarul implicit de date (chei sigilate, jurnal de audit); nu intra niciodata in depozit
data/
+284
View File
@@ -0,0 +1,284 @@
# Aere PQ KMS
A small "transit"-style key management service (in the spirit of Vault's transit engine) where every
key is **hybrid classical + post-quantum**. It encrypts, decrypts, rewraps, issues data keys, signs and
verifies. Callers never see private keys unless a key was explicitly created as exportable.
It runs on **Node.js 24 only** and uses nothing but `node:crypto` (OpenSSL 3.5), `node:http`,
`node:fs`. No dependencies.
| key type | algorithms | what the hybrid means |
|-----------|------------------------------------|-----------------------|
| `encrypt` | X25519 + ML-KEM-768, AES-256-GCM | the data key is derived from **both** shared secrets; recovering it requires both |
| `sign` | Ed25519 + ML-DSA-65 | a signature carries **both** halves; verification fails if **either** half fails |
## What it is NOT
- **Not an HSM itself.** Private keys live on disk sealed under a root key, and in process memory while in use.
Anyone who can read process memory, or who has both the data directory and the root key, has the keys.
- **The root key comes from the environment** (`AERE_KMS_ROOT_KEY`) **or, since 2026-09-28, sealed by an HSM**
(`AERE_KMS_ROOT_HSM`, see below). With the environment there is no physical separation, no key ceremony, no
secret sharing, no unseal quorum; protect the environment accordingly. Only the derived key buffer is zeroed
after derivation; the hex string itself stays readable in the process (configuration) for its lifetime.
- **Not audited.** No third party has reviewed this code or the hybrid construction below.
- **Single process.** There is no file locking; do not point two processes at the same data directory. If
two processes do write the same audit log, the chain breaks and the next start **refuses** with
`AUDIT_CHAIN_INVALID` until the log is moved aside: it is a stop, not a degradation.
- **Audit verification is linear.** Startup and `GET /v1/audit/verify` re-read and re-authenticate the whole
log; on a very large log a caller holding the token can make that endpoint expensive. Rotate the log by
moving it aside (keep it as evidence) and starting a new chain.
- **No TLS.** The server speaks plain HTTP and listens on `127.0.0.1` by default. Put a TLS-terminating
proxy in front of it before exposing it to anything else.
- **One static bearer token.** There are no per-client identities, roles or per-key ACLs, and the audit
log does not record who made a request.
- No key deletion, no root-key rotation, no rate limiting, no replication or backup.
## Root key sealed by an HSM (PKCS#11)
`hsm-radacina.mjs` seals the 32-byte root under an AES-256 key generated **inside** a PKCS#11 token
(`CKA_SENSITIVE`, never extractable) and stores only the sealed form on disk. At start the server asks the
HSM to open it with the token PIN (`AERE_HSM_PIN`, read by `pkcs11-tool` from the environment, never on a
command line). Someone with the disk and the environment but without the HSM (and its PIN) does not have
the root. Set exactly one of `AERE_KMS_ROOT_KEY` / `AERE_KMS_ROOT_HSM`; both is refused (`ROOT_KEY_AMBIGUOUS`).
AERE_HSM_PIN=... node hsm-radacina.mjs sigileaza --modul /usr/lib/softhsm/libsofthsm2.so --token aere-kms --id 0a --iesire root-hsm.json --nou
AERE_KMS_ROOT_HSM=root-hsm.json AERE_HSM_MODULE=/usr/lib/softhsm/libsofthsm2.so AERE_HSM_PIN=... AERE_KMS_TOKEN=... node server.mjs
The sealed file does not choose what the process loads or sends: the PKCS#11 library comes from the process
configuration (`AERE_HSM_MODULE`, an absolute path) and must be exactly the one recorded in the file, checked
before any HSM tool runs (`HSM_MODULE_NOT_ALLOWED` otherwise); the PIN is always read from `AERE_HSM_PIN`, and a
file naming another variable is refused. So write access to the sealed file alone cannot make the KMS load
another library or hand it the PIN or another secret. A modified seal is refused with one code and one message
whichever check catches it (padding or the root's digest), so startup errors are not a padding oracle.
Measured on SoftHSM2 2.6.1 + OpenSC 0.25 (`test/proba-hsm.mjs`, 20/20 on 2026-09-29, needs Node 24 and a PKCS#11 module; the
library and PIN rules above in `test/proba-hsm-incredere.mjs`, 7/7 without an HSM, with `test/control-negativ-hsm-incredere.mjs`):
key generated in the token and not readable out of it, seal/open round trip, the KMS started from the
HSM-opened root and a hybrid round trip through it, and named refusals for a wrong PIN, a missing PIN,
another token, another key and a modified seal. What it does **not** change: after opening, the root is in
process memory as before; the hybrid ML-KEM/ML-DSA operations run in the KMS, not in the HSM (standard
PKCS#11 does not expose them); `pkcs11-tool` works on files, so the root passes for milliseconds through a
file under `/dev/shm`, zero-filled and removed. The mechanism is AES-CBC-PAD (OpenSC 0.25 does not expose
AES-GCM for encryption), so the seal carries 16 bytes of the root's own digest and a modified seal is a named
refusal, never a wrong root. Not yet exercised against a physical HSM.
## Threat model (short)
Defended, and exercised by the test suite (`test/proba.mjs`):
- **A future quantum adversary against stored ciphertexts** (harvest now, decrypt later): the data key
depends on the ML-KEM-768 secret, so breaking X25519 alone does not open an envelope. The reverse also
holds: a flaw in ML-KEM alone does not open an envelope while X25519 stands.
- **Signature forgery with one broken scheme:** a forger must produce valid Ed25519 **and** ML-DSA-65
signatures; the halves cannot be separated and reused as plain signatures over the raw message.
- **Tampering with ciphertexts:** any modified byte, a different `aad`, a different key, a different
version or a retired version is refused with a named reason.
- **Theft of the data directory without the root key:** private keys are sealed with AES-256-GCM; key
files carry an HMAC so that swapped public keys or a lowered `min_decryption_version` are refused.
- **Editing the audit log without the root key:** rows are HMAC-chained; a deleted, changed or reordered
row is detected.
Not defended:
- Compromise of the running process or of the host (memory, environment, debugger).
- An attacker with the root key.
- **Rollback** of the whole data directory (or of one key file) to an older, validly-MACed state, e.g. to
undo a raise of `min_decryption_version`. There is no monotonic counter.
- **Truncation of the audit log's tail** is only detected against an externally recorded head
(`verifyAudit({ expectedHead })`); on its own a hash chain cannot see missing trailing rows.
- Side channels (timing, cache, power) of the underlying OpenSSL implementations were not evaluated.
## Running
```sh
export AERE_KMS_ROOT_KEY=<64 hex characters> # required; the service refuses to start without it
export AERE_KMS_TOKEN=<at least 32 printable chars> # required; clients send "Authorization: Bearer <token>"
node server.mjs
```
| variable | default | meaning |
|---------------------|--------------------|---------|
| `AERE_KMS_ROOT_KEY` | none (required, or `AERE_KMS_ROOT_HSM`) | 32 bytes as hex. Missing, malformed or all-zero: refuses to start. **Never generated automatically.** |
| `AERE_KMS_ROOT_HSM` | none | path of a root sealed by an HSM (see above); exactly one of this and `AERE_KMS_ROOT_KEY` |
| `AERE_HSM_MODULE` | none (required with `AERE_KMS_ROOT_HSM`) | absolute path of the PKCS#11 library; must equal the one recorded in the sealed file |
| `AERE_HSM_PIN` | none (required with `AERE_KMS_ROOT_HSM`) | the token PIN, read by `pkcs11-tool` from the environment, never on a command line |
| `AERE_KMS_TOKEN` | none (required) | bearer token, 32+ printable ASCII characters, must differ from the root key |
| `AERE_KMS_HOST` | `127.0.0.1` | listen address |
| `AERE_KMS_PORT` | `8420` | listen port (`0` picks a free one) |
| `AERE_KMS_MAX_BODY` | `65536` | request body limit in bytes, 8192 to 16777216 (a hybrid signature alone is 4531 base64 characters) |
| `AERE_KMS_DATA_DIR` | `./data` next to `server.mjs` | key files, root check, audit log |
A data directory is bound to the root key it was created with: opening it with another root key fails
with `ROOT_KEY_MISMATCH`. No error message ever contains key material, the root key or the token.
Generate a root key with, for example:
`node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`.
## HTTP API
All bodies are JSON. Binary values (`plaintext`, `aad`, `message`) are **standard base64**; ciphertexts
and signatures are the self-describing strings below. Errors are `{ "error": CODE, "message": text }`.
Every route except `GET /v1/health` requires `Authorization: Bearer <token>`.
| method and path | body | response |
|---|---|---|
| `GET /v1/health` | | `{ ok: true }` (no auth) |
| `GET /v1/keys` | | `{ keys: [names] }` |
| `POST /v1/keys/:name` | `{ type: "encrypt"\|"sign", exportable?: false }` | key description (public keys only) |
| `GET /v1/keys/:name` | | key description |
| `POST /v1/keys/:name/rotate` | | key description with a new latest version |
| `POST /v1/keys/:name/config` | `{ min_decryption_version: n }` | key description |
| `GET /v1/keys/:name/export[/:version]` | | private keys (PKCS#8 DER, base64); `403 KEY_NOT_EXPORTABLE` unless exportable |
| `POST /v1/encrypt/:name` | `{ plaintext, aad? }` | `{ ciphertext, version }` |
| `POST /v1/decrypt/:name` | `{ ciphertext, aad? }` | `{ plaintext, version }` |
| `POST /v1/rewrap/:name` | `{ ciphertext, aad? }` | `{ ciphertext, version }` (the plaintext never leaves the process) |
| `POST /v1/datakey/:name` | `{ aad?, bits?: 128\|256\|512, include_plaintext?: true }` | `{ ciphertext, version, plaintext? }` |
| `POST /v1/sign/:name` | `{ message }` | `{ signature, version }` |
| `POST /v1/verify/:name` | `{ message, signature }` | `{ valid, reason, version, classical, post_quantum }` |
| `GET /v1/audit/verify` | | `{ ok, rows, head }` or `{ ok: false, reason, line }` |
Key names match `^[a-z0-9][a-z0-9_-]{0,63}$`.
### Versions, rotation and retirement
- `rotate` adds a version; `encrypt`, `datakey`, `rewrap` and `sign` always use the latest one.
- Older versions keep decrypting and verifying until `min_decryption_version` is raised past them.
After that, decrypt and rewrap fail with `VERSION_BELOW_MINIMUM`, and verify returns
`valid: false, reason: "VERSION_BELOW_MINIMUM"`.
- `min_decryption_version` **can only be raised** (`MIN_VERSION_NOT_MONOTONIC`), and never above the latest
version (`VERSION_OUT_OF_RANGE`). Retired private keys stay on disk; there is no trim.
- `exportable` is set at creation and cannot be changed. It defaults to `false`.
### Error codes
| code | when |
|---|---|
| `MALFORMED_CIPHERTEXT`, `MALFORMED_SIGNATURE` | not `aerekms:v<n>:<base64>`, non-canonical base64, wrong header, wrong length |
| `VERSION_MISMATCH` | the prefix version and the embedded version differ, or the envelope belongs to another version of this key |
| `KEY_MISMATCH` | the envelope was produced by a different key |
| `UNKNOWN_VERSION` | the key has no such version |
| `VERSION_BELOW_MINIMUM` | the version is retired by `min_decryption_version` |
| `HEADER_AUTH_FAILED` | the key encapsulation, header or aad tag was modified, or the envelope was not produced for this key version (key commitment failed) |
| `AAD_MISMATCH` | the `aad` differs from the one used at encryption |
| `PAYLOAD_AUTH_FAILED` | the encrypted payload or its GCM tag was modified or truncated |
| `CLASSICAL_SIGNATURE_INVALID`, `PQ_SIGNATURE_INVALID`, `BOTH_SIGNATURES_INVALID` | which half of a hybrid signature failed |
| `KEY_NOT_FOUND`, `KEY_EXISTS`, `WRONG_KEY_TYPE`, `INVALID_KEY_NAME`, `INVALID_KEY_TYPE`, `INVALID_POLICY`, `INVALID_BITS`, `KEY_NOT_EXPORTABLE` | request errors |
| `ROOT_KEY_MISSING`, `ROOT_KEY_INVALID`, `ROOT_KEY_WEAK`, `ROOT_KEY_MISMATCH`, `ROOT_CHECK_MISSING` | refuses to start |
| `KEY_FILE_TAMPERED`, `SEAL_AUTH_FAILED` | a key file on disk fails its integrity check |
| `AUDIT_CHAIN_INVALID` | refuses to start on an audit log that does not verify (move it aside as evidence to begin a new chain) |
| `AUDIT_WRITE_FAILED` | the audit row could not be written; the result is withheld, and any change the operation made to the key file (a new key, a new version, a raised minimum) is rolled back, so a change exists only if its audit row exists |
| `UNAUTHENTICATED`, `INVALID_TOKEN` | 401 |
| `BODY_TOO_LARGE` | 413 |
## Library API
```js
import { openKms } from './kms.mjs';
const kms = openKms({ dataDir: './data', rootKey: process.env.AERE_KMS_ROOT_KEY });
kms.createKey('orders', { type: 'encrypt' }); // exportable: false by default
const { ciphertext } = kms.encrypt('orders', 'secret', 'tenant-42');
const { plaintext } = kms.decrypt('orders', ciphertext, 'tenant-42');
kms.rotate('orders'); kms.rewrap('orders', ciphertext, 'tenant-42');
kms.setMinDecryptionVersion('orders', 2);
kms.datakey('orders', { aad: 'file-7', bits: 256, includePlaintext: true });
kms.createKey('releases', { type: 'sign' });
const { signature } = kms.sign('releases', 'artifact bytes');
kms.verify('releases', 'artifact bytes', signature); // { valid, reason, classical, post_quantum, version }
kms.verifyAudit({ expectedHead }); // expectedHead = an earlier kms.auditHead()
```
Refusals throw `KmsError` with a `code` from the table above (`verify` returns `valid: false` instead).
## Wire format
Everything below is fixed by this implementation so that third parties can interoperate using only
standard primitives; `test/proba.mjs` contains a second, independent implementation of it (including
a hand-written HKDF) that decapsulates the service's envelopes and builds envelopes the service accepts.
Notation: `u32` is big-endian, `lp(x)` is `u32(len(x)) || x`, strings are UTF-8, `\0` is a zero byte.
### Public keys and fingerprint
- `encrypt` version: `x25519` = raw 32-byte public key; `ml_kem_768` = SPKI DER (1206 bytes; the raw
1184-byte encapsulation key follows a fixed 22-byte header).
- `sign` version: `ed25519` = raw 32 bytes; `ml_dsa_65` = SPKI DER (1974 bytes; raw key 1952 bytes).
- `fingerprint = SHA-256("aerekms/v1/fingerprint\0" || kind || lp(name) || u32(version) || pubA_raw || pubB_raw)[0..8]`,
with `kind` = `0x45` ('E') or `0x53` ('S').
### Ciphertext: `aerekms:v<version>:<base64(body)>`
```
body = "AKM1" | 0x45 | u32 version | fp(8) | ePub(32) | ctK(1088) | aadTag(16) | commit(16) | payload | gcmTag(16)
```
1. `ePub` is a fresh X25519 public key; `ssX = X25519(eph, recipient_x25519)`.
2. `(ssK, ctK) = ML-KEM-768.Encaps(recipient_ml_kem_768)`.
3. `transcript = "aerekms/v1/hybrid-kem\0" || lp(name) || u32(version) || fp || recipient_x25519_raw || SHA-256(recipient_ek_raw) || ePub || ctK`
4. `IKM = ssK || ssX`, `salt = SHA-256(transcript)`, and with HKDF-SHA-256:
- `commitKey = HKDF(IKM, salt, "aerekms/v1/commit", 32)`
- `aadKey = HKDF(IKM, salt, "aerekms/v1/aad", 32)`, `aadTag = HMAC-SHA-256(aadKey, aad)[0..16]`
- `key || iv = HKDF(IKM, salt, "aerekms/v1/dek\0" || SHA-256(aad), 44)`
5. `commit = HMAC-SHA-256(commitKey, body[0 .. commit offset))[0..16]` (a key commitment over the whole
header, including `aadTag`).
6. `payload || gcmTag = AES-256-GCM(key, iv, plaintext, AAD = body[0 .. payload offset))`.
Decryption checks, in order: format, prefix version = embedded version, version exists and is not retired,
fingerprint, decapsulation, `commit`, `aadTag`, GCM. Each step has its own error code. Absent `aad` and
empty `aad` are the same thing.
The combiner is the common "concatenate both secrets, bind both encapsulations, then KDF" construction.
No formal security proof is provided here.
### Signature: `aerekms:v<version>:<base64(body)>`
```
body = "AKS1" | 0x53 | u32 version | fp(8) | ed25519_sig(64) | ml_dsa_65_sig(3309)
M' = "aerekms/v1/hybrid-sig\0ed25519+ml-dsa-65\0" || fp || u32(version) || message
```
Ed25519 signs `M'`; ML-DSA-65 (pure, FIPS 204) signs `M'` with context string `"aerekms/v1"`. Because both
sign `M'` and not the raw message, neither half is a valid signature over the message on its own.
### Storage
- `data/root-check.json`: an HMAC under a key derived from the root key; detects a wrong root key.
- `data/keys/<name>.json`: key metadata, public keys, and per version `private_sealed` =
`base64(iv(12) || AES-256-GCM ciphertext || tag(16))` of the PKCS#8 private keys, with
AAD `"aerekms/v1/seal\0" name "\0" type "\0" version "\0" fingerprint_hex`. The whole file carries
`mac` = HMAC-SHA-256 over its canonical JSON. Files are written atomically (temp file, fsync, rename).
- Sub-keys are derived from the root key with HKDF-SHA-256 (salt `"aerekms/v1/root"`, one info label each:
seal, key-file MAC, audit chain, root check). The derived root key buffer is zeroed after derivation; the
environment variable it came from is not (see the limits above).
### Audit log: `data/audit.log`
One JSON object per line: `{ seq, ts, op, key, version, ok, reason, prev, mac }`, where `prev` is the
previous row's `mac` (64 zeros for the first row) and `mac = HMAC-SHA-256(auditKey, canonical JSON of the
row without mac)`. Rows never contain plaintext, aad, messages, ciphertexts or key material. Every
operation writes a row, including refused ones (with `ok: false` and the reason code); the row is
fsynced before the result is returned. `verifyAudit()` reports `AUDIT_ROW_MODIFIED`,
`AUDIT_CHAIN_BROKEN` (deleted or reordered rows), `AUDIT_ROW_UNPARSABLE`, and, given an external head,
`AUDIT_TRUNCATED` / `AUDIT_HEAD_MISMATCH`. Record `auditHead()` somewhere else if tail truncation matters.
## Tests
```sh
node test/proba.mjs # the test suite
node test/control-negativ.mjs # plants defects in a copy; each must turn named tests red
node test/control-negativ.mjs --autoproba # decoy plants; the control itself must report each as a failure
```
`test/proba.mjs` pairs every positive assertion with a negative one and checks the refusal **reason**,
not just that something failed. `test/control-negativ.mjs` copies the code to a temp directory, plants
one defect at a time (KDF without the ML-KEM secret, KDF without the X25519 secret, verification that
accepts one signature, ignored aad, ignored minimum version, unchained audit writer, verifier that skips
the chain, verifier that skips row MACs, private key written in clear, key file MAC not checked, root
key generated silently, fingerprint not checked, rewrap returning plaintext, missing auth accepted, body
limit ignored), and requires the named tests to fail with the named message. It reads the suite's JSON
output, not its exit code, and checks that the original files are byte-identical afterwards.
Measured on 2026-09-25, Windows 11, Node 24.14.1, OpenSSL 3.5.5: 61/61 tests pass; the negative control
catches 15/15 plantings; the control's self-test gives 5/5 decoys their failure verdict. Not measured:
Linux or macOS (including whether the `0o600`/`0o700` file modes are applied; Windows ignores them),
throughput under load, behaviour with concurrent processes, side channels.
+142
View File
@@ -0,0 +1,142 @@
// hsm-radacina.mjs - Aere PQ KMS: cheia radacina SIGILATA de un HSM prin PKCS#11 (roadmap master 16, "HSM").
//
// DE CE: pana acum radacina KMS-ului statea IN CLAR in mediu (AERE_KMS_ROOT_KEY), iar README-ul o spune: "Not an HSM". Cu acest
// modul radacina sta pe disc numai SIGILATA de o cheie AES-256 care traieste in HSM si nu poate iesi de acolo (CKA_SENSITIVE,
// CKA_EXTRACTABLE=false); la pornire, KMS-ul cere HSM-ului sa o deschida, cu PIN-ul tokenului. Cine fura discul si mediul fara HSM
// si fara PIN nu are radacina. Masurat pe SoftHSM2 2.6.1 + OpenSC 0.25 (test/proba-hsm.mjs); un HSM fizic se foloseste la fel,
// prin modulul PKCS#11 al producatorului.
//
// CE NU FACE (spus, nu ascuns): dupa deschidere radacina e in memoria procesului, ca inainte (HSM-ul nu face operatiile hibride
// ML-KEM/ML-DSA: niciun HSM de pe piata la data scrierii nu le expune prin PKCS#11 standard); `pkcs11-tool` lucreaza cu fisiere, deci
// radacina trece cateva milisecunde printr-un fisier din /dev/shm (memorie, nu disc), umplut cu zerouri si sters imediat. Integritatea:
// mecanismul folosit e AES-CBC-PAD (OpenSC 0.25 nu expune AES-GCM la cifrare), deci radacina se sigileaza impreuna cu 16 octeti din
// amprenta ei; o sigilare atinsa sau deschisa cu alta cheie da REFUZ numit, nu o radacina gresita (care oricum ar fi refuzata de
// verificarea radacinii din kms.mjs).
//
// node hsm-radacina.mjs sigileaza --modul <lib.so> --token <eticheta> --id <hex> --iesire <fisier> [--nou]
// radacina: AERE_KMS_ROOT_KEY (o radacina existenta) sau --nou (una noua, aleatoare); PIN-ul: AERE_HSM_PIN
// node hsm-radacina.mjs verifica <fisier> deschide sigilarea si spune doar DA/NU (nu tipareste niciodata radacina);
// biblioteca: AERE_HSM_MODULE (trebuie sa fie exact cea din fisier), PIN-ul: AERE_HSM_PIN
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { KmsError, parseRootKey } from './kms.mjs';
export const FORMAT_HSM = 'aerekms-root-hsm/1';
// 2026-09-29, revizuirea adversariala a felii HSM (pista B), inainte de publicare:
// H1: fisierul sigilat numea biblioteca PKCS#11 (`modul`) si variabila PIN-ului (`pinEnv`), iar deschiderea le credea. Cine poate scrie
// fisierul (sta pe disc, e facut sa stea acolo) facea KMS-ul sa incarce ORICE biblioteca la pornire (cod strain in procesul KMS) si
// sa-i dea PIN-ul, sau alta variabila de mediu (de ex. jetonul API) drept PIN. Acum biblioteca vine din configuratia procesului
// (AERE_HSM_MODULE, cale absoluta) si trebuie sa fie EXACT cea din fisier, verificat INAINTE de orice rulare a uneltei; variabila
// PIN-ului e fixa (AERE_HSM_PIN), fisierul nu o poate alege.
// H2: cele doua drumuri de refuz ale unei sigilari atinse (umplutura CBC stricata / amprenta gresita) aveau MESAJE diferite; cine poate
// modifica fisierul si citi jurnalul pornirii avea un oracol de umplutura pe AES-CBC-PAD. Acum acelasi cod si acelasi mesaj.
export const PIN_ENV = 'AERE_HSM_PIN';
const MESAJ_ATINS = 'the sealed root does not open to the sealed root with this HSM key (modified, or sealed by another key)';
const ETICHETA = /^[A-Za-z0-9._-]{1,32}$/;
const ID_HEX = /^[0-9a-fA-F]{2,64}$/;
const amprenta = (r) => crypto.createHash('sha256').update(Buffer.concat([Buffer.from(FORMAT_HSM + '\0', 'utf8'), r])).digest().subarray(0, 16);
function dosarRam() {
const baza = fs.existsSync('/dev/shm') ? '/dev/shm' : os.tmpdir();
return fs.mkdtempSync(path.join(baza, 'aerekms-hsm-'));
}
function stergeSigur(f) {
try { const n = fs.statSync(f).size; fs.writeFileSync(f, Buffer.alloc(n)); } catch { /* nu exista */ }
try { fs.rmSync(f, { force: true }); } catch { /* */ }
}
function pkcs11(unealta, args, env) {
const r = spawnSync(unealta, args, { env, encoding: 'utf8', timeout: 60_000 });
if (r.error && r.error.code === 'ENOENT') throw new KmsError('HSM_TOOL_MISSING', `${unealta} is not installed (OpenSC)`);
if (r.error) throw new KmsError('HSM_TOOL_FAILED', `${unealta} could not run: ${r.error.code || 'error'}`);
const err = (r.stderr || '') + (r.stdout || '');
if (r.status !== 0) {
if (/CKR_PIN_INCORRECT|CKR_PIN_LEN_RANGE|CKR_PIN_LOCKED|Login failed/i.test(err)) throw new KmsError('HSM_LOGIN_REFUSED', 'the HSM refused the PIN');
if (/No slot|token.*not found|Can't find|No token/i.test(err)) throw new KmsError('HSM_TOKEN_NOT_FOUND', 'the HSM token or key was not found');
throw new KmsError('HSM_OPERATION_FAILED', 'the HSM refused the operation');
}
return r;
}
function comuni({ modul, token, idCheie, pinEnv }) {
if (typeof modul !== 'string' || !path.isAbsolute(modul)) throw new KmsError('HSM_CONFIG_INVALID', 'modul must be the absolute path of the PKCS#11 library');
if (!ETICHETA.test(String(token || ''))) throw new KmsError('HSM_CONFIG_INVALID', 'token label must match ^[A-Za-z0-9._-]{1,32}$');
if (!ID_HEX.test(String(idCheie || ''))) throw new KmsError('HSM_CONFIG_INVALID', 'key id must be hex');
if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(String(pinEnv))) throw new KmsError('HSM_CONFIG_INVALID', 'pinEnv must name an environment variable');
return ['--module', modul, '--token-label', token, '--login', '--pin', 'env:' + pinEnv, '--id', idCheie, '--mechanism', 'AES-CBC-PAD'];
}
/** sigileaza o radacina de 32 de octeti cu cheia AES a HSM-ului; intoarce sigilarea (JSON), niciodata radacina */
export function sigileazaRadacina({ modul, token, idCheie, radacina, env = process.env, unealta = 'pkcs11-tool' }) {
const pinEnv = PIN_ENV;
if (!Buffer.isBuffer(radacina) || radacina.length !== 32 || radacina.every((x) => x === 0)) throw new KmsError('ROOT_KEY_INVALID', 'the root to seal must be 32 non-zero bytes');
if (!String(env[pinEnv] || '')) throw new KmsError('HSM_PIN_MISSING', `${pinEnv} is not set`);
const a = comuni({ modul, token, idCheie, pinEnv });
const iv = crypto.randomBytes(16);
const d = dosarRam(); const pt = path.join(d, 'r'), ct = path.join(d, 'c');
try {
fs.writeFileSync(pt, Buffer.concat([radacina, amprenta(radacina)]), { mode: 0o600 });
pkcs11(unealta, [...a, '--encrypt', '--iv', iv.toString('hex'), '--input-file', pt, '--output-file', ct], env);
const c = fs.readFileSync(ct);
if (c.length !== 64) throw new KmsError('HSM_OPERATION_FAILED', `unexpected sealed length ${c.length}`);
return { format: FORMAT_HSM, mecanism: 'AES-CBC-PAD', modul, token, idCheie: idCheie.toLowerCase(), pinEnv, iv: iv.toString('hex'), ct: c.toString('hex'), creat: new Date().toISOString() };
} finally { stergeSigur(pt); stergeSigur(ct); fs.rmSync(d, { recursive: true, force: true }); }
}
/** deschide o sigilare cu HSM-ul; intoarce radacina (Buffer de 32) sau arunca un refuz NUMIT */
export function deschideRadacina(sig, { env = process.env, unealta = 'pkcs11-tool' } = {}) {
if (!sig || sig.format !== FORMAT_HSM || sig.mecanism !== 'AES-CBC-PAD') throw new KmsError('HSM_SEAL_INVALID', `the sealed root is not ${FORMAT_HSM}`);
if (!/^[0-9a-f]{32}$/.test(String(sig.iv)) || !/^[0-9a-f]{128}$/.test(String(sig.ct))) throw new KmsError('HSM_SEAL_INVALID', 'the sealed root has a malformed iv or ciphertext');
// H1: biblioteca si variabila PIN-ului NU se iau din fisier; nimic nu ruleaza pana nu trec ambele verificari
const permis = String(env.AERE_HSM_MODULE || '').trim();
if (!permis || !path.isAbsolute(permis)) throw new KmsError('HSM_CONFIG_INVALID', 'AERE_HSM_MODULE must name the PKCS#11 library (absolute path); the sealed file alone does not choose it');
if (sig.modul !== permis) throw new KmsError('HSM_MODULE_NOT_ALLOWED', 'the sealed root names a PKCS#11 library other than AERE_HSM_MODULE; it is not loaded');
if (sig.pinEnv !== undefined && sig.pinEnv !== PIN_ENV) throw new KmsError('HSM_SEAL_INVALID', `the PIN is always read from ${PIN_ENV}; a sealed file cannot choose another variable`);
const pinEnv = PIN_ENV;
if (!String(env[pinEnv] || '')) throw new KmsError('HSM_PIN_MISSING', `${pinEnv} is not set`);
const a = comuni({ modul: permis, token: sig.token, idCheie: sig.idCheie, pinEnv });
const d = dosarRam(); const ct = path.join(d, 'c'), pt = path.join(d, 'r');
try {
fs.writeFileSync(ct, Buffer.from(sig.ct, 'hex'), { mode: 0o600 });
try { pkcs11(unealta, [...a, '--decrypt', '--iv', sig.iv, '--input-file', ct, '--output-file', pt], env); }
catch (e) { if (e.code === 'HSM_OPERATION_FAILED') throw new KmsError('HSM_ROOT_TAMPERED', MESAJ_ATINS); throw e; }
const p = fs.readFileSync(pt);
const r = Buffer.from(p.subarray(0, 32)); const t = p.subarray(32);
const bun = p.length === 48 && crypto.timingSafeEqual(t, amprenta(r));
p.fill(0);
if (!bun) { r.fill(0); throw new KmsError('HSM_ROOT_TAMPERED', MESAJ_ATINS); }
return r;
} finally { stergeSigur(ct); stergeSigur(pt); fs.rmSync(d, { recursive: true, force: true }); }
}
/** din mediu: AERE_KMS_ROOT_HSM (calea sigilarii) -> radacina in hex, exact forma pe care o primea kms.mjs din AERE_KMS_ROOT_KEY */
export function radacinaDinHsm(env, optiuni = {}) {
const f = String(env.AERE_KMS_ROOT_HSM || '').trim();
let sig;
try { sig = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { throw new KmsError('HSM_SEAL_INVALID', 'AERE_KMS_ROOT_HSM does not point to a readable sealed root'); }
const r = deschideRadacina(sig, { env, ...optiuni });
const h = r.toString('hex'); r.fill(0);
return h;
}
async function cli(argv) {
const [cmd, ...rest] = argv;
const opt = (n) => { const i = rest.indexOf(n); return i >= 0 ? rest[i + 1] : undefined; };
try {
if (cmd === 'sigileaza') {
const iesire = opt('--iesire'); if (!iesire) throw new KmsError('HSM_CONFIG_INVALID', '--iesire <file> is required');
if (fs.existsSync(iesire)) throw new KmsError('HSM_CONFIG_INVALID', 'the output file exists; a sealed root is never overwritten');
const radacina = rest.includes('--nou') ? crypto.randomBytes(32) : parseRootKey(process.env.AERE_KMS_ROOT_KEY);
const sig = sigileazaRadacina({ modul: opt('--modul'), token: opt('--token'), idCheie: opt('--id'), radacina });
radacina.fill(0);
fs.writeFileSync(iesire, JSON.stringify(sig, null, 1) + '\n', { mode: 0o600, flag: 'wx' });
console.log(`sealed root written to ${iesire} (${FORMAT_HSM}, token ${sig.token}, key id ${sig.idCheie})`);
} else if (cmd === 'verifica') {
const r = deschideRadacina(JSON.parse(fs.readFileSync(rest[0], 'utf8'))); r.fill(0);
console.log('DA: the sealed root opens with this HSM and PIN');
} else { console.error('usage: node hsm-radacina.mjs sigileaza --modul <lib> --token <label> --id <hex> --iesire <file> [--nou] | verifica <file> (PIN in AERE_HSM_PIN; verifica also needs AERE_HSM_MODULE)'); process.exitCode = 2; }
} catch (e) { console.error(`NU: ${e.code || 'ERROR'}: ${e.message}`); process.exitCode = 1; }
}
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) cli(process.argv.slice(2));
+912
View File
@@ -0,0 +1,912 @@
// kms.mjs - Aere PQ KMS: un KMS de tip "transit" (ca Vault transit), hibrid clasic + post-cuantic.
//
// Numai node:crypto (Node 24, OpenSSL 3.5), fara dependinte.
//
// chei "encrypt": X25519 + ML-KEM-768, KEM hibrid; secretul plicului se deriva cu HKDF-SHA-256
// peste AMBELE secrete partajate si peste transcriptul ambelor encapsulari,
// legat de nume + versiune + aad; apoi AES-256-GCM.
// chei "sign": Ed25519 + ML-DSA-65; semnatura poarta AMBELE jumatati si verificarea le cere
// pe amandoua.
//
// Cheile private stau pe disc sigilate cu AES-256-GCM sub o cheie derivata din AERE_KMS_ROOT_KEY.
// Fara cheia radacina constructorul refuza (nu se genereaza nicio cheie in tacere).
// Fiecare operatie scrie un rand in jurnalul de audit inlantuit (HMAC peste rand + mac-ul
// randului anterior), fara date clare si fara material de cheie.
//
// Niciun mesaj de eroare nu contine material de cheie: mesajele sunt texte fixe plus nume de
// chei si numere de versiune.
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
export const PREFIX = 'aerekms';
export const KEY_FORMAT = 'aerekms-key/1';
const ZERO_MAC = '0'.repeat(64);
// Etichetele de domeniu. Fac parte din format: un tert care vrea interoperabilitate le
// foloseste exact asa (README, sectiunea "Wire format").
export const LABELS = Object.freeze({
root: 'aerekms/v1/root',
seal: 'aerekms/v1/seal-private',
sealAad: 'aerekms/v1/seal',
fileMac: 'aerekms/v1/key-file-mac',
audit: 'aerekms/v1/audit-chain',
rootCheck: 'aerekms/v1/root-check',
fp: 'aerekms/v1/fingerprint',
kem: 'aerekms/v1/hybrid-kem',
commit: 'aerekms/v1/commit',
aad: 'aerekms/v1/aad',
dek: 'aerekms/v1/dek',
sig: 'aerekms/v1/hybrid-sig',
sigAlg: 'ed25519+ml-dsa-65',
sigCtx: 'aerekms/v1',
});
// Marimi masurate pe Node 24.14.1 / OpenSSL 3.5.5 (2026-09-25).
const SZ = Object.freeze({ x: 32, ek: 1184, ctK: 1088, ed: 64, pkDsa: 1952, mlSig: 3309, fp: 8 });
// Antetele SPKI sunt fixe (22 de octeti); le verificam octet cu octet, nu doar lungimea.
const SPKI_HDR = Object.freeze({
'ml-kem-768': Buffer.from('308204b2300b0609608648016503040402038204a100', 'hex'),
'ml-dsa-65': Buffer.from('308207b2300b0609608648016503040312038207a100', 'hex'),
});
const MAGIC_E = Buffer.from('AKM1', 'ascii');
const MAGIC_S = Buffer.from('AKS1', 'ascii');
const KIND_E = 0x45; // 'E'
const KIND_S = 0x53; // 'S'
// Plicul de criptare:
// magic(4) | kind(1) | version u32be(4) | fp(8) | ePub X25519(32) | ct ML-KEM(1088)
// | aadTag(16) | commit(16) | payload AES-256-GCM (n) | gcmTag(16)
const OFF = Object.freeze({ ver: 5, fp: 9, ePub: 17, ctK: 49, aadTag: 1137, commit: 1153, payload: 1169 });
const ENV_MIN = OFF.payload + 16;
// Semnatura: magic(4) | kind(1) | version(4) | fp(8) | Ed25519(64) | ML-DSA-65(3309)
const SIG_LEN = 17 + SZ.ed + SZ.mlSig;
const MAX_PLAINTEXT = 1024 * 1024;
const MAX_MESSAGE = 1024 * 1024;
const MAX_AAD = 64 * 1024;
const NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
const ENV_RE = /^aerekms:v([1-9][0-9]{0,8}):([A-Za-z0-9+/]+={0,2})$/;
export class KmsError extends Error {
constructor(code, message, extra) {
super(message);
this.name = 'KmsError';
this.code = code;
if (extra) Object.assign(this, extra);
}
}
// ---------------------------------------------------------------------------------------------
// primitive mici
function u32(n) {
const b = Buffer.alloc(4);
b.writeUInt32BE(n >>> 0);
return b;
}
function lp(b) {
const x = Buffer.from(b);
return Buffer.concat([u32(x.length), x]);
}
function utf8(s) {
return Buffer.from(s, 'utf8');
}
function sha256(...parts) {
const h = crypto.createHash('sha256');
for (const p of parts) h.update(p);
return h.digest();
}
function hmac(key, ...parts) {
const h = crypto.createHmac('sha256', key);
for (const p of parts) h.update(p);
return h.digest();
}
function hkdf(ikm, salt, info, len) {
return Buffer.from(crypto.hkdfSync('sha256', ikm, salt, info, len));
}
function ctEq(a, b) {
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
export function canonicalJson(v) {
if (v === null || typeof v !== 'object') return JSON.stringify(v);
if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']';
const keys = Object.keys(v).filter((k) => v[k] !== undefined).sort();
return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalJson(v[k])).join(',') + '}';
}
function writeFileAtomic(p, text) {
const tmp = `${p}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`;
const fd = fs.openSync(tmp, 'w', 0o600);
try {
fs.writeSync(fd, text);
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmp, p);
}
// ---------------------------------------------------------------------------------------------
// cheia radacina
// Citeste AERE_KMS_ROOT_KEY. Refuza lipsa, forma gresita si cheia de zerouri. Mesajul spune
// cel mult LUNGIMEA valorii, niciodata valoarea.
export function parseRootKey(value) {
const s = value === undefined || value === null ? '' : String(value).trim();
if (s === '') throw new KmsError('ROOT_KEY_MISSING', 'AERE_KMS_ROOT_KEY is not set; refusing to start (a root key is never generated automatically)');
if (!/^[0-9a-fA-F]{64}$/.test(s)) {
throw new KmsError('ROOT_KEY_INVALID', `AERE_KMS_ROOT_KEY must be exactly 64 hexadecimal characters (32 bytes); the value given has ${s.length} characters or contains non-hex characters`);
}
const b = Buffer.from(s, 'hex');
if (b.every((x) => x === 0)) throw new KmsError('ROOT_KEY_WEAK', 'AERE_KMS_ROOT_KEY is all zeros; refusing to start');
return b;
}
// ---------------------------------------------------------------------------------------------
// intrari
function checkName(name) {
if (typeof name !== 'string' || !NAME_RE.test(name)) {
throw new KmsError('INVALID_KEY_NAME', 'key name must match ^[a-z0-9][a-z0-9_-]{0,63}$');
}
return name;
}
function toBytes(v, what, max) {
let b;
if (Buffer.isBuffer(v) || v instanceof Uint8Array) b = Buffer.from(v);
else if (typeof v === 'string') b = utf8(v);
else throw new KmsError('INVALID_INPUT', `${what} must be a Buffer, Uint8Array or string`);
if (b.length > max) throw new KmsError(`${what.toUpperCase()}_TOO_LARGE`, `${what} is larger than ${max} bytes`);
return b;
}
function normAad(aad) {
if (aad === undefined || aad === null) return Buffer.alloc(0);
return toBytes(aad, 'aad', MAX_AAD);
}
// ---------------------------------------------------------------------------------------------
// codificarea cheilor publice
function rawOkp(pub) {
return Buffer.from(pub.export({ format: 'jwk' }).x, 'base64url');
}
function okpPublic(raw, crv) {
return crypto.createPublicKey({ key: { kty: 'OKP', crv, x: Buffer.from(raw).toString('base64url') }, format: 'jwk' });
}
function rawFromSpki(spki, alg) {
const hdr = SPKI_HDR[alg];
if (!spki.subarray(0, hdr.length).equals(hdr)) throw new KmsError('INTERNAL', `unexpected SPKI encoding for ${alg}`);
return spki.subarray(hdr.length);
}
function fingerprint(kind, name, ver, pubA, pubB) {
return sha256(utf8(LABELS.fp + '\0'), Buffer.from([kind]), lp(utf8(name)), u32(ver), pubA, pubB).subarray(0, SZ.fp);
}
function sealAad(name, type, ver, fpHex) {
return utf8(`${LABELS.sealAad}\0${name}\0${type}\0${ver}\0${fpHex}`);
}
// ---------------------------------------------------------------------------------------------
// KEM hibrid
// Transcriptul leaga: numele cheii, versiunea, amprenta, cheia X25519 a destinatarului,
// amprenta cheii ML-KEM a destinatarului, cheia X25519 efemera si textul cifrat ML-KEM.
function kemTranscript(name, ver, fp, xPub, ekRaw, ePub, ctK) {
return Buffer.concat([utf8(LABELS.kem + '\0'), lp(utf8(name)), u32(ver), fp, xPub, sha256(ekRaw), ePub, ctK]);
}
// Secretul plicului: HKDF-SHA-256 cu IKM = ss_ML-KEM || ss_X25519 si sare = SHA-256(transcript).
// Din el ies: cheia de angajament (commit), cheia etichetei aad si cheia AES + IV-ul, ultima
// legata si de aad prin info.
function deriveKeys(ssK, ssX, transcript, aad) {
const ikm = Buffer.concat([ssK, ssX]);
const salt = sha256(transcript);
const commitKey = hkdf(ikm, salt, utf8(LABELS.commit), 32);
const aadKey = hkdf(ikm, salt, utf8(LABELS.aad), 32);
const dek = hkdf(ikm, salt, Buffer.concat([utf8(LABELS.dek + '\0'), sha256(aad)]), 44);
ikm.fill(0);
return { commitKey, aadTag: hmac(aadKey, aad).subarray(0, 16), key: dek.subarray(0, 32), iv: dek.subarray(32, 44), dek };
}
function sigMessage(fp, ver, message) {
return Buffer.concat([utf8(LABELS.sig + '\0' + LABELS.sigAlg + '\0'), fp, u32(ver), message]);
}
function parseEnvelope(str, kind) {
const what = kind === KIND_E ? 'ciphertext' : 'signature';
const bad = kind === KIND_E ? 'MALFORMED_CIPHERTEXT' : 'MALFORMED_SIGNATURE';
if (typeof str !== 'string') throw new KmsError(bad, `${what} must be a string of the form aerekms:v<version>:<base64>`);
const m = ENV_RE.exec(str);
if (!m) throw new KmsError(bad, `${what} is not of the form aerekms:v<version>:<base64>`);
const verPrefix = Number(m[1]);
const body = Buffer.from(m[2], 'base64');
if (body.toString('base64') !== m[2]) throw new KmsError(bad, `${what} uses non-canonical base64`);
const magic = kind === KIND_E ? MAGIC_E : MAGIC_S;
if (body.length < 17 || !body.subarray(0, 4).equals(magic) || body[4] !== kind) {
throw new KmsError(bad, `${what} does not carry the expected ${kind === KIND_E ? 'AKM1/E' : 'AKS1/S'} header`);
}
const verBody = body.readUInt32BE(OFF.ver);
if (verBody !== verPrefix) {
throw new KmsError('VERSION_MISMATCH', `the version in the prefix (v${verPrefix}) does not match the version inside the ${what} (v${verBody})`, { version: verPrefix });
}
return { ver: verBody, body, fp: body.subarray(OFF.fp, OFF.fp + SZ.fp) };
}
function describe(key) {
const versions = {};
for (const v of Object.keys(key.versions)) {
const r = key.versions[v];
versions[v] = { created: r.created, fingerprint: r.fingerprint, public: { ...r.public } };
}
return {
name: key.name,
type: key.type,
created: key.created,
policy: { ...key.policy },
min_decryption_version: key.min_decryption_version,
latest_version: key.latest_version,
versions,
};
}
const VERIFY_REFUSALS = new Set(['MALFORMED_SIGNATURE', 'VERSION_MISMATCH', 'UNKNOWN_VERSION', 'VERSION_BELOW_MINIMUM', 'KEY_MISMATCH']);
// ---------------------------------------------------------------------------------------------
export function openKms(opts) {
return new Kms(opts);
}
export class Kms {
#dir;
#keysDir;
#auditPath;
#sealKey;
#fileKey;
#auditKey;
#head;
#keys = new Map();
#priv = new Map();
#pub = new Map();
#closed = false;
constructor({ dataDir, rootKey } = {}) {
// Intai cheia radacina: fara ea nu se atinge discul deloc.
const root = parseRootKey(rootKey);
if (typeof dataDir !== 'string' || dataDir === '') {
root.fill(0);
throw new KmsError('DATA_DIR_MISSING', 'dataDir is required');
}
const sub = (label) => hkdf(root, utf8(LABELS.root), utf8(label), 32);
this.#sealKey = sub(LABELS.seal);
this.#fileKey = sub(LABELS.fileMac);
this.#auditKey = sub(LABELS.audit);
const checkKey = sub(LABELS.rootCheck);
root.fill(0);
this.#dir = path.resolve(dataDir);
this.#keysDir = path.join(this.#dir, 'keys');
this.#auditPath = path.join(this.#dir, 'audit.log');
fs.mkdirSync(this.#keysDir, { recursive: true, mode: 0o700 });
this.#checkRoot(checkKey);
const v = this.verifyAudit();
if (!v.ok) {
throw new KmsError('AUDIT_CHAIN_INVALID', `the audit log failed verification at line ${v.line} (${v.reason}); refusing to start. Move audit.log aside (keep it as evidence) to start a new chain.`);
}
this.#head = { seq: v.head.seq, mac: v.head.mac };
}
get dataDir() {
return this.#dir;
}
close() {
this.#closed = true;
this.#priv.clear();
this.#keys.clear();
this.#pub.clear();
}
// ----------------------------------------------------------------------- radacina si fisiere
#checkRoot(checkKey) {
const p = path.join(this.#dir, 'root-check.json');
const expected = hmac(checkKey, utf8('aerekms root key check')).toString('hex');
checkKey.fill(0);
if (fs.existsSync(p)) {
let rec;
try {
rec = JSON.parse(fs.readFileSync(p, 'utf8'));
} catch {
throw new KmsError('ROOT_CHECK_UNREADABLE', 'root-check.json is not valid JSON; refusing to start');
}
if (!rec || typeof rec.check !== 'string' || !ctEq(utf8(rec.check), utf8(expected))) {
throw new KmsError('ROOT_KEY_MISMATCH', 'AERE_KMS_ROOT_KEY does not match the key this data directory was created with; refusing to start');
}
return;
}
const existing = fs.readdirSync(this.#keysDir).filter((f) => f.endsWith('.json'));
if (existing.length > 0 || fs.existsSync(this.#auditPath)) {
throw new KmsError('ROOT_CHECK_MISSING', 'the data directory has keys or an audit log but no root-check.json; refusing to start');
}
writeFileAtomic(p, JSON.stringify({ format: 'aerekms-root-check/1', check: expected }) + '\n');
}
#keyPath(name) {
return path.join(this.#keysDir, `${name}.json`);
}
#fileMac(obj) {
return hmac(this.#fileKey, utf8(canonicalJson(obj))).toString('hex');
}
#load(name, wantType) {
checkName(name);
let key = this.#keys.get(name);
if (!key) {
const p = this.#keyPath(name);
if (!fs.existsSync(p)) throw new KmsError('KEY_NOT_FOUND', `key "${name}" does not exist`);
let rec;
try {
rec = JSON.parse(fs.readFileSync(p, 'utf8'));
} catch {
throw new KmsError('KEY_FILE_TAMPERED', `the key file for "${name}" is not valid JSON`);
}
const { mac, ...rest } = rec || {};
const macOk = typeof mac === 'string' && ctEq(utf8(mac), utf8(this.#fileMac(rest)));
if (!macOk) throw new KmsError('KEY_FILE_TAMPERED', `the key file for "${name}" failed its integrity check`);
if (rest.name !== name || rest.format !== KEY_FORMAT) {
throw new KmsError('KEY_FILE_TAMPERED', `the key file for "${name}" belongs to another key or format`);
}
key = rest;
this.#keys.set(name, key);
}
if (wantType && key.type !== wantType) {
throw new KmsError('WRONG_KEY_TYPE', `key "${name}" is a ${key.type} key; this operation needs a ${wantType} key`);
}
return key;
}
#save(key) {
const rec = { ...key, mac: this.#fileMac(key) };
writeFileAtomic(this.#keyPath(key.name), JSON.stringify(rec, null, 2) + '\n');
this.#keys.set(key.name, key);
}
// ----------------------------------------------------------------------- sigilarea privatelor
#seal(plain, aad) {
const iv = crypto.randomBytes(12);
const c = crypto.createCipheriv('aes-256-gcm', this.#sealKey, iv);
c.setAAD(aad);
const ct = Buffer.concat([c.update(plain), c.final()]);
plain.fill(0);
return Buffer.concat([iv, ct, c.getAuthTag()]).toString('base64');
}
#unseal(sealed, aad) {
try {
const b = Buffer.from(sealed, 'base64');
const d = crypto.createDecipheriv('aes-256-gcm', this.#sealKey, b.subarray(0, 12));
d.setAAD(aad);
d.setAuthTag(b.subarray(b.length - 16));
return Buffer.concat([d.update(b.subarray(12, b.length - 16)), d.final()]);
} catch {
throw new KmsError('SEAL_AUTH_FAILED', 'a stored private key could not be unsealed (wrong root key or modified key file)');
}
}
#newVersion(key) {
const ver = key.latest_version + 1;
let kind, pubA, pubB, derA, derB, pub;
if (key.type === 'encrypt') {
kind = KIND_E;
const a = crypto.generateKeyPairSync('x25519');
const b = crypto.generateKeyPairSync('ml-kem-768');
const spki = b.publicKey.export({ format: 'der', type: 'spki' });
pubA = rawOkp(a.publicKey);
pubB = rawFromSpki(spki, 'ml-kem-768');
pub = { x25519: pubA.toString('base64'), ml_kem_768: spki.toString('base64') };
derA = a.privateKey.export({ format: 'der', type: 'pkcs8' });
derB = b.privateKey.export({ format: 'der', type: 'pkcs8' });
} else {
kind = KIND_S;
const a = crypto.generateKeyPairSync('ed25519');
const b = crypto.generateKeyPairSync('ml-dsa-65');
const spki = b.publicKey.export({ format: 'der', type: 'spki' });
pubA = rawOkp(a.publicKey);
pubB = rawFromSpki(spki, 'ml-dsa-65');
pub = { ed25519: pubA.toString('base64'), ml_dsa_65: spki.toString('base64') };
derA = a.privateKey.export({ format: 'der', type: 'pkcs8' });
derB = b.privateKey.export({ format: 'der', type: 'pkcs8' });
}
const fp = fingerprint(kind, key.name, ver, pubA, pubB);
const fpHex = fp.toString('hex');
const privJson = JSON.stringify({ a: derA.toString('base64'), b: derB.toString('base64') });
const sealed = this.#seal(utf8(privJson), sealAad(key.name, key.type, ver, fpHex));
derA.fill(0);
derB.fill(0);
key.versions[String(ver)] = {
created: new Date().toISOString(),
fingerprint: fpHex,
public: pub,
private_sealed: sealed,
};
key.latest_version = ver;
return ver;
}
#privateKeys(key, ver) {
const id = `${key.name}:${ver}`;
const cached = this.#priv.get(id);
if (cached) return cached;
const v = key.versions[String(ver)];
const plain = this.#unseal(v.private_sealed, sealAad(key.name, key.type, ver, v.fingerprint));
let obj;
try {
obj = JSON.parse(plain.toString('utf8'));
} catch {
throw new KmsError('SEAL_AUTH_FAILED', 'a stored private key has an unexpected form');
} finally {
plain.fill(0);
}
const derA = Buffer.from(obj.a, 'base64');
const derB = Buffer.from(obj.b, 'base64');
let k;
try {
k = {
a: crypto.createPrivateKey({ key: derA, format: 'der', type: 'pkcs8' }),
b: crypto.createPrivateKey({ key: derB, format: 'der', type: 'pkcs8' }),
};
} catch {
throw new KmsError('SEAL_AUTH_FAILED', 'a stored private key could not be imported');
} finally {
derA.fill(0);
derB.fill(0);
}
const want = key.type === 'encrypt' ? ['x25519', 'ml-kem-768'] : ['ed25519', 'ml-dsa-65'];
if (k.a.asymmetricKeyType !== want[0] || k.b.asymmetricKeyType !== want[1]) {
throw new KmsError('SEAL_AUTH_FAILED', 'a stored private key has the wrong algorithm');
}
this.#priv.set(id, k);
return k;
}
#publicKeys(key, ver) {
const id = `${key.name}:${ver}`;
const cached = this.#pub.get(id);
if (cached) return cached;
const v = key.versions[String(ver)];
let r;
if (key.type === 'encrypt') {
const rawA = Buffer.from(v.public.x25519, 'base64');
const spki = Buffer.from(v.public.ml_kem_768, 'base64');
r = { rawA, rawB: rawFromSpki(spki, 'ml-kem-768'), a: okpPublic(rawA, 'X25519'), b: crypto.createPublicKey({ key: spki, format: 'der', type: 'spki' }) };
} else {
const rawA = Buffer.from(v.public.ed25519, 'base64');
const spki = Buffer.from(v.public.ml_dsa_65, 'base64');
r = { rawA, rawB: rawFromSpki(spki, 'ml-dsa-65'), a: okpPublic(rawA, 'Ed25519'), b: crypto.createPublicKey({ key: spki, format: 'der', type: 'spki' }) };
}
r.fp = Buffer.from(v.fingerprint, 'hex');
this.#pub.set(id, r);
return r;
}
// ----------------------------------------------------------------------- versiuni
#checkVersion(key, ver) {
if (!Object.hasOwn(key.versions, String(ver))) {
throw new KmsError('UNKNOWN_VERSION', `key "${key.name}" has no version ${ver}`, { version: ver });
}
if (ver < key.min_decryption_version) throw new KmsError('VERSION_BELOW_MINIMUM', `version ${ver} of key "${key.name}" is below min_decryption_version ${key.min_decryption_version}`, { version: ver });
}
#checkFingerprint(key, ver, fp, what) {
const fpExpected = Buffer.from(key.versions[String(ver)].fingerprint, 'hex');
if (!fp.equals(fpExpected)) {
const other = Object.keys(key.versions).find((v) => Buffer.from(key.versions[v].fingerprint, 'hex').equals(fp));
if (other !== undefined) {
throw new KmsError('VERSION_MISMATCH', `the ${what} was produced by version ${other} of key "${key.name}", not by version ${ver}`, { version: ver });
}
throw new KmsError('KEY_MISMATCH', `the ${what} was not produced by key "${key.name}"`, { version: ver });
}
}
// ----------------------------------------------------------------------- plicul
#encryptWith(key, pt, aad) {
const ver = key.latest_version;
const pk = this.#publicKeys(key, ver);
const eph = crypto.generateKeyPairSync('x25519');
const ePub = rawOkp(eph.publicKey);
const ssX = crypto.diffieHellman({ privateKey: eph.privateKey, publicKey: pk.a });
const { sharedKey: ssK, ciphertext: ctK } = crypto.encapsulate(pk.b);
const d = deriveKeys(ssK, ssX, kemTranscript(key.name, ver, pk.fp, pk.rawA, pk.rawB, ePub, ctK), aad);
ssX.fill(0);
ssK.fill(0);
const pre = Buffer.concat([MAGIC_E, Buffer.from([KIND_E]), u32(ver), pk.fp, ePub, ctK, d.aadTag]);
const commit = hmac(d.commitKey, pre).subarray(0, 16);
const hdr = Buffer.concat([pre, commit]);
const c = crypto.createCipheriv('aes-256-gcm', d.key, d.iv);
c.setAAD(hdr);
const ct = Buffer.concat([c.update(pt), c.final()]);
const body = Buffer.concat([hdr, ct, c.getAuthTag()]);
d.dek.fill(0);
return { ciphertext: `${PREFIX}:v${ver}:${body.toString('base64')}`, version: ver };
}
#decryptWith(key, ctStr, aad) {
const { ver, body, fp } = parseEnvelope(ctStr, KIND_E);
try {
if (body.length < ENV_MIN) throw new KmsError('MALFORMED_CIPHERTEXT', 'ciphertext is too short');
this.#checkVersion(key, ver);
this.#checkFingerprint(key, ver, fp, 'ciphertext');
const pk = this.#publicKeys(key, ver);
const sk = this.#privateKeys(key, ver);
const ePub = body.subarray(OFF.ePub, OFF.ePub + SZ.x);
const ctK = body.subarray(OFF.ctK, OFF.ctK + SZ.ctK);
const aadTag = body.subarray(OFF.aadTag, OFF.aadTag + 16);
const commit = body.subarray(OFF.commit, OFF.commit + 16);
let ssX, ssK;
try {
ssX = crypto.diffieHellman({ privateKey: sk.a, publicKey: okpPublic(ePub, 'X25519') });
ssK = crypto.decapsulate(sk.b, ctK);
} catch {
throw new KmsError('HEADER_AUTH_FAILED', 'the ciphertext header or key encapsulation was modified, or it was not produced for this key version');
}
const d = deriveKeys(ssK, ssX, kemTranscript(key.name, ver, pk.fp, pk.rawA, pk.rawB, ePub, ctK), aad);
ssX.fill(0);
ssK.fill(0);
try {
if (!ctEq(hmac(d.commitKey, body.subarray(0, OFF.commit)).subarray(0, 16), commit)) {
throw new KmsError('HEADER_AUTH_FAILED', 'the ciphertext header or key encapsulation was modified, or it was not produced for this key version');
}
if (!ctEq(d.aadTag, aadTag)) {
throw new KmsError('AAD_MISMATCH', 'the additional authenticated data (aad) does not match the one used at encryption');
}
let plaintext;
try {
const dc = crypto.createDecipheriv('aes-256-gcm', d.key, d.iv);
dc.setAAD(body.subarray(0, OFF.payload));
dc.setAuthTag(body.subarray(body.length - 16));
plaintext = Buffer.concat([dc.update(body.subarray(OFF.payload, body.length - 16)), dc.final()]);
} catch {
throw new KmsError('PAYLOAD_AUTH_FAILED', 'the encrypted payload or its authentication tag was modified');
}
return { plaintext, version: ver };
} finally {
d.dek.fill(0);
}
} catch (e) {
if (e instanceof KmsError && e.version === undefined) e.version = ver;
throw e;
}
}
#verifyWith(key, msg, signature) {
const { ver, body, fp } = parseEnvelope(signature, KIND_S);
if (body.length !== SIG_LEN) throw new KmsError('MALFORMED_SIGNATURE', `signature must be exactly ${SIG_LEN} bytes after base64 decoding`, { version: ver });
this.#checkVersion(key, ver);
this.#checkFingerprint(key, ver, fp, 'signature');
const pk = this.#publicKeys(key, ver);
const m = sigMessage(pk.fp, ver, msg);
const edSig = body.subarray(17, 17 + SZ.ed);
const mlSig = body.subarray(17 + SZ.ed);
const safe = (f) => {
try {
return f() === true;
} catch {
return false;
}
};
const edOk = safe(() => crypto.verify(null, m, pk.a, edSig));
const pqOk = safe(() => crypto.verify(null, m, { key: pk.b, context: utf8(LABELS.sigCtx) }, mlSig));
const valid = edOk && pqOk;
let reason = null;
if (!edOk && !pqOk) reason = 'BOTH_SIGNATURES_INVALID';
else if (!edOk) reason = 'CLASSICAL_SIGNATURE_INVALID';
else if (!pqOk) reason = 'PQ_SIGNATURE_INVALID';
return { valid, reason, version: ver, classical: edOk, post_quantum: pqOk };
}
// ----------------------------------------------------------------------- jurnalul de audit
#audit(e) {
const row = {
seq: this.#head.seq + 1,
ts: new Date().toISOString(),
op: e.op,
key: e.key ?? null,
version: e.version ?? null,
ok: e.ok === true,
reason: e.reason ?? null,
prev: this.#head.mac,
};
row.mac = hmac(this.#auditKey, utf8(canonicalJson(row))).toString('hex');
try {
const fd = fs.openSync(this.#auditPath, 'a', 0o600);
try {
fs.writeSync(fd, JSON.stringify(row) + '\n');
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
} catch {
throw new KmsError('AUDIT_WRITE_FAILED', 'the audit log could not be written; the result of the operation is withheld');
}
this.#head = { seq: row.seq, mac: row.mac };
}
// Ruleaza o operatie si scrie randul ei de audit. fn intoarce { value, version, ok?, reason? }.
// Rezultatul nu iese din functie decat dupa ce randul de audit e scris.
#run(op, name, fn) {
if (this.#closed) throw new KmsError('KMS_CLOSED', 'this KMS instance was closed');
const keyName = typeof name === 'string' && NAME_RE.test(name) ? name : null;
// A4 (revizuirea din 2026-09-25): o MUTATIE (creare, rotire, minim de versiune) ramanea pe disc cand randul de audit nu se
// putea scrie, iar lantul de audit ramanea valid fara nicio urma a ei. Regula e "o schimbare sta numai daca randul ei sta":
// starea fisierului cheii se retine INAINTE de operatie si se pune la loc daca randul nu se poate scrie.
const keyFile = keyName ? this.#keyPath(keyName) : null;
const before = keyFile && fs.existsSync(keyFile) ? fs.readFileSync(keyFile) : null;
const rollback = () => {
if (!keyFile) return;
const after = fs.existsSync(keyFile) ? fs.readFileSync(keyFile) : null;
const changed = (before === null) !== (after === null) || (before !== null && after !== null && !before.equals(after));
if (!changed) return;
if (before === null) fs.rmSync(keyFile, { force: true });
else writeFileAtomic(keyFile, before);
this.#keys.delete(keyName);
};
let r;
try {
r = fn();
} catch (e0) {
let e = e0;
if (!(e instanceof KmsError)) {
e = new KmsError('INTERNAL', 'internal error');
Object.defineProperty(e, 'cause', { value: e0, enumerable: false });
}
try {
this.#audit({ op, key: keyName, version: e.version ?? null, ok: false, reason: e.code });
} catch (ea) {
rollback();
throw ea;
}
throw e;
}
try {
this.#audit({ op, key: keyName, version: r.version ?? null, ok: r.ok ?? true, reason: r.reason ?? null });
} catch (ea) {
rollback();
throw ea;
}
return r.value;
}
auditHead() {
return { seq: this.#head.seq, mac: this.#head.mac };
}
// Verifica tot jurnalul: fiecare rand trebuie sa aiba mac-ul corect, numarul de ordine urmator
// si mac-ul randului anterior. expectedHead = un cap {seq, mac} tinut in afara (prinde taierea
// cozii, pe care un lant singur nu o poate vedea).
verifyAudit({ expectedHead } = {}) {
const fail = (reason, line, extra) => ({ ok: false, reason, line, ...extra });
let lines = [];
if (fs.existsSync(this.#auditPath)) {
const text = fs.readFileSync(this.#auditPath, 'utf8');
if (text !== '') {
lines = text.split('\n');
if (lines[lines.length - 1] === '') lines.pop();
else return fail('AUDIT_ROW_UNPARSABLE', lines.length);
}
}
let prev = ZERO_MAC;
let seq = -1;
for (let i = 0; i < lines.length; i++) {
let row;
try {
row = JSON.parse(lines[i]);
} catch {
return fail('AUDIT_ROW_UNPARSABLE', i + 1);
}
if (!row || typeof row !== 'object' || Array.isArray(row)) return fail('AUDIT_ROW_UNPARSABLE', i + 1);
const { mac, ...rest } = row;
const macOk = typeof mac === 'string' && ctEq(utf8(mac), utf8(hmac(this.#auditKey, utf8(canonicalJson(rest))).toString('hex')));
if (!macOk) return fail('AUDIT_ROW_MODIFIED', i + 1);
if (row.seq !== seq + 1 || row.prev !== prev) return fail('AUDIT_CHAIN_BROKEN', i + 1);
prev = mac;
seq = row.seq;
}
const head = { seq, mac: prev };
if (expectedHead) {
if (seq < expectedHead.seq) return fail('AUDIT_TRUNCATED', lines.length, { head });
const row = JSON.parse(lines[expectedHead.seq]);
if (row.mac !== expectedHead.mac) return fail('AUDIT_HEAD_MISMATCH', expectedHead.seq + 1, { head });
}
return { ok: true, rows: lines.length, head };
}
// ----------------------------------------------------------------------- cheile
createKey(name, { type, exportable = false } = {}) {
return this.#run('create_key', name, () => {
checkName(name);
if (type !== 'encrypt' && type !== 'sign') throw new KmsError('INVALID_KEY_TYPE', 'type must be "encrypt" or "sign"');
if (typeof exportable !== 'boolean') throw new KmsError('INVALID_POLICY', 'exportable must be a boolean');
if (this.#keys.has(name) || fs.existsSync(this.#keyPath(name))) throw new KmsError('KEY_EXISTS', `key "${name}" already exists`);
const key = {
format: KEY_FORMAT,
name,
type,
created: new Date().toISOString(),
policy: { exportable },
min_decryption_version: 1,
latest_version: 0,
versions: {},
};
const ver = this.#newVersion(key);
this.#save(key);
return { value: describe(key), version: ver };
});
}
getKey(name) {
return this.#run('read_key', name, () => {
const key = this.#load(name);
return { value: describe(key), version: key.latest_version };
});
}
listKeys() {
return this.#run('list_keys', null, () => {
const names = fs.readdirSync(this.#keysDir)
.filter((f) => f.endsWith('.json'))
.map((f) => f.slice(0, -5))
.filter((n) => NAME_RE.test(n))
.sort();
return { value: names };
});
}
rotate(name) {
return this.#run('rotate', name, () => {
const key = structuredClone(this.#load(name));
const ver = this.#newVersion(key);
this.#save(key);
return { value: describe(key), version: ver };
});
}
// Minimul se poate numai RIDICA: o versiune retrasa nu mai decripteaza si nu mai verifica.
setMinDecryptionVersion(name, minVersion) {
return this.#run('config', name, () => {
const key = structuredClone(this.#load(name));
if (!Number.isSafeInteger(minVersion) || minVersion < 1 || minVersion > key.latest_version) {
throw new KmsError('VERSION_OUT_OF_RANGE', `min_decryption_version must be an integer between 1 and ${key.latest_version}`);
}
if (minVersion < key.min_decryption_version) {
throw new KmsError('MIN_VERSION_NOT_MONOTONIC', `min_decryption_version can only be raised (current: ${key.min_decryption_version})`);
}
key.min_decryption_version = minVersion;
this.#save(key);
return { value: describe(key), version: minVersion };
});
}
exportKey(name, version) {
return this.#run('export', name, () => {
const key = this.#load(name);
if (key.policy.exportable !== true) throw new KmsError('KEY_NOT_EXPORTABLE', `key "${name}" was not created as exportable`);
const ver = version === undefined || version === null ? key.latest_version : version;
if (!Number.isSafeInteger(ver) || !Object.hasOwn(key.versions, String(ver))) {
throw new KmsError('UNKNOWN_VERSION', `key "${name}" has no version ${ver}`);
}
const sk = this.#privateKeys(key, ver);
const der = (k) => k.export({ format: 'der', type: 'pkcs8' }).toString('base64');
const priv = key.type === 'encrypt'
? { x25519_pkcs8: der(sk.a), ml_kem_768_pkcs8: der(sk.b) }
: { ed25519_pkcs8: der(sk.a), ml_dsa_65_pkcs8: der(sk.b) };
return {
value: { name, type: key.type, version: ver, fingerprint: key.versions[String(ver)].fingerprint, private: priv },
version: ver,
};
});
}
// ----------------------------------------------------------------------- operatiile transit
encrypt(name, plaintext, aad) {
return this.#run('encrypt', name, () => {
const key = this.#load(name, 'encrypt');
const pt = toBytes(plaintext, 'plaintext', MAX_PLAINTEXT);
const r = this.#encryptWith(key, pt, normAad(aad));
pt.fill(0);
return { value: r, version: r.version };
});
}
decrypt(name, ciphertext, aad) {
return this.#run('decrypt', name, () => {
const key = this.#load(name, 'encrypt');
const r = this.#decryptWith(key, ciphertext, normAad(aad));
return { value: r, version: r.version };
});
}
// Reincapsuleaza la ultima versiune. Textul clar nu iese din proces: raspunsul are numai
// textul cifrat nou.
rewrap(name, ciphertext, aad) {
return this.#run('rewrap', name, () => {
const key = this.#load(name, 'encrypt');
const aadB = normAad(aad);
const { plaintext } = this.#decryptWith(key, ciphertext, aadB);
try {
const r = this.#encryptWith(key, plaintext, aadB);
return { value: { ciphertext: r.ciphertext, version: r.version }, version: r.version };
} finally {
plaintext.fill(0);
}
});
}
datakey(name, { aad, bits = 256, includePlaintext = true } = {}) {
return this.#run('datakey', name, () => {
const key = this.#load(name, 'encrypt');
if (![128, 256, 512].includes(bits)) throw new KmsError('INVALID_BITS', 'bits must be 128, 256 or 512');
if (typeof includePlaintext !== 'boolean') throw new KmsError('INVALID_INPUT', 'includePlaintext must be a boolean');
const dk = crypto.randomBytes(bits / 8);
try {
const r = this.#encryptWith(key, dk, normAad(aad));
const value = { ciphertext: r.ciphertext, version: r.version };
if (includePlaintext) value.plaintext = dk.toString('base64');
return { value, version: r.version };
} finally {
dk.fill(0);
}
});
}
sign(name, message) {
return this.#run('sign', name, () => {
const key = this.#load(name, 'sign');
const msg = toBytes(message, 'message', MAX_MESSAGE);
const ver = key.latest_version;
const pk = this.#publicKeys(key, ver);
const sk = this.#privateKeys(key, ver);
const m = sigMessage(pk.fp, ver, msg);
const edSig = crypto.sign(null, m, sk.a);
const mlSig = crypto.sign(null, m, { key: sk.b, context: utf8(LABELS.sigCtx) });
if (edSig.length !== SZ.ed || mlSig.length !== SZ.mlSig) throw new KmsError('INTERNAL', 'unexpected signature length');
const body = Buffer.concat([MAGIC_S, Buffer.from([KIND_S]), u32(ver), pk.fp, edSig, mlSig]);
return { value: { signature: `${PREFIX}:v${ver}:${body.toString('base64')}`, version: ver }, version: ver };
});
}
// Intoarce { valid, reason, version, classical, post_quantum }. valid cere AMBELE semnaturi.
verify(name, message, signature) {
return this.#run('verify', name, () => {
const key = this.#load(name, 'sign');
const msg = toBytes(message, 'message', MAX_MESSAGE);
let r;
try {
r = this.#verifyWith(key, msg, signature);
} catch (e) {
if (e instanceof KmsError && VERIFY_REFUSALS.has(e.code)) {
r = { valid: false, reason: e.code, version: e.version ?? null, classical: false, post_quantum: false };
} else {
throw e;
}
}
return { value: r, version: r.version, ok: r.valid, reason: r.reason };
});
}
}
+333
View File
@@ -0,0 +1,333 @@
// server.mjs - serverul HTTP al Aere PQ KMS (node:http, fara dependinte).
//
// Mediu:
// AERE_KMS_ROOT_KEY 64 de caractere hexa (32 de octeti), SAU:
// AERE_KMS_ROOT_HSM calea radacinii SIGILATE de un HSM (hsm-radacina.mjs), deschisa la pornire cu PIN-ul din AERE_HSM_PIN;
// exact una din cele doua; fara niciuna refuza pornirea, cu amandoua refuza (ROOT_KEY_AMBIGUOUS)
// AERE_KMS_TOKEN obligatoriu, cel putin 32 de caractere; se cere ca "Authorization: Bearer <token>"
// AERE_KMS_HOST implicit 127.0.0.1
// AERE_KMS_PORT implicit 8420
// AERE_KMS_MAX_BODY implicit 65536 (octeti)
// AERE_KMS_DATA_DIR implicit ./data langa acest fisier
//
// Nicio valoare din mediu nu se tipareste. Raspunsurile de eroare sunt { error: COD, message }.
import http from 'node:http';
import crypto from 'node:crypto';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { openKms, parseRootKey, KmsError } from './kms.mjs';
import { radacinaDinHsm } from './hsm-radacina.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const STATUS = {
NOT_FOUND: 404,
KEY_NOT_FOUND: 404,
METHOD_NOT_ALLOWED: 405,
KEY_EXISTS: 409,
KEY_NOT_EXPORTABLE: 403,
UNAUTHENTICATED: 401,
INVALID_TOKEN: 401,
BODY_TOO_LARGE: 413,
UNSUPPORTED_MEDIA_TYPE: 415,
INTERNAL: 500,
AUDIT_WRITE_FAILED: 500,
SEAL_AUTH_FAILED: 500,
KEY_FILE_TAMPERED: 500,
KMS_CLOSED: 503,
};
class HttpError extends Error {
constructor(status, code, message) {
super(message);
this.status = status;
this.code = code;
}
}
export function configFromEnv(env, optiuniHsm = {}) {
const token = String(env.AERE_KMS_TOKEN ?? '').trim();
if (token === '') throw new KmsError('TOKEN_MISSING', 'AERE_KMS_TOKEN is not set; refusing to start');
if (token.length < 32) throw new KmsError('TOKEN_TOO_SHORT', `AERE_KMS_TOKEN must be at least 32 characters; the value given has ${token.length}`);
if (!/^[\x21-\x7e]+$/.test(token)) throw new KmsError('TOKEN_INVALID', 'AERE_KMS_TOKEN must be printable ASCII without spaces');
// Validam cheia radacina aici, ca serverul sa nu porneasca deloc fara ea. Din 2026-09-28 poate veni si SIGILATA de un HSM.
const inClar = String(env.AERE_KMS_ROOT_KEY ?? '').trim() !== '', dinHsm = String(env.AERE_KMS_ROOT_HSM ?? '').trim() !== '';
if (inClar && dinHsm) throw new KmsError('ROOT_KEY_AMBIGUOUS', 'set AERE_KMS_ROOT_KEY or AERE_KMS_ROOT_HSM, not both');
const rootHex = dinHsm ? radacinaDinHsm(env, optiuniHsm) : env.AERE_KMS_ROOT_KEY;
const root = parseRootKey(rootHex);
const sameAsRoot = token.toLowerCase() === root.toString('hex');
root.fill(0);
if (sameAsRoot) throw new KmsError('TOKEN_EQUALS_ROOT_KEY', 'AERE_KMS_TOKEN must not be the root key');
const host = String(env.AERE_KMS_HOST ?? '').trim() || '127.0.0.1';
const portRaw = String(env.AERE_KMS_PORT ?? '').trim() || '8420';
const port = Number(portRaw);
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new KmsError('INVALID_PORT', 'AERE_KMS_PORT must be an integer between 0 and 65535');
const maxRaw = String(env.AERE_KMS_MAX_BODY ?? '').trim() || '65536';
const maxBody = Number(maxRaw);
// Sub 8192 nu incape nici o cerere de verificare (semnatura hibrida are 4531 de caractere base64).
if (!Number.isInteger(maxBody) || maxBody < 8192 || maxBody > 16 * 1024 * 1024) {
throw new KmsError('INVALID_MAX_BODY', 'AERE_KMS_MAX_BODY must be an integer between 8192 and 16777216');
}
const dataDir = String(env.AERE_KMS_DATA_DIR ?? '').trim() || path.join(HERE, 'data');
return { token, rootKey: rootHex, rootSource: dinHsm ? 'hsm' : 'env', host, port, maxBody, dataDir };
}
function tooBig(n, maxBody) {
return n > maxBody;
}
function authCheck(req, tokenHash) {
const header = req.headers['authorization'];
if (typeof header !== 'string' || header === '') return 'UNAUTHENTICATED';
const m = /^Bearer ([\x21-\x7e]+)$/.exec(header);
if (!m) return 'INVALID_TOKEN';
const got = crypto.createHash('sha256').update(m[1], 'utf8').digest();
if (!crypto.timingSafeEqual(got, tokenHash)) return 'INVALID_TOKEN';
return null;
}
// Arunca restul corpului fara sa-l tina in memorie; peste plafon inchide conexiunea.
function discard(req, cap) {
let n = 0;
req.on('data', (c) => {
n += c.length;
if (n > cap) req.destroy();
});
req.on('error', () => {});
req.resume();
}
function readBody(req, maxBody) {
return new Promise((resolve, reject) => {
const declared = req.headers['content-length'];
if (declared !== undefined) {
const n = Number(declared);
if (!Number.isSafeInteger(n) || n < 0) return reject(new HttpError(400, 'INVALID_CONTENT_LENGTH', 'invalid Content-Length'));
if (tooBig(n, maxBody)) return reject(new HttpError(413, 'BODY_TOO_LARGE', `request body is larger than ${maxBody} bytes`));
}
const chunks = [];
let size = 0;
let done = false;
req.on('data', (c) => {
if (done) return;
size += c.length;
if (tooBig(size, maxBody)) {
done = true;
chunks.length = 0;
reject(new HttpError(413, 'BODY_TOO_LARGE', `request body is larger than ${maxBody} bytes`));
return;
}
chunks.push(c);
});
req.on('end', () => {
if (!done) {
done = true;
resolve(Buffer.concat(chunks));
}
});
req.on('error', () => {
if (!done) {
done = true;
reject(new HttpError(400, 'BAD_REQUEST', 'the request body could not be read'));
}
});
});
}
function send(res, status, obj, close = false) {
const body = JSON.stringify(obj);
const headers = {
'content-type': 'application/json; charset=utf-8',
'content-length': Buffer.byteLength(body),
'cache-control': 'no-store',
'x-content-type-options': 'nosniff',
};
if (close) headers.connection = 'close';
res.writeHead(status, headers);
res.end(body);
}
function b64Field(obj, field, { optional = false } = {}) {
const v = obj[field];
if (v === undefined || v === null) {
if (optional) return undefined;
throw new HttpError(400, 'MISSING_FIELD', `field "${field}" is required`);
}
if (typeof v !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(v) || v.length % 4 !== 0) {
throw new HttpError(400, 'INVALID_BASE64', `field "${field}" must be standard base64`);
}
const b = Buffer.from(v, 'base64');
if (b.toString('base64') !== v) throw new HttpError(400, 'INVALID_BASE64', `field "${field}" must be canonical base64`);
return b;
}
function strField(obj, field) {
const v = obj[field];
if (typeof v !== 'string') throw new HttpError(400, 'MISSING_FIELD', `field "${field}" is required and must be a string`);
return v;
}
export function createServer({ kms, token, maxBody = 65536 }) {
if (typeof token !== 'string' || token.length < 32) throw new KmsError('TOKEN_TOO_SHORT', 'token must be at least 32 characters');
const tokenHash = crypto.createHash('sha256').update(token, 'utf8').digest();
const drainCap = maxBody * 4 + 1024 * 1024;
async function handle(req, res) {
let url;
try {
url = new URL(req.url, 'http://localhost');
} catch {
discard(req, drainCap);
return send(res, 400, { error: 'BAD_REQUEST', message: 'invalid request URL' }, true);
}
const method = req.method;
const parts = url.pathname.split('/').filter((p) => p !== '');
if (method === 'GET' && url.pathname === '/v1/health') {
discard(req, drainCap);
return send(res, 200, { ok: true });
}
// Autentificarea se face INAINTE de a citi corpul.
const authErr = authCheck(req, tokenHash);
if (authErr) {
discard(req, drainCap);
return send(res, 401, { error: authErr, message: authErr === 'UNAUTHENTICATED' ? 'missing bearer token' : 'invalid bearer token' }, true);
}
let body = null;
if (method === 'POST') {
const ctype = String(req.headers['content-type'] ?? '');
let raw;
try {
raw = await readBody(req, maxBody);
} catch (e) {
discard(req, drainCap);
throw e;
}
if (raw.length > 0 && ctype !== '' && !/^application\/json\b/i.test(ctype)) {
throw new HttpError(415, 'UNSUPPORTED_MEDIA_TYPE', 'request body must be application/json');
}
if (raw.length === 0) body = {};
else {
try {
body = JSON.parse(raw.toString('utf8'));
} catch {
throw new HttpError(400, 'INVALID_JSON', 'request body is not valid JSON');
}
}
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new HttpError(400, 'INVALID_JSON', 'request body must be a JSON object');
} else {
discard(req, drainCap);
}
const name = parts[2] !== undefined ? decodeURIComponent(parts[2]) : undefined;
if (parts[0] !== 'v1') throw new HttpError(404, 'NOT_FOUND', 'no such route');
// /v1/keys
if (parts[1] === 'keys') {
if (parts.length === 2 && method === 'GET') return send(res, 200, { keys: kms.listKeys() });
if (parts.length === 3 && method === 'POST') {
const exportable = body.exportable === undefined ? false : body.exportable;
return send(res, 200, kms.createKey(name, { type: body.type, exportable }));
}
if (parts.length === 3 && method === 'GET') return send(res, 200, kms.getKey(name));
if (parts.length === 4 && parts[3] === 'rotate' && method === 'POST') return send(res, 200, kms.rotate(name));
if (parts.length === 4 && parts[3] === 'config' && method === 'POST') {
return send(res, 200, kms.setMinDecryptionVersion(name, body.min_decryption_version));
}
if ((parts.length === 4 || parts.length === 5) && parts[3] === 'export' && method === 'GET') {
let ver;
if (parts.length === 5) {
if (!/^[1-9][0-9]{0,8}$/.test(parts[4])) throw new HttpError(400, 'INVALID_VERSION', 'version must be a positive integer');
ver = Number(parts[4]);
}
return send(res, 200, kms.exportKey(name, ver));
}
}
if (parts.length === 3 && method === 'POST') {
switch (parts[1]) {
case 'encrypt': {
const r = kms.encrypt(name, b64Field(body, 'plaintext'), b64Field(body, 'aad', { optional: true }));
return send(res, 200, r);
}
case 'decrypt': {
const r = kms.decrypt(name, strField(body, 'ciphertext'), b64Field(body, 'aad', { optional: true }));
const out = { plaintext: r.plaintext.toString('base64'), version: r.version };
r.plaintext.fill(0);
return send(res, 200, out);
}
case 'rewrap':
return send(res, 200, kms.rewrap(name, strField(body, 'ciphertext'), b64Field(body, 'aad', { optional: true })));
case 'datakey': {
const includePlaintext = body.include_plaintext === undefined ? true : body.include_plaintext;
const bits = body.bits === undefined ? 256 : body.bits;
return send(res, 200, kms.datakey(name, { aad: b64Field(body, 'aad', { optional: true }), bits, includePlaintext }));
}
case 'sign':
return send(res, 200, kms.sign(name, b64Field(body, 'message')));
case 'verify':
return send(res, 200, kms.verify(name, b64Field(body, 'message'), strField(body, 'signature')));
default:
break;
}
}
if (parts.length === 3 && parts[1] === 'audit' && parts[2] === 'verify' && method === 'GET') {
return send(res, 200, kms.verifyAudit());
}
throw new HttpError(404, 'NOT_FOUND', 'no such route');
}
const server = http.createServer((req, res) => {
handle(req, res).catch((e) => {
if (res.headersSent) {
res.destroy();
return;
}
if (e instanceof HttpError) return send(res, e.status, { error: e.code, message: e.message }, e.status === 413);
if (e instanceof KmsError) return send(res, STATUS[e.code] ?? 400, { error: e.code, message: e.message });
if (e instanceof URIError) return send(res, 400, { error: 'BAD_REQUEST', message: 'invalid percent-encoding in path' });
return send(res, 500, { error: 'INTERNAL', message: 'internal error' });
});
});
server.headersTimeout = 10_000;
server.requestTimeout = 30_000;
return server;
}
async function main() {
let cfg;
let kms;
try {
cfg = configFromEnv(process.env);
kms = openKms({ dataDir: cfg.dataDir, rootKey: cfg.rootKey });
} catch (e) {
const code = e instanceof KmsError ? e.code : 'INTERNAL';
const msg = e instanceof KmsError ? e.message : 'internal error';
process.stderr.write(`aere-pq-kms: refusing to start: ${code}: ${msg}\n`);
process.exitCode = 1;
return;
}
const server = createServer({ kms, token: cfg.token, maxBody: cfg.maxBody });
server.on('error', (e) => {
process.stderr.write(`aere-pq-kms: server error: ${e.code ?? 'ERROR'}\n`);
process.exitCode = 1;
});
server.listen(cfg.port, cfg.host, () => {
const a = server.address();
process.stdout.write(`aere-pq-kms: listening on ${a.address}:${a.port}\n`);
});
const stop = () => {
server.close(() => kms.close());
};
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
}
if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
main();
}
@@ -0,0 +1,58 @@
// test/control-negativ-hsm-incredere.mjs (2026-09-29): controlul negativ al probei H1 (proba-hsm-incredere.mjs). Trei stari pe caz:
// PRINS (proba a rulat pana la capat si a iesit rosie pe verificarea numita), SCAPAT, STRICAT (copia nu s-a incarcat / proba nu a rulat).
// V0 modulul de DINAINTE de reparatie (HEAD-ul lui git la momentul scrierii: `git show <rev>:.../hsm-radacina.mjs`) -> rosu pe H1
// P1 verificarea bibliotecii scoasa cu o conditie falsa la rulare -> rosu pe biblioteca straina
// P2 verificarea variabilei PIN-ului scoasa cu o conditie falsa la rulare -> rosu pe jetonul API ca PIN
// Copiile stau LANGA original (./kms.mjs trebuie sa se rezolve) si se sterg la sfarsit; originalul trebuie sa ramana octet cu octet.
// node test/control-negativ-hsm-incredere.mjs -> 0 toate prinse, 1 unul scapa, 2 STRICAT
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const SRC = path.join(AICI, '..', 'hsm-radacina.mjs');
const PROBA = path.join(AICI, 'proba-hsm-incredere.mjs');
const sha = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
const inainte = sha(SRC);
const REV_VECHE = process.env.AERE_HSM_REV_VECHE || '7f2e7182';
let prinse = 0, stricate = 0, total = 0;
function caz(id, text, tinta) {
total++;
const copie = path.join(AICI, '..', `.plantat-hsm-${id}.mjs`);
try {
fs.writeFileSync(copie, text);
const r = spawnSync(process.execPath, [PROBA], { encoding: 'utf8', env: { ...process.env, AERE_HSM_MODUL_SUB_PROBA: copie } });
const out = (r.stdout || '') + (r.stderr || '');
if (!/increderea in fisierul sigilat \(H1\): \d+\/\d+/.test(out)) { stricate++; console.log(` STRICAT ${id}: proba nu a ajuns la capat (${out.trim().split('\n').pop().slice(0, 120)})`); return; }
if (!/\[OK \] CONTROL POZITIV/.test(out)) { stricate++; console.log(` STRICAT ${id}: controlul pozitiv al probei nu a trecut pe copie`); return; }
const rosii = out.split('\n').filter((l) => l.includes('[RAU ]'));
if (r.status === 1 && rosii.some((l) => l.includes(tinta))) { prinse++; console.log(` PRINS ${id}: ${rosii.length} verificari rosii, intre ele "${tinta}"`); }
else console.log(` SCAPAT ${id}: cod ${r.status}, "${tinta}" nu e rosie`);
} finally { fs.rmSync(copie, { force: true }); }
}
const inlocuieste = (t, a, b) => { if (t.split(a).length !== 2) return null; return t.replace(a, b); };
// V0: codul vechi, din git (octetii comisi, fara conversia autocrlf)
// In depozitul public (alt istoric) codul de dinainte nu exista: V0 se sare, spus, si nu se numara; in depozitul de lucru trebuie sa ruleze.
const CALE_VECHE = `${REV_VECHE}:cloud-gateway/pq-kms/hsm-radacina.mjs`;
const exista = spawnSync('git', ['cat-file', '-e', CALE_VECHE], { cwd: path.join(AICI, '..'), encoding: 'utf8' }).status === 0;
if (!exista) console.log(` SARIT V0: codul de dinainte de reparatie (${REV_VECHE}) nu e in istoricul acestui depozit; NEMASURAT aici`);
else {
const g = spawnSync('git', ['-c', 'core.autocrlf=false', 'show', CALE_VECHE], { cwd: path.join(AICI, '..'), encoding: 'utf8' });
if (g.status !== 0 || !g.stdout.includes('export function deschideRadacina')) { stricate++; total++; console.log(' STRICAT V0: nu citesc modulul vechi din git (' + REV_VECHE + ')'); }
else caz('V0', g.stdout, 'biblioteca din fisier, alta decat AERE_HSM_MODULE');
}
const nou = fs.readFileSync(SRC, 'utf8');
const p1 = inlocuieste(nou, "if (sig.modul !== permis) throw", "if (sig.modul !== permis && process.env.AERE_PLANTA_NICIODATA === 'da') throw");
if (!p1) { stricate++; total++; console.log(' STRICAT P1: ancora nu apare exact o data'); } else caz('P1', p1, 'biblioteca din fisier, alta decat AERE_HSM_MODULE');
const p2 = inlocuieste(nou, "if (sig.pinEnv !== undefined && sig.pinEnv !== PIN_ENV) throw", "if (sig.pinEnv !== undefined && sig.pinEnv !== PIN_ENV && process.env.AERE_PLANTA_NICIODATA === 'da') throw");
if (!p2) { stricate++; total++; console.log(' STRICAT P2: ancora nu apare exact o data'); } else caz('P2', p2, 'alta variabila drept PIN');
const ramase = fs.readdirSync(path.join(AICI, '..')).filter((f) => f.startsWith('.plantat-hsm-'));
if (sha(SRC) !== inainte || ramase.length) { stricate++; console.log(' STRICAT originalul s-a schimbat sau au ramas copii: ' + ramase.join(',')); }
console.log(`\ncontrolul negativ H1: prinse ${prinse}/${total}, stricate ${stricate}`);
process.exitCode = stricate ? 2 : prinse === total ? 0 : 1;
+423
View File
@@ -0,0 +1,423 @@
// test/control-negativ.mjs - controlul negativ al probei Aere PQ KMS.
//
// O proba care nu poate iesi rosie nu masoara nimic. Aici se planteaza, intr-o COPIE a codului,
// cate un defect real, si se cere ca proba sa iasa ROSIE pe exact probele numite, pentru
// MOTIVUL numit (un fragment din mesajul afirmatiei care a cazut), nu doar "ceva a picat".
//
// Reguli, platite in alte parti ale casei:
// - verdictul se citeste din JSON-ul probei (AERE_KMS_PROBA_JSON), nu din codul de iesire;
// o proba care nu a ajuns la capat sau a rulat alt numar de probe e STRICAT, nu ROSU;
// - copia se reface pentru FIECARE plantare si se compara sha256 cu originalul inainte de a
// planta (altfel s-ar masura plantarea de dinainte);
// - ancora unei plantari trebuie sa apara EXACT o data; o plantare care nu se poate pune e un
// ESEC al controlului, nu o trecere;
// - plantarile se fac cu o conditie falsa la RULARE sau cu o inlocuire care ramane cod valid,
// ca rosul sa vina din proba, nu din incarcarea modulului;
// - la sfarsit originalul trebuie sa fie identic octet cu octet (sha256).
//
// Iesire: 0 numai daca proba e VERDE pe copia neatinsa, fiecare plantare e ROSIE pe probele
// numite si originalul e neatins; altfel 1.
//
// --autoproba: controlul controlului. Ruleaza momeli (ancora inexistenta, plantare fara efect,
// motiv gresit, proba inexistenta, modul care nu se incarca) si cere ca fiecare sa primeasca
// verdictul ei de ESEC. Un control care nu a fost vazut esuand nu se poate crede.
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const RADACINA = path.resolve(HERE, '..');
// 2026-09-28: server.mjs importa si hsm-radacina.mjs (radacina sigilata de HSM); fara el copia nu mai pornea si linia de baza iesea STRICATA
const FISIERE = ['kms.mjs', 'server.mjs', 'hsm-radacina.mjs', 'test/proba.mjs'];
const NICIODATA = "process.env.AERE_KMS_PLANTA_NICIODATA === 'da'";
// Fiecare plantare: fisierul, ancora (exact o aparitie), inlocuirea, si probele care TREBUIE sa
// iasa rosii, fiecare cu un fragment din motivul pe care trebuie sa cada.
const PLANTARI = [
{
id: 'P16',
defect: 'A4: mutatia ramane pe disc cand randul de audit nu se poate scrie (rollback-ul nu se mai face)',
fisier: 'kms.mjs',
ancora: ' if (!changed) return;',
inlocuire: " if (!changed || !(process.env.AERE_KMS_PLANTA_NICIODATA === 'da')) return;",
rosii: [
['audit: o mutatie al carei rand de audit nu se poate scrie NU ramane pe disc (rotire, minim, creare), iar lantul ramane valid', 'rotirea a ramas pe disc fara rand de audit'],
],
},
{
id: 'P01',
defect: 'KDF fara secretul ML-KEM (IKM = numai X25519)',
fisier: 'kms.mjs',
ancora: 'const ikm = Buffer.concat([ssK, ssX]);',
inlocuire: 'const ikm = Buffer.concat([ssX]);',
rosii: [
['criptare: atacatorul cu doar secretul X25519 nu poate deriva cheia plicului', 'plicul s-a deschis numai cu secretul X25519'],
['interop: plicul serviciului decapsulat si decriptat manual cu node:crypto', 'commit'],
['interop: plic construit fara unul din secrete e refuzat de serviciu cu HEADER_AUTH_FAILED', 'KDF doar-x: trebuia refuzat'],
],
},
{
id: 'P02',
defect: 'KDF fara secretul X25519 (IKM = numai ML-KEM)',
fisier: 'kms.mjs',
ancora: 'const ikm = Buffer.concat([ssK, ssX]);',
inlocuire: 'const ikm = Buffer.concat([ssK]);',
rosii: [
['criptare: atacatorul cu doar secretul ML-KEM nu poate deriva cheia plicului', 'plicul s-a deschis numai cu secretul ML-KEM'],
['interop: plic construit fara unul din secrete e refuzat de serviciu cu HEADER_AUTH_FAILED', 'KDF doar-k: trebuia refuzat'],
],
},
{
id: 'P03',
defect: 'verificarea accepta o singura semnatura (SAU in loc de SI)',
fisier: 'kms.mjs',
ancora: 'const valid = edOk && pqOk;',
inlocuire: 'const valid = edOk || pqOk;',
rosii: [
['semnare: jumatatea Ed25519 stricata e refuzata cu CLASSICAL_SIGNATURE_INVALID', 'valid: asteptat false'],
['semnare: jumatatea ML-DSA-65 stricata e refuzata cu PQ_SIGNATURE_INVALID', 'valid: asteptat false'],
['semnare: jumatati amestecate din doua semnaturi valide sunt refuzate', 'amestec peste "unu": asteptat false'],
],
},
{
id: 'P04',
defect: 'AAD ignorat (inlocuit cu sirul gol)',
fisier: 'kms.mjs',
ancora: "return toBytes(aad, 'aad', MAX_AAD);",
inlocuire: 'return Buffer.alloc(0);',
rosii: [
['criptare: alt aad refuzat cu AAD_MISMATCH', 'alt aad: trebuia refuzat cu AAD_MISMATCH'],
['datakey: cheia clara si cea invelita corespund; forma doar-invelita nu intoarce cheia clara', 'cheia de date legata de aad'],
['rewrap: reincapsuleaza la ultima versiune, acelasi text clar, raspunsul nu contine text clar', 'rewrap cu alt aad'],
],
},
{
id: 'P05',
defect: 'min_decryption_version ignorat',
fisier: 'kms.mjs',
ancora: 'if (ver < key.min_decryption_version) throw',
inlocuire: `if (ver < key.min_decryption_version && ${NICIODATA}) throw`,
rosii: [
['rotire: sub min_decryption_version decriptarea e refuzata cu VERSION_BELOW_MINIMUM', 'v1 sub minim: trebuia refuzat'],
['rotire: sub min_decryption_version verificarea semnaturii e refuzata cu VERSION_BELOW_MINIMUM', 'v1 sub minim: asteptat false'],
['server: flux complet prin HTTP (creare, criptare, decriptare, rotire, rewrap, datakey, semnare, verificare, audit)', 'sub minim prin HTTP'],
],
},
{
id: 'P06',
defect: 'jurnalul scris fara legatura cu randul anterior (prev constant)',
fisier: 'kms.mjs',
ancora: 'prev: this.#head.mac,',
inlocuire: 'prev: ZERO_MAC,',
rosii: [
['audit: jurnalul neatins se verifica OK, un rand pe operatie, si refuzurile au motivul lor', 'jurnal neatins'],
['audit: rand sters detectat cu AUDIT_CHAIN_BROKEN pe randul lui', 'randul: asteptat 4'],
],
},
{
id: 'P07',
defect: 'verificatorul jurnalului nu verifica legatura (seq/prev)',
fisier: 'kms.mjs',
ancora: 'if (row.seq !== seq + 1 || row.prev !== prev)',
inlocuire: `if ((row.seq !== seq + 1 || row.prev !== prev) && ${NICIODATA})`,
rosii: [
['audit: rand sters detectat cu AUDIT_CHAIN_BROKEN pe randul lui', 'rand sters: asteptat false'],
['audit: randuri reordonate detectate cu AUDIT_CHAIN_BROKEN', 'reordonare: asteptat false'],
['audit: pornirea refuza un jurnal stricat cu AUDIT_CHAIN_INVALID', 'trebuia refuzat cu AUDIT_CHAIN_INVALID'],
],
},
{
id: 'P08',
defect: 'verificatorul jurnalului nu verifica mac-ul randului',
fisier: 'kms.mjs',
ancora: "if (!macOk) return fail('AUDIT_ROW_MODIFIED', i + 1);",
inlocuire: `if (!macOk && ${NICIODATA}) return fail('AUDIT_ROW_MODIFIED', i + 1);`,
rosii: [['audit: rand schimbat detectat cu AUDIT_ROW_MODIFIED', 'rand schimbat: asteptat false']],
},
{
id: 'P09',
defect: 'cheia privata scrisa si necifrata langa sigiliu',
fisier: 'kms.mjs',
ancora: 'private_sealed: sealed,',
inlocuire: "private_sealed: sealed, private_debug: Buffer.from(privJson).toString('base64'),",
rosii: [['stocare: materialul privat nu apare in clar pe disc (cu controlul pozitiv al scanerului)', 'material privat gasit in clar']],
},
{
id: 'P10',
defect: 'integritatea fisierului de cheie neverificata',
fisier: 'kms.mjs',
ancora: "if (!macOk) throw new KmsError('KEY_FILE_TAMPERED'",
inlocuire: `if (!macOk && ${NICIODATA}) throw new KmsError('KEY_FILE_TAMPERED'`,
rosii: [
['stocare: min_decryption_version coborat pe disc refuzat cu KEY_FILE_TAMPERED', 'trebuia refuzat cu KEY_FILE_TAMPERED'],
['stocare: cheie publica inlocuita pe disc refuzata cu KEY_FILE_TAMPERED', 'trebuia refuzat cu KEY_FILE_TAMPERED'],
],
},
{
id: 'P11',
defect: 'fara cheie radacina se genereaza una in tacere',
fisier: 'kms.mjs',
ancora: "if (s === '') throw new KmsError('ROOT_KEY_MISSING',",
inlocuire: "if (s === '') return crypto.randomBytes(32); if (s === '') throw new KmsError('ROOT_KEY_MISSING',",
rosii: [
['radacina: lipsa cheii refuza pornirea cu ROOT_KEY_MISSING si nu creeaza nimic pe disc', 'trebuia refuzat cu ROOT_KEY_MISSING'],
['server: configurarea implicita asculta pe 127.0.0.1 si cere token si cheie radacina', 'fara cheie radacina: trebuia refuzat'],
['server: pornit din linia de comanda refuza fara AERE_KMS_ROOT_KEY si nu tipareste tokenul', 'codul de iesire'],
],
},
{
id: 'P12',
defect: 'amprenta cheii/versiunii din plic neverificata',
fisier: 'kms.mjs',
ancora: 'if (!fp.equals(fpExpected)) {',
inlocuire: `if (!fp.equals(fpExpected) && ${NICIODATA}) {`,
rosii: [
['criptare: alta cheie refuzata cu KEY_MISMATCH', 'motiv asteptat KEY_MISMATCH'],
['semnare: alta cheie refuzata cu KEY_MISMATCH, semnatura malformata cu MALFORMED_SIGNATURE', 'motivul: asteptat "KEY_MISMATCH"'],
],
},
{
id: 'P13',
defect: 'rewrap intoarce si textul clar',
fisier: 'kms.mjs',
ancora: 'return { value: { ciphertext: r.ciphertext, version: r.version }, version: r.version };',
inlocuire: "return { value: { ciphertext: r.ciphertext, version: r.version, plaintext: plaintext.toString('base64') }, version: r.version };",
rosii: [
['rewrap: reincapsuleaza la ultima versiune, acelasi text clar, raspunsul nu contine text clar', 'campurile raspunsului'],
['server: flux complet prin HTTP (creare, criptare, decriptare, rotire, rewrap, datakey, semnare, verificare, audit)', 'rewrap nu intoarce text clar'],
],
},
{
id: 'P14',
defect: 'serverul lasa sa treaca o cerere fara Authorization',
fisier: 'server.mjs',
ancora: "if (typeof header !== 'string' || header === '') return 'UNAUTHENTICATED';",
inlocuire: "if (typeof header !== 'string' || header === '') return null;",
rosii: [
['server: fara Authorization raspunde 401 UNAUTHENTICATED', 'fara token: asteptat 401'],
['server: pornit din linia de comanda asculta pe 127.0.0.1 si raspunde', 'cerere neautentificata'],
],
},
{
id: 'P15',
defect: 'serverul ignora limita de marime a cererii',
fisier: 'server.mjs',
ancora: 'return n > maxBody;',
inlocuire: 'return false;',
rosii: [
['server: cerere peste limita cu Content-Length raspunde 413 BODY_TOO_LARGE', 'peste limita: asteptat 413'],
['server: cerere peste limita fara Content-Length (chunked) raspunde 413 BODY_TOO_LARGE', 'peste limita, chunked: asteptat 413'],
],
},
];
// Momelile pentru --autoproba: controlul insusi trebuie sa poata iesi rosu. Fiecare momeala e o
// plantare stricata dinadins si are verdictul pe care controlul TREBUIE sa i-l dea.
const MOMELI = [
{
id: 'M1',
defect: 'ancora care nu exista in cod',
fisier: 'kms.mjs',
ancora: 'ACEASTA ANCORA NU EXISTA IN COD',
inlocuire: 'x',
rosii: [['semnare: semnatura hibrida se verifica, cu ambele jumatati raportate', 'x']],
asteptat: 'ESEC CONTROL',
},
{
id: 'M2',
defect: 'plantare fara efect (un comentariu)',
fisier: 'kms.mjs',
ancora: "export const PREFIX = 'aerekms';",
inlocuire: "export const PREFIX = 'aerekms'; // momeala fara efect",
rosii: [['semnare: semnatura hibrida se verifica, cu ambele jumatati raportate', 'x']],
asteptat: 'VERDE (NEPRINS)',
},
{
id: 'M3',
defect: 'defect real, dar motivul cerut nu e cel pe care cade proba',
fisier: 'kms.mjs',
ancora: 'const valid = edOk && pqOk;',
inlocuire: 'const valid = edOk || pqOk;',
rosii: [['semnare: jumatatea Ed25519 stricata e refuzata cu CLASSICAL_SIGNATURE_INVALID', 'un motiv care nu apare niciodata']],
asteptat: 'ROSU GRESIT',
},
{
id: 'M4',
defect: 'proba numita nu exista',
fisier: 'kms.mjs',
ancora: 'const valid = edOk && pqOk;',
inlocuire: 'const valid = edOk || pqOk;',
rosii: [['o proba care nu exista', 'x']],
asteptat: 'ESEC CONTROL',
},
{
id: 'M5',
defect: 'plantare care rupe incarcarea modulului',
fisier: 'kms.mjs',
ancora: 'const valid = edOk && pqOk;',
inlocuire: 'const valid = edOk && ;',
rosii: [['semnare: jumatatea Ed25519 stricata e refuzata cu CLASSICAL_SIGNATURE_INVALID', 'valid: asteptat false']],
asteptat: 'STRICAT',
},
];
// ---------------------------------------------------------------------------------------------
const sha = (p) => crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
const amprente = () => Object.fromEntries(FISIERE.map((f) => [f, sha(path.join(RADACINA, f))]));
function pregatesteCopie(dest) {
fs.rmSync(dest, { recursive: true, force: true });
for (const f of FISIERE) {
const d = path.join(dest, f);
fs.mkdirSync(path.dirname(d), { recursive: true });
fs.copyFileSync(path.join(RADACINA, f), d);
}
for (const f of FISIERE) {
if (sha(path.join(dest, f)) !== sha(path.join(RADACINA, f))) throw new Error(`copia lui ${f} difera de original inainte de plantare`);
}
}
function planteaza(dest, p) {
const fp = path.join(dest, p.fisier);
const text = fs.readFileSync(fp, 'utf8');
const bucati = text.split(p.ancora);
if (bucati.length !== 2) return { ok: false, motiv: `ancora apare de ${bucati.length - 1} ori in ${p.fisier} (trebuie exact o data)` };
const nou = bucati.join(p.inlocuire);
fs.writeFileSync(fp, nou);
if (sha(fp) === sha(path.join(RADACINA, p.fisier))) return { ok: false, motiv: 'fisierul plantat e identic cu originalul' };
return { ok: true };
}
function envCurat() {
return Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('AERE_KMS_')));
}
function ruleaza(dest) {
const out = path.join(dest, 'rezultat-proba.json');
fs.rmSync(out, { force: true });
const t0 = Date.now();
const r = spawnSync(process.execPath, [path.join(dest, 'test', 'proba.mjs')], {
cwd: dest,
env: { ...envCurat(), AERE_KMS_PROBA_JSON: out },
encoding: 'utf8',
timeout: 300000,
maxBuffer: 16 * 1024 * 1024,
});
let json = null;
try {
json = JSON.parse(fs.readFileSync(out, 'utf8'));
} catch {
json = null;
}
return { json, status: r.status, signal: r.signal, ms: Date.now() - t0, stderr: String(r.stderr || '').slice(-600) };
}
function main() {
const autoproba = process.argv.includes('--autoproba');
const PL = autoproba ? MOMELI : PLANTARI;
if (autoproba) console.log('AUTOPROBA: momelile de mai jos TREBUIE sa primeasca verdictul lor de esec\n');
const inainte = amprente();
const lucru = fs.mkdtempSync(path.join(os.tmpdir(), 'aerekms-control-'));
const dest = path.join(lucru, 'copie');
const linii = [];
let esecuri = 0;
try {
// 1. linia de baza: copia neatinsa trebuie sa fie VERDE
pregatesteCopie(dest);
const baza = ruleaza(dest);
if (!baza.json || baza.json.completed !== true) {
console.log(`LINIA DE BAZA STRICATA: proba nu a ajuns la capat (cod ${baza.status}, semnal ${baza.signal})\n${baza.stderr}`);
return 1;
}
const numeBaza = new Set(baza.json.results.map((r) => r.nume));
if (baza.json.failed.length !== 0) {
console.log(`LINIA DE BAZA ROSIE: ${baza.json.failed.length} probe pica pe codul neatins:\n ${baza.json.failed.join('\n ')}`);
return 1;
}
console.log(`linia de baza: VERDE, ${baza.json.passed}/${baza.json.total} probe, ${baza.ms} ms (node ${baza.json.node}, openssl ${baza.json.openssl})\n`);
// 2. fiecare plantare pe o copie proaspata
for (const p of PL) {
pregatesteCopie(dest);
const numite = p.rosii.map(([n]) => n);
const lipsa = numite.filter((n) => !numeBaza.has(n));
if (lipsa.length) {
esecuri++;
linii.push({ p, verdict: 'ESEC CONTROL', detaliu: `proba numita nu exista in proba: ${lipsa.join(' | ')}` });
continue;
}
const pl = planteaza(dest, p);
if (!pl.ok) {
esecuri++;
linii.push({ p, verdict: 'ESEC CONTROL', detaliu: `plantarea nu s-a putut pune: ${pl.motiv}` });
continue;
}
const r = ruleaza(dest);
if (!r.json || r.json.completed !== true || r.json.total !== baza.json.total) {
esecuri++;
linii.push({ p, verdict: 'STRICAT', detaliu: `proba nu a rulat intreaga (cod ${r.status}, probe ${r.json ? r.json.total : '-'}/${baza.json.total}); ${r.stderr.split('\n').slice(-3).join(' ')}` });
continue;
}
const dupaNume = new Map(r.json.results.map((x) => [x.nume, x]));
const probleme = [];
let rosiiNumite = 0;
for (const [nume, motiv] of p.rosii) {
const x = dupaNume.get(nume);
if (x.ok) probleme.push(`VERDE: ${nume}`);
else if (!String(x.motiv).includes(motiv)) probleme.push(`ROSU DIN ALT MOTIV: ${nume} -> "${x.motiv.slice(0, 160)}" (cerut: "${motiv}")`);
else rosiiNumite++;
}
const inPlus = r.json.failed.filter((n) => !numite.includes(n));
if (probleme.length === 0) {
linii.push({ p, verdict: 'ROSU', detaliu: `${rosiiNumite}/${numite.length} numite rosii pe motivul cerut; alte ${inPlus.length} rosii in plus`, inPlus, ms: r.ms });
} else {
esecuri++;
linii.push({ p, verdict: r.json.failed.length === 0 ? 'VERDE (NEPRINS)' : 'ROSU GRESIT', detaliu: probleme.join('\n '), inPlus, ms: r.ms });
}
}
} finally {
fs.rmSync(lucru, { recursive: true, force: true });
}
for (const l of linii) {
console.log(`${l.verdict.padEnd(15)} ${l.p.id} ${l.p.defect}${l.ms ? ` (${l.ms} ms)` : ''}\n ${l.detaliu}`);
if (l.inPlus && l.inPlus.length) console.log(` in plus: ${l.inPlus.join(' | ')}`);
}
// 3. originalul neatins
const dupa = amprente();
const schimbate = FISIERE.filter((f) => inainte[f] !== dupa[f]);
if (schimbate.length) {
esecuri++;
console.log(`\nORIGINALUL S-A SCHIMBAT: ${schimbate.join(', ')}`);
} else {
console.log(`\noriginal neatins (sha256): ${FISIERE.map((f) => `${f}=${dupa[f].slice(0, 12)}`).join(' ')}`);
}
if (autoproba) {
// Aici esecurile sunt ceruse: fiecare momeala trebuie sa primeasca exact verdictul ei.
let potrivite = 0;
for (const l of linii) {
const ok = l.verdict === l.p.asteptat;
if (ok) potrivite++;
console.log(`${ok ? 'CORECT ' : 'GRESIT '} ${l.p.id}: controlul a spus "${l.verdict}", trebuia "${l.p.asteptat}"`);
}
const originalOk = schimbate.length === 0;
console.log(`\nautoproba controlului: ${potrivite}/${MOMELI.length} momeli cu verdictul cerut; original ${originalOk ? 'neatins' : 'SCHIMBAT'}`);
return potrivite === MOMELI.length && linii.length === MOMELI.length && originalOk ? 0 : 1;
}
const rosii = linii.filter((l) => l.verdict === 'ROSU').length;
console.log(`\ncontrol negativ: ${rosii}/${PLANTARI.length} plantari prinse pe probele numite; ${esecuri} esecuri ale controlului`);
return esecuri === 0 && rosii === PLANTARI.length ? 0 : 1;
}
try {
process.exitCode = main();
} catch (e) {
console.log(`controlul negativ a cazut: ${(e && e.stack) || e}`);
process.exitCode = 2;
}
+41
View File
@@ -0,0 +1,41 @@
// test/proba-hsm-incredere.mjs (2026-09-29, revizuirea adversariala a feliei HSM, H1): fisierul sigilat NU alege biblioteca PKCS#11 si
// nici variabila de mediu trimisa drept PIN. Nu cere un HSM: unealta primita e o cale care NU exista, deci orice verificare care lasa
// cererea sa ajunga la unealta se vede ca HSM_TOOL_MISSING, iar un refuz dat INAINTE de unealta are codul lui. Controlul pozitiv al
// metodei: o sigilare corecta ajunge chiar la unealta (HSM_TOOL_MISSING), deci refuzurile de mai jos nu vin din altceva.
// node test/proba-hsm-incredere.mjs -> 0 toate cum trebuia, 1 altfel
// AERE_HSM_MODUL_SUB_PROBA=<cale> numai pentru controlul negativ (o copie plantata a modulului)
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const AICI = path.dirname(fileURLToPath(import.meta.url));
const MOD = process.env.AERE_HSM_MODUL_SUB_PROBA || path.join(AICI, '..', 'hsm-radacina.mjs');
const { deschideRadacina, radacinaDinHsm, FORMAT_HSM } = await import(pathToFileURL(MOD).href);
let rele = 0, n = 0;
const cer = (nume, ok, extra = '') => { n++; console.log(` [${ok ? 'OK ' : 'RAU '}] ${nume}${extra ? ' (' + extra + ')' : ''}`); if (!ok) rele++; };
const codul = (fn) => { try { fn(); return 'FARA REFUZ'; } catch (e) { return e.code || String(e.message).slice(0, 60); } };
const LIB = path.resolve('/usr/lib/softhsm/libsofthsm2.so');
const RAU = path.resolve('/tmp/biblioteca-straina.so');
const UNEALTA = path.join(os.tmpdir(), 'nu-exista-' + process.pid, 'pkcs11-tool');
const sig = { format: FORMAT_HSM, mecanism: 'AES-CBC-PAD', modul: LIB, token: 'aere-kms', idCheie: '0a', pinEnv: 'AERE_HSM_PIN', iv: '00'.repeat(16), ct: '11'.repeat(64) };
const env = { AERE_HSM_PIN: '483920', AERE_HSM_MODULE: LIB, AERE_KMS_TOKEN: 'AERE-SINTETIC-jeton-api-care-nu-trebuie-trimis-ca-pin' };
const deschide = (s, e = env) => codul(() => deschideRadacina(s, { env: e, unealta: UNEALTA }));
cer('CONTROL POZITIV: o sigilare corecta ajunge la unealta (HSM_TOOL_MISSING aici), deci refuzurile de mai jos vin din verificari', deschide(sig) === 'HSM_TOOL_MISSING', deschide(sig));
cer('H1: o biblioteca din fisier, alta decat AERE_HSM_MODULE -> HSM_MODULE_NOT_ALLOWED, fara sa ruleze unealta', deschide({ ...sig, modul: RAU }) === 'HSM_MODULE_NOT_ALLOWED', deschide({ ...sig, modul: RAU }));
cer('H1: fara AERE_HSM_MODULE -> HSM_CONFIG_INVALID (fisierul singur nu alege biblioteca)', deschide(sig, { ...env, AERE_HSM_MODULE: '' }) === 'HSM_CONFIG_INVALID');
cer('H1: AERE_HSM_MODULE relativ -> HSM_CONFIG_INVALID', deschide(sig, { ...env, AERE_HSM_MODULE: 'libsofthsm2.so' }) === 'HSM_CONFIG_INVALID');
cer('H1: fisierul cere alta variabila drept PIN (jetonul API) -> HSM_SEAL_INVALID, fara sa ruleze unealta', deschide({ ...sig, pinEnv: 'AERE_KMS_TOKEN' }) === 'HSM_SEAL_INVALID', deschide({ ...sig, pinEnv: 'AERE_KMS_TOKEN' }));
const { pinEnv, ...faraPinEnv } = sig;
cer('o sigilare fara camp pinEnv (PIN-ul din AERE_HSM_PIN) ajunge la unealta', deschide(faraPinEnv) === 'HSM_TOOL_MISSING');
// drumul serverului: AERE_KMS_ROOT_HSM spre un fisier cu biblioteca straina
const T = fs.mkdtempSync(path.join(os.tmpdir(), 'hsm-incredere-'));
try {
const f = path.join(T, 'root-hsm.json'); fs.writeFileSync(f, JSON.stringify({ ...sig, modul: RAU }));
cer('H1 pe drumul serverului: AERE_KMS_ROOT_HSM cu biblioteca straina -> HSM_MODULE_NOT_ALLOWED', codul(() => radacinaDinHsm({ ...env, AERE_KMS_ROOT_HSM: f }, { unealta: UNEALTA })) === 'HSM_MODULE_NOT_ALLOWED');
} finally { fs.rmSync(T, { recursive: true, force: true }); }
console.log(`\nincrederea in fisierul sigilat (H1): ${n - rele}/${n} cum trebuia`);
process.exitCode = rele ? 1 : 0;
+88
View File
@@ -0,0 +1,88 @@
// test/proba-hsm.mjs - proba radacinii KMS sigilate de un HSM (hsm-radacina.mjs), pe un HSM PKCS#11 REAL (SoftHSM2), nu pe o imitatie
// a uneltei: token nou intr-un dosar temporar, cheie AES-256 generata IN token (sensitive, never extractable), apoi sigilare,
// deschidere, KMS-ul pornit din radacina deschisa si o runda hibrida (ML-KEM-768 + X25519) prin el. Fiecare refuz se judeca dupa
// MOTIV (codul), nu dupa faptul ca a aruncat ceva.
// Cere: Node 24 (kms.mjs), softhsm2-util si pkcs11-tool (OpenSC) in PATH; libsofthsm2.so. Ruleaza in WSL / Linux:
// /root/node24/bin/node test/proba-hsm.mjs -> 0 toate cum trebuia, 1 altfel, 2 NEMASURAT (HSM-ul de proba nu porneste)
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { sigileazaRadacina, deschideRadacina, radacinaDinHsm, FORMAT_HSM } from '../hsm-radacina.mjs';
import { configFromEnv } from '../server.mjs';
import { openKms } from '../kms.mjs';
const MODUL = process.env.AERE_PKCS11_MODUL || '/usr/lib/softhsm/libsofthsm2.so';
let rele = 0, n = 0;
const cer = (nume, ok, extra = '') => { n++; console.log(` [${ok ? 'OK ' : 'RAU '}] ${nume}${extra ? ' (' + extra + ')' : ''}`); if (!ok) rele++; };
const codul = (fn) => { try { fn(); return 'FARA REFUZ'; } catch (e) { return e.code || String(e.message).slice(0, 60); } };
const nemasurat = (m) => { console.log('NEMASURAT: ' + m); process.exit(2); };
if (!fs.existsSync(MODUL)) nemasurat('lipseste modulul PKCS#11 ' + MODUL);
const T = fs.mkdtempSync(path.join(os.tmpdir(), 'proba-hsm-'));
// 2026-09-29 (H1): deschiderea cere biblioteca din configuratia procesului, nu din fisierul sigilat
const env = { ...process.env, SOFTHSM2_CONF: path.join(T, 'softhsm2.conf'), AERE_HSM_PIN: '483920', AERE_HSM_MODULE: MODUL };
fs.mkdirSync(path.join(T, 'tokens'));
fs.writeFileSync(env.SOFTHSM2_CONF, `directories.tokendir = ${path.join(T, 'tokens')}\nobjectstore.backend = file\nlog.level = ERROR\n`);
const ruleaza = (c, a) => spawnSync(c, a, { env, encoding: 'utf8' });
try {
let r = ruleaza('softhsm2-util', ['--init-token', '--free', '--label', 'aere-kms', '--pin', env.AERE_HSM_PIN, '--so-pin', '771122']);
if (r.status !== 0) nemasurat('softhsm2-util nu initializeaza tokenul: ' + (r.stderr || r.error));
r = ruleaza('pkcs11-tool', ['--module', MODUL, '--token-label', 'aere-kms', '--login', '--pin', 'env:AERE_HSM_PIN', '--keygen', '--key-type', 'AES:32', '--label', 'kms-root', '--id', '0a', '--sensitive']);
if (r.status !== 0) nemasurat('cheia AES nu se genereaza in token: ' + (r.stderr || r.error));
cer('cheia AES e generata IN token: sensitive, never extractable', /never extractable/.test(r.stdout) && /sensitive/.test(r.stdout));
r = ruleaza('pkcs11-tool', ['--module', MODUL, '--token-label', 'aere-kms', '--login', '--pin', 'env:AERE_HSM_PIN', '--read-object', '--type', 'secrkey', '--id', '0a', '--output-file', path.join(T, 'k')]);
cer('cheia NU poate fi citita afara din HSM', r.status !== 0 && (!fs.existsSync(path.join(T, 'k')) || fs.statSync(path.join(T, 'k')).size === 0));
const radacina = crypto.randomBytes(32);
const sig = sigileazaRadacina({ modul: MODUL, token: 'aere-kms', idCheie: '0a', radacina: Buffer.from(radacina), env });
cer('sigilarea: formatul, 64 de octeti, si radacina NU apare in ea', sig.format === FORMAT_HSM && sig.ct.length === 128 && !JSON.stringify(sig).includes(radacina.toString('hex')));
const d = deschideRadacina(sig, { env });
cer('deschiderea cu HSM-ul si PIN-ul da exact radacina sigilata', d.equals(radacina));
const s2 = sigileazaRadacina({ modul: MODUL, token: 'aere-kms', idCheie: '0a', radacina: Buffer.from(radacina), env });
cer('doua sigilari ale aceleiasi radacini difera (iv aleator), amandoua se deschid', s2.ct !== sig.ct && deschideRadacina(s2, { env }).equals(radacina));
// refuzuri, fiecare cu motivul lui
cer('PIN gresit -> HSM_LOGIN_REFUSED', codul(() => deschideRadacina(sig, { env: { ...env, AERE_HSM_PIN: '000000' } })) === 'HSM_LOGIN_REFUSED');
cer('PIN lipsa -> HSM_PIN_MISSING (nu se incearca fara)', codul(() => deschideRadacina(sig, { env: { ...env, AERE_HSM_PIN: '' } })) === 'HSM_PIN_MISSING');
cer('alt token -> HSM_TOKEN_NOT_FOUND', codul(() => deschideRadacina({ ...sig, token: 'alt-token' }, { env })) === 'HSM_TOKEN_NOT_FOUND');
const cti = Buffer.from(sig.ct, 'hex'); cti[3] ^= 0x01; // primul bloc: CBC descifreaza, dar in altceva
cer('sigilare atinsa in primul bloc -> HSM_ROOT_TAMPERED (amprenta), nu o radacina gresita', codul(() => deschideRadacina({ ...sig, ct: cti.toString('hex') }, { env })) === 'HSM_ROOT_TAMPERED');
const ctu = Buffer.from(sig.ct, 'hex'); ctu[63] ^= 0x80; // ultimul bloc: umplutura strica
cer('sigilare atinsa in ultimul bloc -> HSM_ROOT_TAMPERED', codul(() => deschideRadacina({ ...sig, ct: ctu.toString('hex') }, { env })) === 'HSM_ROOT_TAMPERED');
// H2 (2026-09-29): umplutura stricata (ultimul bloc) si amprenta gresita (primul bloc) dau ACELASI mesaj: altfel jurnalul pornirii e un oracol de umplutura
const mesaj = (s) => { try { deschideRadacina(s, { env }); return 'FARA REFUZ'; } catch (e) { return e.code + ': ' + e.message; } };
const m1 = mesaj({ ...sig, ct: cti.toString('hex') }), m2 = mesaj({ ...sig, ct: ctu.toString('hex') });
cer('H2: umplutura stricata si amprenta gresita nu se deosebesc prin mesaj', m1 === m2 && m1.startsWith('HSM_ROOT_TAMPERED'), m1 === m2 ? 'identice' : m1 + ' | ' + m2);
// CONTROLUL NECESITATII amprentei: fara ea, CBC ar fi dat 48 de octeti de gunoi, deci amprenta e cea care prinde atingerea
const ctf = path.join(T, 'c'), ptf = path.join(T, 'p'); fs.writeFileSync(ctf, cti);
r = ruleaza('pkcs11-tool', ['--module', MODUL, '--token-label', 'aere-kms', '--login', '--pin', 'env:AERE_HSM_PIN', '--id', '0a', '--mechanism', 'AES-CBC-PAD', '--decrypt', '--iv', sig.iv, '--input-file', ctf, '--output-file', ptf]);
cer('CONTROL: HSM-ul singur descifreaza sigilarea atinsa fara sa se planga (48 de octeti) - de aceea amprenta', r.status === 0 && fs.statSync(ptf).size === 48);
r = ruleaza('pkcs11-tool', ['--module', MODUL, '--token-label', 'aere-kms', '--login', '--pin', 'env:AERE_HSM_PIN', '--keygen', '--key-type', 'AES:32', '--label', 'alta', '--id', '0b', '--sensitive']);
cer('alta cheie din acelasi token -> HSM_ROOT_TAMPERED (nu se deschide cu cheia gresita)', r.status === 0 && codul(() => deschideRadacina({ ...sig, idCheie: '0b' }, { env })) === 'HSM_ROOT_TAMPERED');
// KMS-ul pornit din radacina deschisa de HSM, capat la capat
const fsig = path.join(T, 'root-hsm.json'); fs.writeFileSync(fsig, JSON.stringify(sig));
const tok = crypto.randomBytes(24).toString('hex');
const cfg = configFromEnv({ ...env, AERE_KMS_ROOT_HSM: fsig, AERE_KMS_TOKEN: tok, AERE_KMS_DATA_DIR: path.join(T, 'date') });
cer('serverul ia radacina din HSM (rootSource=hsm) si e chiar cea sigilata', cfg.rootSource === 'hsm' && cfg.rootKey === radacina.toString('hex'));
const kms = openKms({ dataDir: cfg.dataDir, rootKey: cfg.rootKey });
kms.createKey('client', { type: 'encrypt' });
const c = kms.encrypt('client', 'date de pastrat', 'ctx').ciphertext;
cer('KMS pornit din radacina HSM: runda hibrida X25519 + ML-KEM-768', kms.decrypt('client', c, 'ctx').plaintext.toString() === 'date de pastrat');
kms.close();
const cfg2 = configFromEnv({ ...env, AERE_KMS_ROOT_HSM: fsig, AERE_KMS_TOKEN: tok, AERE_KMS_DATA_DIR: path.join(T, 'date') });
const kms2 = openKms({ dataDir: cfg2.dataDir, rootKey: cfg2.rootKey });
cer('redeschis din HSM, KMS-ul descifreaza ce a cifrat inainte (aceeasi radacina)', kms2.decrypt('client', c, 'ctx').plaintext.toString() === 'date de pastrat');
kms2.close();
cer('amandoua sursele de radacina deodata -> ROOT_KEY_AMBIGUOUS', codul(() => configFromEnv({ ...env, AERE_KMS_ROOT_HSM: fsig, AERE_KMS_ROOT_KEY: radacina.toString('hex'), AERE_KMS_TOKEN: tok })) === 'ROOT_KEY_AMBIGUOUS');
cer('sigilarea lipsa -> HSM_SEAL_INVALID', codul(() => radacinaDinHsm({ ...env, AERE_KMS_ROOT_HSM: path.join(T, 'nu-exista.json') })) === 'HSM_SEAL_INVALID');
cer('cu PIN gresit serverul REFUZA sa porneasca (nu cade pe alta radacina)', codul(() => configFromEnv({ ...env, AERE_HSM_PIN: '999999', AERE_KMS_ROOT_HSM: fsig, AERE_KMS_TOKEN: tok })) === 'HSM_LOGIN_REFUSED');
// /dev/shm curat dupa operatii: fisierele temporare cu radacina nu raman
const ramase = fs.existsSync('/dev/shm') ? fs.readdirSync('/dev/shm').filter((x) => x.startsWith('aerekms-hsm-')) : [];
cer('nicio urma a radacinii in /dev/shm dupa operatii', ramase.length === 0, ramase.join(','));
} finally { fs.rmSync(T, { recursive: true, force: true }); }
console.log(`\nradacina KMS sigilata de HSM (SoftHSM2 + OpenSC): ${n - rele}/${n} cum trebuia`);
process.exitCode = rele ? 1 : 0;
File diff suppressed because it is too large. Load diff