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:
commit
7d814d1bb8
24 files changed
+7004
No files matched your search
@@ -0,0 +1,67 @@
|
||||
# Aere PQ PKI
|
||||
|
||||
A private certificate authority that issues **post-quantum X.509 v3 certificates** signed with **ML-DSA** (FIPS 204, the pure form with an empty context, as RFC 9881 specifies for certificates), revocation lists signed the same way, and a strict chain verifier. Node 24 with its bundled OpenSSL 3.5, no dependencies.
|
||||
|
||||
With a chain from this CA, a TLS 1.3 server is post-quantum end to end: the key exchange is `X25519MLKEM768` and the server authenticates with an `mldsa65` signature. Measured in the probes: a Node server with our chain, and both `openssl s_client` (3.5) and a Node client accept it (`Verify return code: 0`, `Peer signature type: mldsa65`, `Negotiated TLS1.3 group: X25519MLKEM768`).
|
||||
|
||||
```
|
||||
export AERE_PKI_PASSPHRASE='...12+ characters with 3 character classes, or 20+ characters...'
|
||||
node cli.mjs init --dir ca --name root --org "Example" # ML-DSA-87 root, pathLen 1, 10 years
|
||||
node cli.mjs intermediate --dir ca --ca root --name issuing # ML-DSA-65, pathLen 0, 5 years
|
||||
node cli.mjs issue --dir ca --ca issuing --cn api.internal --dns api.internal --out api # 90 days, serverAuth
|
||||
node cli.mjs revoke --dir ca --ca issuing --cert api.crt
|
||||
node cli.mjs crl --dir ca --ca issuing --out issuing.crl
|
||||
node cli.mjs verify --roots ca/root.crt --chain api.chain.pem --host api.internal --crl issuing.crl
|
||||
node cli.mjs unseal --key api.key --out api.p8.pem # unencrypted PKCS#8 for a TLS server, only on request
|
||||
```
|
||||
|
||||
Nothing is ever overwritten, and without `AERE_PKI_PASSPHRASE` nothing is issued.
|
||||
|
||||
## Private keys on disk
|
||||
|
||||
Private keys are written **sealed** in a format of our own, never as PKCS#8:
|
||||
|
||||
```
|
||||
-----BEGIN AERE PQ PKI PRIVATE KEY-----
|
||||
SEQUENCE {
|
||||
header SEQUENCE { version 1, "scrypt", salt (16 bytes), N=131072, r=8, p=1, "aes-256-gcm", iv (12 bytes) },
|
||||
tag (16 bytes),
|
||||
ciphertext -- the PKCS#8 DER of the key, AES-256-GCM under scrypt(passphrase, salt), with the header as AAD
|
||||
}
|
||||
-----END AERE PQ PKI PRIVATE KEY-----
|
||||
```
|
||||
|
||||
Why: the PKCS#8 encryption that `node:crypto` produces (`key.export({cipher})`) derives its key with PBKDF2 at **2048 iterations**, which the adversarial review measured at 3 to 5 ms per passphrase guess. With scrypt at N=2^17, r=8, p=1 (128 MiB of memory per guess) one guess costs **about 0.7 to 1.0 s on the development laptop** (Intel i7-10870H, Node 24 `scryptSync`; the probe measures it on every run and prints the number, and fails under 25 ms). The header is bound as AAD, so a changed parameter, salt, IV or ciphertext byte fails authentication exactly like a wrong passphrase (`KEY_LOCKED`); the reader accepts N only between 2^14 and 2^20 (`KEY_FORMAT` otherwise), so a crafted file cannot make it allocate gigabytes. **PKCS#8 files, encrypted or not, are refused by `importPrivateKey` with `KEY_FORMAT`**; a key made before this format has to be re-sealed.
|
||||
|
||||
The passphrase policy (`checkPassphrase`, applied when a key is written): at least 12 characters and at least 3 of the 4 classes (lower, upper, digit, other), or at least 20 characters; one repeated character is refused; the obvious ones (`password`, `qwerty`, `123456`, `letmein`, ... with or without digits and punctuation appended) are refused. Refusals carry `PASSPHRASE`.
|
||||
|
||||
A Node TLS server loads the key in process, without ever writing it in clear: `tls.createServer({ key: importPrivateKey(fs.readFileSync('api.key', 'utf8'), passphrase).export({ type: 'pkcs8', format: 'pem' }), cert })`. For servers that only read files, `node cli.mjs unseal` writes an unencrypted PKCS#8 file with mode 0600 and never overwrites; delete it when it is no longer needed. `readSealedKeyHeader(pem)` returns the KDF parameters without opening the key.
|
||||
|
||||
## What the verifier checks
|
||||
|
||||
`verifyChain` always returns a verdict `{ ok, code, reason, chain }`; it never throws, whatever bytes it is given (the probe feeds it hundreds of random mutations, truncations and garbage).
|
||||
|
||||
- **Path building**: issuer/subject matched byte-exactly, key identifiers matched when present, and **every candidate path is tried**, trust anchors first: with a renewed root (two anchors with the same name and key, one expired) or a cross-signed intermediate listed before the right one, the valid path is found. If no path validates, the failure of the last path tried is returned (`UNTRUSTED` when no path reaches an anchor).
|
||||
- **Every link**: a valid ML-DSA signature, a CA issuer (`basicConstraints`) with `keyCertSign`, the issuer's `pathLen`, validity at the time of use, no unknown critical extension; the trusted root must be a valid self-signed certificate.
|
||||
- **Public keys**: the `subjectPublicKeyInfo` of every certificate must carry a key of exactly the FIPS 204 length for its algorithm (1312 / 1952 / 2592 bytes for ML-DSA-44 / 65 / 87) with no unused bits; anything else is the verdict `SPKI`, on the leaf too (its key is never used by the verifier, so without this check a 10-byte "key" passed).
|
||||
- **Extended key usage on authorities**: when an issuer in the chain, root included, carries an EKU, the purpose asked for must be in it (verdict `EKU`, naming the authority), as OpenSSL, Chrome and Mozilla do. `anyExtendedKeyUsage` does not satisfy a purpose, as in OpenSSL.
|
||||
- **Revocation**, for each issuer in the chain: among that issuer's lists that verify under its key and are not dated in the future, **the one with the newest `thisUpdate` is used** (ties broken by the larger `crlNumber`); the order of the input does not matter. That list must be current (`CRL_STALE` after `nextUpdate`), and a listed serial is `REVOKED`. `requireCrl` makes a missing list `CRL_MISSING`. A list whose signature does not verify is `CRL_SIGNATURE`.
|
||||
- **CRL extensions**: `authorityKeyIdentifier` and `crlNumber` are understood; `issuingDistributionPoint` and `deltaCRLIndicator` are refused however they are marked, and so is any other critical extension of the list or of an entry (`certificateIssuer` of an indirect list, for instance): verdict `CRL_EXT`, naming the extension. Non-critical unknown extensions (a `reasonCode` on an entry, for instance) are ignored.
|
||||
- **End entity**: not a CA, `digitalSignature`, the extended key usage of the purpose, and the host name or IPv4 address in the subject alternative name.
|
||||
|
||||
Every refusal carries a code: `SIGNATURE`, `UNTRUSTED`, `ROOT`, `EXPIRED`, `NOT_YET_VALID`, `NOT_CA`, `KEY_USAGE`, `PATH_LEN`, `EKU`, `SPKI`, `REVOKED`, `CRL_MISSING`, `CRL_SIGNATURE`, `CRL_STALE`, `CRL_EXT`, `LEAF_IS_CA`, `HOSTNAME`, `CRITICAL_EXT`, `ALG`, `ALG_MISMATCH`, `ALG_PARAMS`, `VERSION`, `EXT_DUP`, `DER`. The DER parser is strict: no indefinite lengths, no non-minimal lengths, no trailing bytes, no non-canonical integers or object identifiers; object identifiers with a multi-byte first subidentifier (`2.999` is `06 02 88 37`) encode and decode as OpenSSL does.
|
||||
|
||||
## How it is proven
|
||||
|
||||
`node test/proba.mjs` (27 probes, about 25 s) compares every verdict with a foreign implementation, the OpenSSL 3.5 command line in `-x509_strict` mode: the valid chain, revocation, the newest of several lists (both orders), lists made by `openssl ca -gencrl` (plain, with a revoked entry and a reason code, with a critical issuing distribution point, with an unknown critical extension), a delta list (OpenSSL refuses it only with `-extended_crl`), a changed byte, another root, expiry and not-yet-valid, a path-length violation, a non-CA issuer (a chain made by OpenSSL), host and IP names, purpose on the leaf and on authorities (`unsuitable certificate purpose` at depth 1), a renewed root (both anchors in one `CAfile`), malformed public keys (`decode error`), an unknown critical extension (made by OpenSSL), object identifier bytes (`asn1parse -genstr`). It also reads and verifies certificates made by OpenSSL, runs the real TLS handshake, measures the cost of a passphrase guess, exercises the passphrase policy, and drives the command line end to end. `node test/control-negativ.mjs` (about 3 minutes, four plantings in parallel) breaks each check in a copy of the code (22 plantings, at least one per finding of the review) and requires the named probe to turn red, the original to stay byte-identical, and the untouched suite to stay green; the number of probes is taken from the untouched run, not written down.
|
||||
|
||||
## What it does not do, and where it differs from OpenSSL
|
||||
|
||||
- **Composite (hybrid classical + ML-DSA) certificates**: still IETF drafts; this CA issues pure ML-DSA certificates. A client that only knows classical algorithms cannot verify them.
|
||||
- **OCSP, name constraints, certificate policies, IPv6 names, delta and partial (IDP) revocation lists**: not implemented; delta and IDP lists are refused (`CRL_EXT`) rather than misread. OpenSSL without `-extended_crl` silently treats a delta list as a complete one; we do not.
|
||||
- **A list without `nextUpdate`** is accepted for as long as it is the newest one, as OpenSSL does; an operator who wants freshness enforced must publish lists with `nextUpdate`.
|
||||
- **A leaf without `keyUsage`** is refused here (`KEY_USAGE`); OpenSSL `-x509_strict` accepts it.
|
||||
- **Backtracking between intermediates**: we find the valid path when a cross-signed intermediate is listed first; OpenSSL does not and refuses that input.
|
||||
- **Name comparison** is byte-exact on the DER encoding, not the full RFC 5280 normalization; chains issued here always encode names the same way.
|
||||
- **The CA key is protected by a passphrase on disk** (scrypt + AES-256-GCM, above), not by an HSM. Keep the root offline. **PKCS#8 is no longer the on-disk format**; `unseal` produces it only on request.
|
||||
- The second implementation used in the probes (OpenSSL) shares the ML-DSA code with Node, since Node bundles OpenSSL; the X.509 encoding, path building and revocation logic are independent.
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env node
|
||||
// cli.mjs: linia de comanda a autoritatii de certificare post-cuantice (pki.mjs). Starea sta intr-un dosar: fiecare CA are
|
||||
// <nume>.crt (PEM), <nume>.key (cheia SIGILATA cu parola din AERE_PKI_PASSPHRASE: scrypt + AES-256-GCM, formatul propriu din pki.mjs,
|
||||
// niciodata in clar si niciodata PKCS#8 pe disc [A1]), <nume>.revoked.json (seriile revocate) si <nume>.crlnum (numarul ultimei liste).
|
||||
// "unseal" scrie o cheie in PKCS#8 necifrat, singura forma pe care o citesc serverele TLS straine; se face numai la cerere explicita.
|
||||
// Mesajele pentru utilizator sunt in engleza.
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import * as P from './pki.mjs';
|
||||
|
||||
const USAGE = `aere-pq-pki: a private post-quantum certificate authority (X.509 v3, ML-DSA, RFC 9881)
|
||||
node cli.mjs init --dir D --name NAME [--org O] [--alg ml-dsa-87] [--days 3650] [--path-len 1]
|
||||
node cli.mjs intermediate --dir D --ca ROOT --name NAME [--org O] [--alg ml-dsa-65] [--days 1825] [--path-len 0]
|
||||
node cli.mjs issue --dir D --ca CA --cn CN [--dns a,b] [--ip 192.0.2.10] [--client] [--alg ml-dsa-65] [--days 90] --out PREFIX
|
||||
node cli.mjs revoke --dir D --ca CA --cert FILE
|
||||
node cli.mjs crl --dir D --ca CA [--days 7] --out FILE
|
||||
node cli.mjs verify --roots FILE --chain FILE [--host H] [--crl FILE ...] [--purpose serverAuth|clientAuth] [--require-crl]
|
||||
node cli.mjs unseal --key FILE.key --out FILE.pem (writes the key as UNENCRYPTED PKCS#8, for a TLS server; keep it 0600)
|
||||
Private keys are written sealed with AERE_PKI_PASSPHRASE (scrypt 2^17 + AES-256-GCM): at least 12 characters with 3 character classes,
|
||||
or at least 20 characters; obvious passphrases are refused. Without it nothing is issued.`;
|
||||
|
||||
function args(argv) {
|
||||
const o = { _: [] };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (!a.startsWith('--')) { o._.push(a); continue; }
|
||||
const k = a.slice(2);
|
||||
const flag = ['client', 'require-crl'].includes(k);
|
||||
const v = flag ? true : argv[++i];
|
||||
if (v === undefined) throw new P.PkiError('USAGE', '--' + k + ' needs a value');
|
||||
if (k === 'crl') (o.crl ||= []).push(v); else o[k] = v;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
// La deschidere se cere doar sa existe (o cheie sigilata a trecut politica atunci cand a fost scrisa); politica intreaga
|
||||
// (P.checkPassphrase) se aplica la SCRIERE, in exportPrivateKey, ca o inasprire viitoare sa nu incuie cheile vechi.
|
||||
const pass = () => {
|
||||
const p = process.env.AERE_PKI_PASSPHRASE;
|
||||
if (!p || p.length < 12) throw new P.PkiError('PASSPHRASE', 'set AERE_PKI_PASSPHRASE (at least 12 characters with 3 character classes, or at least 20 characters)');
|
||||
return p;
|
||||
};
|
||||
const need = (o, ...ks) => { for (const k of ks) if (!o[k]) throw new P.PkiError('USAGE', '--' + k + ' is required'); };
|
||||
const safeName = (n) => { if (!/^[A-Za-z0-9._-]{1,64}$/.test(n)) throw new P.PkiError('USAGE', 'names use letters, digits, ".", "_" and "-" only'); return n; };
|
||||
function loadCa(dir, ca) {
|
||||
const n = safeName(ca);
|
||||
const cert = P.unpem(fs.readFileSync(path.join(dir, n + '.crt'), 'utf8'))[0];
|
||||
const key = P.importPrivateKey(fs.readFileSync(path.join(dir, n + '.key'), 'utf8'), pass());
|
||||
return { n, cert, key };
|
||||
}
|
||||
function writeNew(file, data, mode = 0o600) {
|
||||
if (fs.existsSync(file)) throw new P.PkiError('EXISTS', file + ' exists; nothing is overwritten');
|
||||
fs.writeFileSync(file, data, { mode, flag: 'wx' });
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
const [cmd, ...rest] = argv;
|
||||
if (!cmd || cmd === '--help') { console.log(USAGE); return 0; }
|
||||
const o = args(rest);
|
||||
if (cmd === 'init' || cmd === 'intermediate') {
|
||||
need(o, 'dir', 'name');
|
||||
const n = safeName(o.name);
|
||||
fs.mkdirSync(o.dir, { recursive: true, mode: 0o700 });
|
||||
const alg = o.alg || (cmd === 'init' ? 'ml-dsa-87' : 'ml-dsa-65');
|
||||
const k = P.generateKey(alg);
|
||||
const pl = o['path-len'] !== undefined ? Number(o['path-len']) : (cmd === 'init' ? 1 : 0);
|
||||
let cert;
|
||||
if (cmd === 'init') cert = P.issue({ issuer: null, signingKey: k.privateKey, subject: { cn: o.name, o: o.org }, publicKey: k.publicKey, ca: true, pathLen: pl, days: Number(o.days || 3650) });
|
||||
else { need(o, 'ca'); const ca = loadCa(o.dir, o.ca); cert = P.issue({ issuer: ca.cert, signingKey: ca.key, subject: { cn: o.name, o: o.org }, publicKey: k.publicKey, ca: true, pathLen: pl, days: Number(o.days || 1825) }); }
|
||||
const pem = P.exportPrivateKey(k.privateKey, pass());
|
||||
writeNew(path.join(o.dir, n + '.key'), pem);
|
||||
writeNew(path.join(o.dir, n + '.crt'), P.pem('CERTIFICATE', cert), 0o644);
|
||||
writeNew(path.join(o.dir, n + '.revoked.json'), '[]\n');
|
||||
console.log(`${cmd === 'init' ? 'root' : 'intermediate'} "${o.name}" (${alg}) written to ${o.dir}`);
|
||||
return 0;
|
||||
}
|
||||
if (cmd === 'issue') {
|
||||
need(o, 'dir', 'ca', 'cn', 'out');
|
||||
const ca = loadCa(o.dir, o.ca);
|
||||
const alg = o.alg || 'ml-dsa-65';
|
||||
const k = P.generateKey(alg);
|
||||
const cert = P.issue({ issuer: ca.cert, signingKey: ca.key, subject: { cn: o.cn }, publicKey: k.publicKey, days: Number(o.days || 90),
|
||||
dns: o.dns ? String(o.dns).split(',') : [], ips: o.ip ? String(o.ip).split(',') : [], eku: [o.client ? 'clientAuth' : 'serverAuth'] });
|
||||
writeNew(o.out + '.key', P.exportPrivateKey(k.privateKey, pass()));
|
||||
writeNew(o.out + '.crt', P.pem('CERTIFICATE', cert), 0o644);
|
||||
writeNew(o.out + '.chain.pem', P.pem('CERTIFICATE', cert) + P.pem('CERTIFICATE', ca.cert), 0o644);
|
||||
console.log(`certificate for "${o.cn}" (${alg}, serial ${P.parseCert(cert).serial.toString('hex')}) written to ${o.out}.crt`);
|
||||
return 0;
|
||||
}
|
||||
if (cmd === 'revoke') {
|
||||
need(o, 'dir', 'ca', 'cert');
|
||||
const ca = loadCa(o.dir, o.ca);
|
||||
const c = P.parseCert(P.unpem(fs.readFileSync(o.cert, 'utf8'))[0]);
|
||||
if (!c.issuerRaw.equals(P.parseCert(ca.cert).subjectRaw)) throw new P.PkiError('ISSUER', 'this certificate was not issued by ' + ca.n);
|
||||
const f = path.join(o.dir, ca.n + '.revoked.json');
|
||||
const list = JSON.parse(fs.readFileSync(f, 'utf8'));
|
||||
const s = c.serial.toString('hex');
|
||||
if (!list.some((x) => x.serial === s)) list.push({ serial: s, date: new Date().toISOString() });
|
||||
fs.writeFileSync(f, JSON.stringify(list, null, 1) + '\n');
|
||||
console.log(`serial ${s} revoked by ${ca.n}; publish a new list with "crl"`);
|
||||
return 0;
|
||||
}
|
||||
if (cmd === 'crl') {
|
||||
need(o, 'dir', 'ca', 'out');
|
||||
const ca = loadCa(o.dir, o.ca);
|
||||
const nf = path.join(o.dir, ca.n + '.crlnum');
|
||||
const number = (fs.existsSync(nf) ? Number(fs.readFileSync(nf, 'utf8')) : 0) + 1;
|
||||
const list = JSON.parse(fs.readFileSync(path.join(o.dir, ca.n + '.revoked.json'), 'utf8'));
|
||||
const der = P.crl({ issuer: ca.cert, signingKey: ca.key, revoked: list, days: Number(o.days || 7), number });
|
||||
fs.writeFileSync(o.out, P.pem('X509 CRL', der));
|
||||
fs.writeFileSync(nf, String(number));
|
||||
console.log(`revocation list #${number} of ${ca.n} (${list.length} revoked) written to ${o.out}`);
|
||||
return 0;
|
||||
}
|
||||
if (cmd === 'verify') {
|
||||
need(o, 'roots', 'chain');
|
||||
const chain = P.unpem(fs.readFileSync(o.chain, 'utf8'));
|
||||
const r = P.verifyChain({ leaf: chain[0], intermediates: chain.slice(1), roots: P.unpem(fs.readFileSync(o.roots, 'utf8')),
|
||||
host: o.host || null, purpose: o.purpose || 'serverAuth', requireCrl: !!o['require-crl'],
|
||||
crls: (o.crl || []).flatMap((f) => P.unpem(fs.readFileSync(f, 'utf8'), 'X509 CRL')) });
|
||||
console.log(r.ok ? `OK: ${r.chain.join(' <- ')}` : `REFUSED (${r.code}): ${r.reason}`);
|
||||
return r.ok ? 0 : 1;
|
||||
}
|
||||
if (cmd === 'unseal') {
|
||||
need(o, 'key', 'out');
|
||||
const key = P.importPrivateKey(fs.readFileSync(o.key, 'utf8'), pass());
|
||||
writeNew(o.out, key.export({ type: 'pkcs8', format: 'pem' }));
|
||||
console.log(`${o.key} unsealed to ${o.out} as UNENCRYPTED PKCS#8 (mode 0600); delete it when the server no longer needs it`);
|
||||
return 0;
|
||||
}
|
||||
throw new P.PkiError('USAGE', 'unknown command ' + cmd + '\n' + USAGE);
|
||||
}
|
||||
|
||||
try { process.exitCode = main(process.argv.slice(2)); }
|
||||
catch (e) { console.error(`error (${e.code || 'ERROR'}): ${e.message}`); process.exitCode = 2; }
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
// der.mjs: codor si decodor DER minimal (ASN.1), numai ce trebuie pentru X.509 v3 si CRL v2. Fara dependinte.
|
||||
// Decodorul e STRICT: lungimi in forma cea mai scurta, fara lungime nedefinita, fara octeti in plus; un DER necanonic e o eroare,
|
||||
// nu o interpretare (doua codificari ale aceluiasi certificat ar da doua amprente).
|
||||
|
||||
export const TAG = {
|
||||
BOOLEAN: 0x01, INTEGER: 0x02, BIT_STRING: 0x03, OCTET_STRING: 0x04, NULL: 0x05, OID: 0x06, UTF8: 0x0c,
|
||||
PRINTABLE: 0x13, IA5: 0x16, UTC_TIME: 0x17, GEN_TIME: 0x18, SEQUENCE: 0x30, SET: 0x31,
|
||||
};
|
||||
|
||||
function lenBytes(n) {
|
||||
if (n < 0x80) return Buffer.from([n]);
|
||||
const out = [];
|
||||
while (n > 0) { out.unshift(n & 0xff); n = Math.floor(n / 256); }
|
||||
return Buffer.from([0x80 | out.length, ...out]);
|
||||
}
|
||||
|
||||
export function tlv(tag, content) {
|
||||
const c = Buffer.isBuffer(content) ? content : Buffer.from(content);
|
||||
return Buffer.concat([Buffer.from([tag]), lenBytes(c.length), c]);
|
||||
}
|
||||
|
||||
export const seq = (...items) => tlv(TAG.SEQUENCE, Buffer.concat(items.filter(Boolean)));
|
||||
export const set = (...items) => tlv(TAG.SET, Buffer.concat(items.filter(Boolean)));
|
||||
export const ctx = (n, content, constructed = true) => tlv((constructed ? 0xa0 : 0x80) | n, content);
|
||||
export const octets = (b) => tlv(TAG.OCTET_STRING, b);
|
||||
export const bits = (b, unused = 0) => tlv(TAG.BIT_STRING, Buffer.concat([Buffer.from([unused]), b]));
|
||||
export const bool = (v) => tlv(TAG.BOOLEAN, Buffer.from([v ? 0xff : 0x00]));
|
||||
export const utf8 = (s) => tlv(TAG.UTF8, Buffer.from(s, 'utf8'));
|
||||
export const ia5 = (s) => tlv(TAG.IA5, Buffer.from(s, 'ascii'));
|
||||
|
||||
/** INTEGER din Buffer fara semn (big-endian) sau din numar/BigInt nenegativ, in forma DER minima. */
|
||||
export function int(v) {
|
||||
let b;
|
||||
if (Buffer.isBuffer(v)) b = v;
|
||||
else {
|
||||
let x = BigInt(v);
|
||||
if (x < 0n) throw new Error('DER: numai intregi nenegativi');
|
||||
const a = [];
|
||||
do { a.unshift(Number(x & 0xffn)); x >>= 8n; } while (x > 0n);
|
||||
b = Buffer.from(a);
|
||||
}
|
||||
let i = 0;
|
||||
while (i < b.length - 1 && b[i] === 0 && (b[i + 1] & 0x80) === 0) i++;
|
||||
b = b.subarray(i);
|
||||
if (b[0] & 0x80) b = Buffer.concat([Buffer.from([0]), b]);
|
||||
return tlv(TAG.INTEGER, b);
|
||||
}
|
||||
|
||||
/** Un subidentificator in baza 128, cu bitul 7 pus pe toti octetii in afara de ultimul (X.690 8.19.2). */
|
||||
function base128(x) {
|
||||
const a = [Number(x & 0x7fn)]; x >>= 7n;
|
||||
while (x > 0n) { a.unshift(Number(x & 0x7fn) | 0x80); x >>= 7n; }
|
||||
return a;
|
||||
}
|
||||
|
||||
export function oid(dotted) {
|
||||
const p = String(dotted).split('.').map((x) => { if (!/^\d+$/.test(x)) throw new Error('DER: OID cu componenta nevalida: ' + dotted); return BigInt(x); });
|
||||
if (p.length < 2) throw new Error('DER: OID prea scurt');
|
||||
if (p[0] > 2n || (p[0] < 2n && p[1] > 39n)) throw new Error('DER: OID cu arc nevalid: ' + dotted);
|
||||
// [A10] primul subidentificator poarta impreuna arcul si al doilea numar (40*arc + al doilea) si, ca oricare altul, se scrie in baza 128
|
||||
// pe mai multi octeti cand trece de 127: 2.999 e 88 37, nu un singur octet trunchiat. Pe arcul 2 al doilea numar nu are limita.
|
||||
const out = base128(p[0] * 40n + p[1]);
|
||||
for (const v of p.slice(2)) out.push(...base128(v));
|
||||
return tlv(TAG.OID, Buffer.from(out));
|
||||
}
|
||||
|
||||
/** Timp X.509: UTCTime pana in 2049, GeneralizedTime dupa (RFC 5280 4.1.2.5), cu secunde si Z. */
|
||||
export function time(d) {
|
||||
const y = d.getUTCFullYear();
|
||||
const pad = (n, w = 2) => String(n).padStart(w, '0');
|
||||
const rest = pad(d.getUTCMonth() + 1) + pad(d.getUTCDate()) + pad(d.getUTCHours()) + pad(d.getUTCMinutes()) + pad(d.getUTCSeconds()) + 'Z';
|
||||
if (y >= 1950 && y < 2050) return tlv(TAG.UTC_TIME, Buffer.from(pad(y % 100) + rest, 'ascii'));
|
||||
return tlv(TAG.GEN_TIME, Buffer.from(pad(y, 4) + rest, 'ascii'));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ decodare
|
||||
|
||||
/** Un element: { tag, start, hdr, len, end, raw (tot TLV-ul), content } peste acelasi Buffer. */
|
||||
export function read(buf, off = 0) {
|
||||
if (off + 2 > buf.length) throw new Error('DER: trunchiat la antet');
|
||||
const tag = buf[off];
|
||||
if ((tag & 0x1f) === 0x1f) throw new Error('DER: eticheta cu forma lunga nesuportata');
|
||||
let l = buf[off + 1], hdr = 2;
|
||||
if (l === 0x80) throw new Error('DER: lungime nedefinita (BER), refuzata');
|
||||
if (l & 0x80) {
|
||||
const n = l & 0x7f;
|
||||
if (n === 0 || n > 4) throw new Error('DER: lungime pe ' + n + ' octeti');
|
||||
if (off + 2 + n > buf.length) throw new Error('DER: trunchiat la lungime');
|
||||
if (buf[off + 2] === 0) throw new Error('DER: lungime cu zero initial (necanonica)');
|
||||
l = 0;
|
||||
for (let i = 0; i < n; i++) l = l * 256 + buf[off + 2 + i];
|
||||
if (l < 0x80) throw new Error('DER: lungime scurta scrisa in forma lunga (necanonica)');
|
||||
hdr = 2 + n;
|
||||
}
|
||||
const end = off + hdr + l;
|
||||
if (end > buf.length) throw new Error('DER: continut trunchiat');
|
||||
return { tag, start: off, hdr, len: l, end, raw: buf.subarray(off, end), content: buf.subarray(off + hdr, end) };
|
||||
}
|
||||
|
||||
/** Toate elementele din continutul unui element construit (SEQUENCE, SET, [n]). */
|
||||
export function children(el) {
|
||||
const out = [];
|
||||
let o = 0;
|
||||
while (o < el.content.length) { const c = read(el.content, o); out.push(c); o = c.end; }
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Decodeaza un document DER intreg si refuza octetii in plus. */
|
||||
export function parse(buf) {
|
||||
const el = read(buf, 0);
|
||||
if (el.end !== buf.length) throw new Error('DER: ' + (buf.length - el.end) + ' octeti dupa structura');
|
||||
return el;
|
||||
}
|
||||
|
||||
export function expect(el, tag, what) {
|
||||
if (el.tag !== tag) throw new Error(`DER: ${what}: eticheta 0x${el.tag.toString(16)}, asteptat 0x${tag.toString(16)}`);
|
||||
return el;
|
||||
}
|
||||
|
||||
export function oidToString(el) {
|
||||
expect(el, TAG.OID, 'OID');
|
||||
const b = el.content;
|
||||
if (b.length === 0) throw new Error('DER: OID gol');
|
||||
if (b[b.length - 1] & 0x80) throw new Error('DER: OID trunchiat');
|
||||
// [A10] intai se citesc TOTI subidentificatorii in baza 128 (si primul poate avea mai multi octeti), abia apoi primul se desparte in
|
||||
// arc si al doilea numar: sub 80 arcul e catul impartirii la 40, de la 80 in sus arcul e 2 (X.690 8.19.4). Un octet 0x80 la inceputul
|
||||
// unui subidentificator e o codificare necanonica si se refuza.
|
||||
const subs = []; let v = 0n, inceput = true;
|
||||
for (let i = 0; i < b.length; i++) {
|
||||
if (inceput && b[i] === 0x80) throw new Error('DER: OID necanonic');
|
||||
v = (v << 7n) | BigInt(b[i] & 0x7f); inceput = false;
|
||||
if ((b[i] & 0x80) === 0) { subs.push(v); v = 0n; inceput = true; }
|
||||
}
|
||||
const first = subs[0];
|
||||
const arc = first < 80n ? first / 40n : 2n;
|
||||
return [arc, first - arc * 40n, ...subs.slice(1)].map(String).join('.');
|
||||
}
|
||||
|
||||
export function intToBigInt(el) {
|
||||
expect(el, TAG.INTEGER, 'INTEGER');
|
||||
const b = el.content;
|
||||
if (b.length === 0) throw new Error('DER: INTEGER gol');
|
||||
if (b.length > 1 && ((b[0] === 0 && (b[1] & 0x80) === 0) || (b[0] === 0xff && (b[1] & 0x80)))) throw new Error('DER: INTEGER necanonic');
|
||||
if (b[0] & 0x80) throw new Error('DER: INTEGER negativ');
|
||||
return BigInt('0x' + (b.toString('hex') || '0'));
|
||||
}
|
||||
|
||||
export function timeToDate(el) {
|
||||
const s = el.content.toString('ascii');
|
||||
let m;
|
||||
if (el.tag === TAG.UTC_TIME && (m = /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s))) {
|
||||
const yy = +m[1]; const y = yy >= 50 ? 1900 + yy : 2000 + yy;
|
||||
return new Date(Date.UTC(y, +m[2] - 1, +m[3], +m[4], +m[5], +m[6]));
|
||||
}
|
||||
if (el.tag === TAG.GEN_TIME && (m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/.exec(s))) {
|
||||
return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]));
|
||||
}
|
||||
throw new Error('DER: timp in forma nepermisa de RFC 5280: ' + s);
|
||||
}
|
||||
|
||||
export function bitString(el) {
|
||||
expect(el, TAG.BIT_STRING, 'BIT STRING');
|
||||
if (el.content.length === 0) throw new Error('DER: BIT STRING gol');
|
||||
return { unused: el.content[0], bytes: el.content.subarray(1) };
|
||||
}
|
||||
+520
@@ -0,0 +1,520 @@
|
||||
// pki.mjs: autoritate de certificare post-cuantica privata. Emite certificate X.509 v3 semnate cu ML-DSA (FIPS 204, forma "pura",
|
||||
// context gol, cum cere RFC 9881 pentru certificate), liste de revocare v2 semnate la fel, si verifica un lant strict (RFC 5280, partea
|
||||
// de care are nevoie un TLS privat). Numai Node 24 + OpenSSL 3.5 (node:crypto), fara dependinte.
|
||||
// Ce NU face: certificate compuse (hibride clasic + PQ; sunt inca drafturi IETF), OCSP, constrangeri de nume, politici, liste delta sau
|
||||
// partiale (IDP). Numele se compara pe octeti (DER identic), nu prin normalizarea completa din RFC 5280: lanturile emise aici folosesc
|
||||
// aceeasi codificare.
|
||||
// Revizuirea adversariala din 2026-09-25 a gasit sapte defecte, reparate aici si marcate in cod cu [A1]..[A10]: cheia pe disc sub
|
||||
// PBKDF2 slab (A1), prima lista de revocare in loc de cea mai noua (A2), extensiile listei ignorate (A3), exceptie pe SPKI malformat si
|
||||
// frunza cu cheie de 10 octeti admisa (A5), EKU pe autoritati neaplicat (A6), prima ancora cu acelasi nume la reinnoirea radacinii (A7),
|
||||
// OID cu primul subidentificator pe mai multi octeti (A10, in der.mjs).
|
||||
import crypto from 'node:crypto';
|
||||
import * as D from './der.mjs';
|
||||
|
||||
export const ALG = {
|
||||
'ml-dsa-44': '2.16.840.1.101.3.4.3.17',
|
||||
'ml-dsa-65': '2.16.840.1.101.3.4.3.18',
|
||||
'ml-dsa-87': '2.16.840.1.101.3.4.3.19',
|
||||
};
|
||||
const ALG_BY_OID = Object.fromEntries(Object.entries(ALG).map(([k, v]) => [v, k]));
|
||||
/** [A5] lungimea cheii publice ML-DSA, FIPS 204 tabelul 2: o cheie de alta lungime nu e o cheie, oricare ar fi OID-ul de deasupra ei. */
|
||||
export const PK_LEN = { 'ml-dsa-44': 1312, 'ml-dsa-65': 1952, 'ml-dsa-87': 2592 };
|
||||
const OID = {
|
||||
CN: '2.5.4.3', O: '2.5.4.10',
|
||||
basicConstraints: '2.5.29.19', keyUsage: '2.5.29.15', extKeyUsage: '2.5.29.37', subjectAltName: '2.5.29.17',
|
||||
subjectKeyIdentifier: '2.5.29.14', authorityKeyIdentifier: '2.5.29.35', crlNumber: '2.5.29.20',
|
||||
issuingDistributionPoint: '2.5.29.28', deltaCRLIndicator: '2.5.29.27',
|
||||
serverAuth: '1.3.6.1.5.5.7.3.1', clientAuth: '1.3.6.1.5.5.7.3.2',
|
||||
};
|
||||
const KU = { digitalSignature: 0, keyCertSign: 5, cRLSign: 6 };
|
||||
const EXT_STIUTE = new Set([OID.basicConstraints, OID.keyUsage, OID.extKeyUsage, OID.subjectAltName, OID.subjectKeyIdentifier, OID.authorityKeyIdentifier]);
|
||||
/** [A3] extensii de CRL pe care le intelegem (AKI, crlNumber) si extensii care schimba INTELESUL listei si pe care le refuzam oricum ar fi
|
||||
* marcate: o lista delta sau una cu punct de distributie (partiala, indirecta, numai CA, numai anumite motive) nu acopera ce pare sa acopere. */
|
||||
const CRL_EXT_STIUTE = new Set([OID.authorityKeyIdentifier, OID.crlNumber]);
|
||||
const CRL_EXT_REFUZATE = { [OID.issuingDistributionPoint]: 'issuingDistributionPoint', [OID.deltaCRLIndicator]: 'deltaCRLIndicator' };
|
||||
|
||||
export class PkiError extends Error { constructor(code, msg) { super(msg); this.code = code; } }
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ chei
|
||||
|
||||
export function generateKey(alg) {
|
||||
if (!ALG[alg]) throw new PkiError('ALG', 'unsupported algorithm ' + alg + ' (ml-dsa-44, ml-dsa-65, ml-dsa-87)');
|
||||
return crypto.generateKeyPairSync(alg);
|
||||
}
|
||||
|
||||
// [A1] Sigilarea proprie a cheii pe disc. PKCS#8 cifrat de Node (key.export cu cipher) foloseste PBKDF2 cu 2048 de iteratii, masurat la
|
||||
// 3-5 ms per incercare de parola, adica o parola de 12 caractere se incearca de sute de ori pe secunda pe un singur fir. Aici cheia de
|
||||
// cifrare vine din scrypt (N=2^17, r=8, p=1: 128 MiB de memorie si ~1 s per incercare pe un laptop, masurat in proba), iar DER-ul PKCS#8
|
||||
// e cifrat cu AES-256-GCM, cu antetul (versiunea formatului si toti parametrii) legat ca AAD: un octet schimbat in antet sau in text
|
||||
// strica eticheta de autentificare, deci "parola gresita" si "fisier atins" au acelasi raspuns, KEY_LOCKED.
|
||||
// AerePqPkiKey ::= SEQUENCE { header SEQUENCE { version INTEGER (1), kdf UTF8String "scrypt", salt OCTET STRING (16), N INTEGER,
|
||||
// r INTEGER, p INTEGER, cipher UTF8String "aes-256-gcm", iv OCTET STRING (12) }, tag OCTET STRING (16),
|
||||
// ciphertext OCTET STRING (PKCS#8 DER cifrat) }
|
||||
// scris PEM sub eticheta KEY_LABEL. PKCS#8 clasic (cifrat sau nu) NU mai e acceptat de pe disc.
|
||||
export const KEY_LABEL = 'AERE PQ PKI PRIVATE KEY';
|
||||
export const SEAL = Object.freeze({ version: 1, kdf: 'scrypt', N: 2 ** 17, r: 8, p: 1, cipher: 'aes-256-gcm', saltLen: 16, ivLen: 12, tagLen: 16, maxmem: 256 * 1024 * 1024 });
|
||||
const SEAL_N_MIN = 2 ** 14, SEAL_N_MAX = 2 ** 20; // la citire: sub 2^14 e prea slab ca sa fi fost scris de noi, peste 2^20 ar cere peste 1 GiB
|
||||
/** Parole pe care orice dictionar le incearca primele; comparate dupa ce se scot cifrele si semnele de la coada. */
|
||||
const PAROLE_EVIDENTE = new Set(['password', 'passw0rd', 'passphrase', 'qwerty', 'qwertyuiop', '123456', '12345678', '123456789', '1234567890',
|
||||
'iloveyou', 'letmein', 'welcome', 'admin', 'administrator', 'abc123', 'monkey', 'dragon', 'secret', 'changeme', 'default']);
|
||||
|
||||
/** [A1] Politica de parola: cel putin 12 caractere; cel putin 3 clase (minuscule, majuscule, cifre, altele) sau cel putin 20 de caractere;
|
||||
* nu toate caracterele identice; nu o parola evidenta (cu sau fara cifre/semne la coada). Arunca PkiError('PASSPHRASE'). */
|
||||
export function checkPassphrase(p) {
|
||||
if (typeof p !== 'string' || p.length < 12) throw new PkiError('PASSPHRASE', 'the passphrase needs at least 12 characters');
|
||||
const clase = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((re) => re.test(p)).length;
|
||||
if (clase < 3 && p.length < 20) throw new PkiError('PASSPHRASE', 'the passphrase needs 3 character classes (lower, upper, digit, other) or at least 20 characters');
|
||||
if (/^(.)\1*$/s.test(p)) throw new PkiError('PASSPHRASE', 'a passphrase made of one repeated character is refused');
|
||||
const nucleu = p.toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
if (PAROLE_EVIDENTE.has(nucleu) || PAROLE_EVIDENTE.has(nucleu.replace(/[0-9]+$/, ''))) throw new PkiError('PASSPHRASE', 'this passphrase is on every attacker\'s first list');
|
||||
return p;
|
||||
}
|
||||
|
||||
const sealHeader = (salt, N, r, p, iv) => D.seq(D.int(SEAL.version), D.utf8(SEAL.kdf), D.octets(salt), D.int(N), D.int(r), D.int(p), D.utf8(SEAL.cipher), D.octets(iv));
|
||||
|
||||
export function exportPrivateKey(key, passphrase) {
|
||||
checkPassphrase(passphrase);
|
||||
algOfKey(key);
|
||||
const salt = crypto.randomBytes(SEAL.saltLen), iv = crypto.randomBytes(SEAL.ivLen);
|
||||
const header = sealHeader(salt, SEAL.N, SEAL.r, SEAL.p, iv);
|
||||
const kek = crypto.scryptSync(passphrase, salt, 32, { N: SEAL.N, r: SEAL.r, p: SEAL.p, maxmem: SEAL.maxmem });
|
||||
const plain = key.export({ type: 'pkcs8', format: 'der' });
|
||||
const c = crypto.createCipheriv(SEAL.cipher, kek, iv, { authTagLength: SEAL.tagLen });
|
||||
c.setAAD(header);
|
||||
const ct = Buffer.concat([c.update(plain), c.final()]);
|
||||
const tag = c.getAuthTag();
|
||||
plain.fill(0); kek.fill(0);
|
||||
return pem(KEY_LABEL, D.seq(header, D.octets(tag), D.octets(ct)));
|
||||
}
|
||||
|
||||
/** Citeste antetul unei chei sigilate fara sa o deschida (parametrii KDF, ca sa poata fi masurati). Arunca PkiError('KEY_FORMAT'). */
|
||||
export function readSealedKeyHeader(pemText) {
|
||||
const blobs = unpem(pemText, KEY_LABEL);
|
||||
if (blobs.length !== 1) {
|
||||
if (/-----BEGIN (ENCRYPTED )?PRIVATE KEY-----/.test(pemText)) throw new PkiError('KEY_FORMAT', 'this is a PKCS#8 key; private keys are accepted only in the sealed "' + KEY_LABEL + '" format (scrypt + AES-256-GCM)');
|
||||
throw new PkiError('KEY_FORMAT', 'expected exactly one "' + KEY_LABEL + '" block');
|
||||
}
|
||||
let h;
|
||||
try {
|
||||
const [hdr, tagEl, ctEl, ...rest] = D.children(D.expect(D.parse(blobs[0]), D.TAG.SEQUENCE, 'sealed key'));
|
||||
if (rest.length || !ctEl) throw new Error('three parts expected');
|
||||
const [ver, kdf, salt, N, r, p, cipher, iv, ...hr] = D.children(D.expect(hdr, D.TAG.SEQUENCE, 'header'));
|
||||
if (hr.length || !iv) throw new Error('eight header fields expected');
|
||||
h = {
|
||||
version: Number(D.intToBigInt(ver)), kdf: D.expect(kdf, D.TAG.UTF8, 'kdf').content.toString('utf8'),
|
||||
salt: Buffer.from(D.expect(salt, D.TAG.OCTET_STRING, 'salt').content), N: Number(D.intToBigInt(N)), r: Number(D.intToBigInt(r)), p: Number(D.intToBigInt(p)),
|
||||
cipher: D.expect(cipher, D.TAG.UTF8, 'cipher').content.toString('utf8'), iv: Buffer.from(D.expect(iv, D.TAG.OCTET_STRING, 'iv').content),
|
||||
tag: Buffer.from(D.expect(tagEl, D.TAG.OCTET_STRING, 'tag').content), ct: Buffer.from(D.expect(ctEl, D.TAG.OCTET_STRING, 'ciphertext').content), aad: Buffer.from(hdr.raw),
|
||||
};
|
||||
} catch (e) { throw new PkiError('KEY_FORMAT', 'sealed key: ' + e.message); }
|
||||
if (h.version !== SEAL.version || h.kdf !== SEAL.kdf || h.cipher !== SEAL.cipher) throw new PkiError('KEY_FORMAT', `sealed key: unknown format (version ${h.version}, ${h.kdf}, ${h.cipher})`);
|
||||
if (h.salt.length !== SEAL.saltLen || h.iv.length !== SEAL.ivLen || h.tag.length !== SEAL.tagLen) throw new PkiError('KEY_FORMAT', 'sealed key: salt, iv or tag of the wrong length');
|
||||
if (!Number.isInteger(h.N) || h.N < SEAL_N_MIN || h.N > SEAL_N_MAX || (h.N & (h.N - 1)) !== 0 || !(h.r >= 1 && h.r <= 32) || !(h.p >= 1 && h.p <= 16)) throw new PkiError('KEY_FORMAT', `sealed key: scrypt parameters out of range (N=${h.N}, r=${h.r}, p=${h.p})`);
|
||||
return h;
|
||||
}
|
||||
|
||||
export function importPrivateKey(pemText, passphrase) {
|
||||
const h = readSealedKeyHeader(pemText);
|
||||
if (typeof passphrase !== 'string' || !passphrase) throw new PkiError('KEY_LOCKED', 'the private key could not be opened (missing or wrong passphrase)');
|
||||
let kek;
|
||||
try { kek = crypto.scryptSync(passphrase, h.salt, 32, { N: h.N, r: h.r, p: h.p, maxmem: SEAL.maxmem }); }
|
||||
catch (e) { throw new PkiError('KEY_FORMAT', 'sealed key: scrypt refused the parameters (' + e.message + ')'); }
|
||||
let plain;
|
||||
try {
|
||||
const d = crypto.createDecipheriv(SEAL.cipher, kek, h.iv, { authTagLength: SEAL.tagLen });
|
||||
d.setAAD(h.aad); d.setAuthTag(h.tag);
|
||||
plain = Buffer.concat([d.update(h.ct), d.final()]);
|
||||
} catch { throw new PkiError('KEY_LOCKED', 'the private key could not be opened (missing or wrong passphrase)'); }
|
||||
finally { kek.fill(0); }
|
||||
try {
|
||||
const key = crypto.createPrivateKey({ key: plain, format: 'der', type: 'pkcs8' });
|
||||
algOfKey(key);
|
||||
return key;
|
||||
} catch (e) { throw new PkiError(e.code === 'ALG' ? 'ALG' : 'KEY_FORMAT', 'sealed key: the content is not an ML-DSA PKCS#8 key'); }
|
||||
finally { plain.fill(0); }
|
||||
}
|
||||
|
||||
function algOfKey(k) {
|
||||
const t = k.asymmetricKeyType;
|
||||
if (!ALG[t]) throw new PkiError('ALG', 'key type ' + t + ' is not ML-DSA');
|
||||
return t;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ constructie
|
||||
|
||||
const algId = (alg) => D.seq(D.oid(ALG[alg])); // RFC 9881: parametrii LIPSESC
|
||||
export function name({ cn, o }) {
|
||||
const rdn = (oid, v) => D.set(D.seq(D.oid(oid), D.utf8(v)));
|
||||
return D.seq(o ? rdn(OID.O, o) : null, rdn(OID.CN, cn));
|
||||
}
|
||||
function keyUsageBits(names) {
|
||||
let v = 0, hi = -1;
|
||||
for (const n of names) { const b = KU[n]; v |= 0x80 >> b; hi = Math.max(hi, b); }
|
||||
const bytes = Buffer.from([v & 0xff]);
|
||||
const unused = 7 - hi; // biti ramasi neinsemnati dupa cel mai mare bit pus (DER: fara biti zero la coada)
|
||||
return D.bits(bytes, unused);
|
||||
}
|
||||
const ext = (oid, critical, valueDer) => D.seq(D.oid(oid), critical ? D.bool(true) : null, D.octets(valueDer));
|
||||
function keyId(spkiDer) {
|
||||
const spki = D.parse(spkiDer); const [, pk] = D.children(spki);
|
||||
return crypto.createHash('sha256').update(D.bitString(pk).bytes).digest().subarray(0, 20); // RFC 7093 metoda 1
|
||||
}
|
||||
|
||||
function randomSerial() {
|
||||
const b = crypto.randomBytes(16);
|
||||
b[0] &= 0x7f; if (b[0] === 0) b[0] = 1;
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emite un certificat. issuer = { cert (DER) , key (KeyObject privat) } sau null pentru o radacina auto-semnata.
|
||||
* opts: { subject: {cn, o}, publicKey (KeyObject), ca: bool, pathLen?: int, days, dns?: [], ips?: [], eku?: ['serverAuth','clientAuth'], notBefore? }
|
||||
*/
|
||||
export function issue({ issuer, signingKey, subject, publicKey, ca = false, pathLen, days, dns = [], ips = [], eku = [], notBefore }) {
|
||||
const alg = algOfKey(signingKey);
|
||||
algOfKey(publicKey);
|
||||
const spki = publicKey.export({ type: 'spki', format: 'der' });
|
||||
const ski = keyId(spki);
|
||||
const ic = issuer ? parseCert(issuer) : null;
|
||||
const signerSpki = crypto.createPublicKey(signingKey).export({ type: 'spki', format: 'der' });
|
||||
if (ic) {
|
||||
if (!ic.isCA || !ic.keyUsage.has('keyCertSign')) throw new PkiError('ISSUER', 'the issuer certificate is not a CA with keyCertSign');
|
||||
if (!signerSpki.equals(ic.spki)) throw new PkiError('ISSUER', 'the signing key does not belong to the issuer certificate');
|
||||
if (!ic.ski) throw new PkiError('ISSUER', 'the issuer certificate has no subject key identifier');
|
||||
} else if (!signerSpki.equals(spki)) throw new PkiError('ISSUER', 'a self-signed root is signed by its own key');
|
||||
const issuerName = ic ? ic.subjectRaw : name(subject);
|
||||
const aki = ic ? ic.ski : null;
|
||||
const nb = notBefore ? new Date(notBefore) : new Date(Date.now() - 60 * 1000);
|
||||
const na = new Date(nb.getTime() + days * 86400 * 1000);
|
||||
const exts = [
|
||||
ext(OID.basicConstraints, true, D.seq(ca ? D.bool(true) : null, ca && Number.isInteger(pathLen) ? D.int(pathLen) : null)),
|
||||
ext(OID.keyUsage, true, keyUsageBits(ca ? ['digitalSignature', 'keyCertSign', 'cRLSign'] : ['digitalSignature'])),
|
||||
eku.length ? ext(OID.extKeyUsage, false, D.seq(...eku.map((e) => D.oid(OID[e])))) : null,
|
||||
dns.length || ips.length ? ext(OID.subjectAltName, false, D.seq(
|
||||
...dns.map((d) => D.tlv(0x82, Buffer.from(d, 'ascii'))),
|
||||
...ips.map((ip) => D.tlv(0x87, ipBytes(ip))))) : null,
|
||||
ext(OID.subjectKeyIdentifier, false, D.octets(ski)),
|
||||
aki ? ext(OID.authorityKeyIdentifier, false, D.seq(D.tlv(0x80, aki))) : null,
|
||||
].filter(Boolean);
|
||||
const tbs = D.seq(
|
||||
D.ctx(0, D.int(2)), D.int(randomSerial()), algId(alg), issuerName,
|
||||
D.seq(D.time(nb), D.time(na)), name(subject), spki,
|
||||
D.ctx(3, D.seq(...exts)));
|
||||
const sig = crypto.sign(null, tbs, signingKey);
|
||||
return D.seq(tbs, algId(alg), D.bits(sig));
|
||||
}
|
||||
|
||||
function ipBytes(ip) {
|
||||
const p = ip.split('.').map(Number);
|
||||
if (p.length !== 4 || p.some((x) => !(x >= 0 && x <= 255))) throw new PkiError('SAN', 'only IPv4 addresses are supported: ' + ip);
|
||||
return Buffer.from(p);
|
||||
}
|
||||
|
||||
/** Lista de revocare v2. revoked = [{ serial (Buffer sau hex), date }]; number = numarul CRL-ului (crescator). */
|
||||
export function crl({ issuer, signingKey, revoked = [], days, number, thisUpdate }) {
|
||||
const alg = algOfKey(signingKey);
|
||||
const c = parseCert(issuer);
|
||||
if (!c.isCA || !c.keyUsage.has('cRLSign')) throw new PkiError('ISSUER', 'the issuer may not sign revocation lists');
|
||||
const tu = thisUpdate ? new Date(thisUpdate) : new Date(Date.now() - 60 * 1000);
|
||||
const nu = new Date(tu.getTime() + days * 86400 * 1000);
|
||||
const rev = revoked.map((r) => D.seq(D.int(Buffer.isBuffer(r.serial) ? r.serial : Buffer.from(r.serial, 'hex')), D.time(new Date(r.date))));
|
||||
const tbs = D.seq(D.int(1), algId(alg), c.subjectRaw, D.time(tu), D.time(nu), rev.length ? D.seq(...rev) : null,
|
||||
D.ctx(0, D.seq(ext(OID.authorityKeyIdentifier, false, D.seq(D.tlv(0x80, c.ski))), ext(OID.crlNumber, false, D.int(number)))));
|
||||
return D.seq(tbs, algId(alg), D.bits(crypto.sign(null, tbs, signingKey)));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ citire
|
||||
|
||||
/** Extensions ::= SEQUENCE OF Extension { extnID OID, critical BOOLEAN DEFAULT FALSE, extnValue OCTET STRING }, cu forma DER ceruta. */
|
||||
function parseExtensions(seqEl, what) {
|
||||
const exts = new Map();
|
||||
for (const x of D.children(D.expect(seqEl, D.TAG.SEQUENCE, what))) {
|
||||
const xs = D.children(D.expect(x, D.TAG.SEQUENCE, 'Extension'));
|
||||
const id = D.oidToString(xs[0]);
|
||||
let critical = false, val;
|
||||
if (xs.length === 3) { if (xs[1].tag !== D.TAG.BOOLEAN || xs[1].content[0] !== 0xff) throw new PkiError('DER', 'critical must be TRUE when present (DER)'); critical = true; val = xs[2]; }
|
||||
else if (xs.length === 2) val = xs[1];
|
||||
else throw new PkiError('DER', 'an Extension has two or three parts');
|
||||
if (exts.has(id)) throw new PkiError('EXT_DUP', 'extension ' + id + ' appears twice');
|
||||
exts.set(id, { critical, value: D.expect(val, D.TAG.OCTET_STRING, 'extnValue').content });
|
||||
}
|
||||
return exts;
|
||||
}
|
||||
|
||||
export function parseCert(der) {
|
||||
const top = D.parse(der);
|
||||
D.expect(top, D.TAG.SEQUENCE, 'certificat');
|
||||
const [tbsEl, algEl, sigEl, ...rest] = D.children(top);
|
||||
if (rest.length || !sigEl) throw new PkiError('DER', 'a certificate has exactly three parts');
|
||||
const t = D.children(D.expect(tbsEl, D.TAG.SEQUENCE, 'tbsCertificate'));
|
||||
let i = 0;
|
||||
if (!t[i] || t[i].tag !== 0xa0) throw new PkiError('VERSION', 'only X.509 v3 certificates are accepted');
|
||||
const ver = D.intToBigInt(D.children(t[i++])[0]);
|
||||
if (ver !== 2n) throw new PkiError('VERSION', 'only X.509 v3 certificates are accepted');
|
||||
if (t.length < 7) throw new PkiError('DER', 'tbsCertificate is missing fields');
|
||||
const serial = t[i++].content;
|
||||
D.intToBigInt(t[i - 1]); // forma canonica si pozitiva (RFC 5280 4.1.2.2)
|
||||
const innerAlg = sigAlgOf(t[i++]);
|
||||
const issuerRaw = D.expect(t[i++], D.TAG.SEQUENCE, 'issuer').raw;
|
||||
const [nbEl, naEl] = D.children(D.expect(t[i++], D.TAG.SEQUENCE, 'validity'));
|
||||
if (!naEl) throw new PkiError('DER', 'validity has two times');
|
||||
const subjectRaw = D.expect(t[i++], D.TAG.SEQUENCE, 'subject').raw;
|
||||
const spkiEl = D.expect(t[i++], D.TAG.SEQUENCE, 'subjectPublicKeyInfo');
|
||||
// [A5] cheia publica se valideaza la citire: doua parti, BIT STRING fara biti nefolositi, si lungimea FIPS 204 a algoritmului declarat.
|
||||
// Fara asta o frunza cu o "cheie" de 10 octeti sub id-ml-dsa-65 trecea verificarea lantului (verificatorul nu foloseste cheia frunzei),
|
||||
// iar un intermediar cu aceeasi cheie arunca o exceptie din node:crypto in loc de un verdict.
|
||||
const spkiKids = D.children(spkiEl);
|
||||
if (spkiKids.length !== 2) throw new PkiError('SPKI', 'subjectPublicKeyInfo has two parts');
|
||||
const pkAlg = sigAlgOf(spkiKids[0]);
|
||||
const pkBits = D.bitString(spkiKids[1]);
|
||||
if (pkBits.unused !== 0 || pkBits.bytes.length !== PK_LEN[pkAlg]) throw new PkiError('SPKI', `the ${pkAlg} public key must be ${PK_LEN[pkAlg]} bytes, this one has ${pkBits.bytes.length}`);
|
||||
let exts = new Map();
|
||||
while (i < t.length) {
|
||||
const e = t[i++];
|
||||
if (e.tag === 0xa1 || e.tag === 0xa2) throw new PkiError('UNIQUE_ID', 'unique identifiers are not accepted');
|
||||
if (e.tag !== 0xa3 || exts.size) throw new PkiError('DER', 'unexpected field in tbsCertificate');
|
||||
const inner = D.children(e);
|
||||
if (inner.length !== 1) throw new PkiError('DER', 'extensions [3] wraps exactly one SEQUENCE');
|
||||
exts = parseExtensions(inner[0], 'extensions');
|
||||
}
|
||||
const outerAlg = sigAlgOf(algEl);
|
||||
if (outerAlg !== innerAlg) throw new PkiError('ALG_MISMATCH', 'the outer signature algorithm differs from the one inside the certificate');
|
||||
const sig = D.bitString(sigEl);
|
||||
if (sig.unused !== 0) throw new PkiError('DER', 'signature bit string has unused bits');
|
||||
const c = {
|
||||
der: Buffer.from(der), tbs: tbsEl.raw, alg: innerAlg, pkAlg, signature: sig.bytes, serial: Buffer.from(serial),
|
||||
issuerRaw: Buffer.from(issuerRaw), subjectRaw: Buffer.from(subjectRaw), spki: Buffer.from(spkiEl.raw),
|
||||
notBefore: D.timeToDate(nbEl), notAfter: D.timeToDate(naEl), exts,
|
||||
isCA: false, pathLen: undefined, keyUsage: new Set(), eku: null, dns: [], ips: [], ski: null, aki: null, unknownCritical: [],
|
||||
};
|
||||
for (const [id, x] of exts) if (x.critical && !EXT_STIUTE.has(id)) c.unknownCritical.push(id);
|
||||
const bc = exts.get(OID.basicConstraints);
|
||||
if (bc) {
|
||||
const f = D.children(D.parse(bc.value));
|
||||
if (f[0] && f[0].tag === D.TAG.BOOLEAN) { c.isCA = f[0].content[0] === 0xff; if (!c.isCA) throw new PkiError('DER', 'cA FALSE must be absent (DER)'); f.shift(); }
|
||||
if (f[0]) c.pathLen = Number(D.intToBigInt(f[0]));
|
||||
}
|
||||
const ku = exts.get(OID.keyUsage);
|
||||
if (ku) {
|
||||
const b = D.bitString(D.parse(ku.value));
|
||||
for (const [n, bit] of Object.entries(KU)) if (b.bytes.length > (bit >> 3) && (b.bytes[bit >> 3] & (0x80 >> (bit & 7)))) c.keyUsage.add(n);
|
||||
}
|
||||
const ek = exts.get(OID.extKeyUsage);
|
||||
if (ek) c.eku = new Set(D.children(D.parse(ek.value)).map((o) => D.oidToString(o)));
|
||||
const san = exts.get(OID.subjectAltName);
|
||||
if (san) for (const g of D.children(D.parse(san.value))) {
|
||||
if (g.tag === 0x82) c.dns.push(g.content.toString('ascii').toLowerCase());
|
||||
else if (g.tag === 0x87 && g.content.length === 4) c.ips.push([...g.content].join('.'));
|
||||
}
|
||||
const s = exts.get(OID.subjectKeyIdentifier);
|
||||
if (s) c.ski = Buffer.from(D.expect(D.parse(s.value), D.TAG.OCTET_STRING, 'SKI').content);
|
||||
const a = exts.get(OID.authorityKeyIdentifier);
|
||||
if (a) { const k = D.children(D.parse(a.value)).find((x) => x.tag === 0x80); if (k) c.aki = Buffer.from(k.content); }
|
||||
return c;
|
||||
}
|
||||
|
||||
function sigAlgOf(el) {
|
||||
const f = D.children(D.expect(el, D.TAG.SEQUENCE, 'AlgorithmIdentifier'));
|
||||
if (!f.length) throw new PkiError('DER', 'empty AlgorithmIdentifier');
|
||||
const o = D.oidToString(f[0]);
|
||||
if (!ALG_BY_OID[o]) throw new PkiError('ALG', 'algorithm ' + o + ' is not ML-DSA');
|
||||
if (f.length !== 1) throw new PkiError('ALG_PARAMS', 'ML-DSA AlgorithmIdentifier must have no parameters (RFC 9881)');
|
||||
return ALG_BY_OID[o];
|
||||
}
|
||||
|
||||
const isTime = (el) => el && (el.tag === D.TAG.UTC_TIME || el.tag === D.TAG.GEN_TIME);
|
||||
|
||||
/**
|
||||
* Citeste o lista de revocare v2. Intoarce { tbs, alg, signature, issuerRaw, thisUpdate, nextUpdate, revoked (Map serialHex -> Date),
|
||||
* crlNumber (BigInt|null), aki (Buffer|null), refusedExt (string|null), exts }. [A3] Extensiile listei si ale intrarilor sunt citite:
|
||||
* AKI si crlNumber sunt intelese; issuingDistributionPoint si deltaCRLIndicator sunt REFUZATE oricum ar fi marcate, si la fel orice alta
|
||||
* extensie critica (a listei sau a unei intrari). Refuzul nu e exceptie: sta in refusedExt, si verifyChain il face verdict CRL_EXT, ca o
|
||||
* lista straina cu o extensie rea sa nu opreasca verificarea unui lant pe care nu il priveste.
|
||||
*/
|
||||
export function parseCrl(der) {
|
||||
const top = D.parse(der);
|
||||
const [tbsEl, algEl, sigEl, ...rest] = D.children(D.expect(top, D.TAG.SEQUENCE, 'CRL'));
|
||||
if (rest.length || !sigEl) throw new PkiError('DER', 'a revocation list has exactly three parts');
|
||||
const t = D.children(D.expect(tbsEl, D.TAG.SEQUENCE, 'tbsCertList'));
|
||||
let i = 0;
|
||||
if (!t[i] || t[i].tag !== D.TAG.INTEGER || D.intToBigInt(t[i++]) !== 1n) throw new PkiError('VERSION', 'only v2 revocation lists are accepted');
|
||||
const innerAlg = sigAlgOf(t[i++]);
|
||||
const issuerRaw = D.expect(t[i++], D.TAG.SEQUENCE, 'issuer').raw;
|
||||
if (!isTime(t[i])) throw new PkiError('DER', 'thisUpdate missing');
|
||||
const thisUpdate = D.timeToDate(t[i++]);
|
||||
let nextUpdate = null;
|
||||
if (isTime(t[i])) nextUpdate = D.timeToDate(t[i++]);
|
||||
const revoked = new Map();
|
||||
let refusedExt = null;
|
||||
const refuza = (what) => { if (!refusedExt) refusedExt = what; };
|
||||
if (t[i] && t[i].tag === D.TAG.SEQUENCE) {
|
||||
for (const r of D.children(t[i++])) {
|
||||
const [s, d, ee, ...er] = D.children(D.expect(r, D.TAG.SEQUENCE, 'revoked entry'));
|
||||
if (!d || er.length) throw new PkiError('DER', 'a revoked entry has two or three parts');
|
||||
D.intToBigInt(s); // seria, in forma canonica
|
||||
if (!isTime(d)) throw new PkiError('DER', 'revocation date missing');
|
||||
revoked.set(s.content.toString('hex'), D.timeToDate(d));
|
||||
if (ee) for (const [id, x] of parseExtensions(ee, 'crlEntryExtensions')) if (x.critical) refuza(`a critical entry extension ${id}`); // reasonCode, invalidityDate: necritice, ignorate
|
||||
}
|
||||
}
|
||||
let exts = new Map(), crlNumber = null, aki = null;
|
||||
if (t[i] && t[i].tag === 0xa0) {
|
||||
const inner = D.children(t[i++]);
|
||||
if (inner.length !== 1) throw new PkiError('DER', 'crlExtensions [0] wraps exactly one SEQUENCE');
|
||||
exts = parseExtensions(inner[0], 'crlExtensions');
|
||||
for (const [id, x] of exts) {
|
||||
if (CRL_EXT_REFUZATE[id]) refuza(`${CRL_EXT_REFUZATE[id]} (${id}); delta and partial lists are not supported`);
|
||||
else if (x.critical && !CRL_EXT_STIUTE.has(id)) refuza(`an unknown critical extension ${id}`);
|
||||
}
|
||||
const n = exts.get(OID.crlNumber);
|
||||
if (n) crlNumber = D.intToBigInt(D.parse(n.value));
|
||||
const a = exts.get(OID.authorityKeyIdentifier);
|
||||
if (a) { const k = D.children(D.parse(a.value)).find((x) => x.tag === 0x80); if (k) aki = Buffer.from(k.content); }
|
||||
}
|
||||
if (i !== t.length) throw new PkiError('DER', 'unexpected field in tbsCertList');
|
||||
if (sigAlgOf(algEl) !== innerAlg) throw new PkiError('ALG_MISMATCH', 'the outer signature algorithm differs from the one inside the list');
|
||||
const sig = D.bitString(sigEl);
|
||||
if (sig.unused !== 0) throw new PkiError('DER', 'signature bit string has unused bits');
|
||||
return { tbs: tbsEl.raw, alg: innerAlg, signature: sig.bytes, issuerRaw: Buffer.from(issuerRaw), thisUpdate, nextUpdate, revoked, crlNumber, aki, refusedExt, exts };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ verificare
|
||||
|
||||
/** [A5] Un SPKI pe care node:crypto nu il poate importa da PkiError('SPKI'), pe care verifyChain o face verdict; niciodata exceptie bruta. */
|
||||
function verifySig(tbs, signature, spkiDer, who) {
|
||||
let key;
|
||||
try { key = crypto.createPublicKey({ key: spkiDer, format: 'der', type: 'spki' }); }
|
||||
catch { throw new PkiError('SPKI', `the public key of "${who}" cannot be decoded`); }
|
||||
return crypto.verify(null, tbs, key, signature);
|
||||
}
|
||||
|
||||
function hostMatches(pattern, host) {
|
||||
if (pattern === host) return true;
|
||||
if (pattern.startsWith('*.')) { const rest = pattern.slice(2); const dot = host.indexOf('.'); return dot > 0 && host.slice(dot + 1) === rest; }
|
||||
return false;
|
||||
}
|
||||
|
||||
const MAX_ADANCIME = 8, MAX_DRUMURI = 32;
|
||||
const cmpBig = (a, b) => ((a ?? -1n) === (b ?? -1n) ? 0 : (a ?? -1n) > (b ?? -1n) ? 1 : -1);
|
||||
|
||||
/**
|
||||
* Verifica un lant: leaf (DER), intermediates [DER], roots [DER] (increderea), at (Date), purpose ('serverAuth'|'clientAuth'|null),
|
||||
* host (nume sau IPv4, pentru serverAuth), crls [DER], requireCrl (fiecare emitator din lant trebuie sa aiba o lista valabila).
|
||||
* Intoarce { ok, code, reason, chain: [subject CN...] }. Intoarce intotdeauna un verdict: pe orice octeti, niciodata exceptie [A5].
|
||||
*/
|
||||
export function verifyChain(opts) {
|
||||
try { return verifyChainInner(opts); }
|
||||
catch (e) { return { ok: false, code: e instanceof PkiError ? e.code : 'DER', reason: String(e && e.message || e) }; }
|
||||
}
|
||||
|
||||
function verifyChainInner({ leaf, intermediates = [], roots = [], at = new Date(), purpose = 'serverAuth', host = null, crls = [], requireCrl = false }) {
|
||||
const fail = (code, reason) => ({ ok: false, code, reason });
|
||||
let certs;
|
||||
try { certs = { leaf: parseCert(leaf), inter: intermediates.map(parseCert), roots: roots.map(parseCert) }; }
|
||||
catch (e) { return fail(e.code || 'DER', e.message); }
|
||||
const lists = [];
|
||||
try { for (const x of crls) lists.push(parseCrl(x)); } catch (e) { return fail(e.code || 'DER', 'revocation list: ' + e.message); }
|
||||
const emite = (p, c) => p.subjectRaw.equals(c.issuerRaw) && (!c.aki || (p.ski && p.ski.equals(c.aki)));
|
||||
|
||||
// 1. drumurile: de la frunza in sus, emitatorul e certificatul al carui subiect e egal (pe octeti) cu emitentul si al carui SKI e AKI-ul.
|
||||
// [A7] Se incearca TOATE candidatele (intai ancorele, apoi intermediarele, fara cicluri), si primul drum care trece intreg e raspunsul:
|
||||
// la reinnoirea radacinii operatorul are doua ancore cu acelasi nume si aceeasi cheie, una expirata, si "prima gasita" refuza un lant
|
||||
// valid; la fel cu un intermediar semnat incrucisat de o radacina straina, pus inaintea celui bun.
|
||||
let blocat = certs.leaf, blocatAdancime = -1, incercate = 0; // cel mai adanc certificat fara niciun emitent candidat (pentru mesajul UNTRUSTED)
|
||||
const stiva = [certs.leaf];
|
||||
function* drumuri(cur) {
|
||||
const ancore = certs.roots.filter((r) => emite(r, cur));
|
||||
for (const r of ancore) yield [...stiva, r];
|
||||
const inter = stiva.length < MAX_ADANCIME ? certs.inter.filter((c) => c !== cur && !stiva.includes(c) && emite(c, cur)) : [];
|
||||
for (const c of inter) { stiva.push(c); yield* drumuri(c); stiva.pop(); }
|
||||
if (!ancore.length && !inter.length && stiva.length - 1 > blocatAdancime) { blocat = cur; blocatAdancime = stiva.length - 1; }
|
||||
}
|
||||
let ultimul = null;
|
||||
for (const path of drumuri(certs.leaf)) {
|
||||
if (++incercate > MAX_DRUMURI) break;
|
||||
const r = judeca(path);
|
||||
if (r.ok) return r;
|
||||
ultimul = r;
|
||||
}
|
||||
if (ultimul) return ultimul;
|
||||
return fail('UNTRUSTED', 'no trusted issuer for "' + cnOf(blocat) + '"');
|
||||
|
||||
function judeca(path) {
|
||||
const top = path[path.length - 1];
|
||||
if (!top.subjectRaw.equals(top.issuerRaw) || !verifySig(top.tbs, top.signature, top.spki, cnOf(top))) return fail('ROOT', 'the trusted root is not a valid self-signed certificate');
|
||||
// 2. fiecare legatura
|
||||
for (let k = 0; k < path.length; k++) {
|
||||
const c = path[k];
|
||||
if (c.unknownCritical.length) return fail('CRITICAL_EXT', `"${cnOf(c)}" carries an unknown critical extension ${c.unknownCritical[0]}`);
|
||||
if (at < c.notBefore) return fail('NOT_YET_VALID', `"${cnOf(c)}" is not valid before ${c.notBefore.toISOString()}`);
|
||||
if (at > c.notAfter) return fail('EXPIRED', `"${cnOf(c)}" expired at ${c.notAfter.toISOString()}`);
|
||||
if (k === path.length - 1) break;
|
||||
const p = path[k + 1];
|
||||
if (!p.isCA) return fail('NOT_CA', `"${cnOf(p)}" is not a CA (basicConstraints) and cannot issue "${cnOf(c)}"`);
|
||||
if (!p.keyUsage.has('keyCertSign')) return fail('KEY_USAGE', `"${cnOf(p)}" has no keyCertSign`);
|
||||
const casBelow = path.slice(1, k + 1).filter((x) => x.isCA).length; // CA-urile intermediare de sub p, fara frunza
|
||||
if (p.pathLen !== undefined && casBelow > p.pathLen) return fail('PATH_LEN', `"${cnOf(p)}" allows ${p.pathLen} CA(s) below it, the chain has ${casBelow}`);
|
||||
// [A6] EKU pe o autoritate restrange tot ce e sub ea (OpenSSL, Chrome, Mozilla fac la fel); anyExtendedKeyUsage NU scuteste, ca la OpenSSL.
|
||||
if (purpose && p.eku && !p.eku.has(OID[purpose])) return fail('EKU', `the issuer "${cnOf(p)}" is not valid for ${purpose} (its extended key usage does not allow it)`);
|
||||
if (!verifySig(c.tbs, c.signature, p.spki, cnOf(c))) return fail('SIGNATURE', `the signature on "${cnOf(c)}" does not verify under "${cnOf(p)}"`);
|
||||
const rv = revocare(c, p);
|
||||
if (rv) return rv;
|
||||
}
|
||||
// 4. frunza
|
||||
const L = certs.leaf;
|
||||
if (purpose) {
|
||||
if (L.isCA) return fail('LEAF_IS_CA', 'a CA certificate is not accepted as an end-entity certificate');
|
||||
if (!L.keyUsage.has('digitalSignature')) return fail('KEY_USAGE', 'the end-entity certificate has no digitalSignature');
|
||||
if (L.eku && !L.eku.has(OID[purpose])) return fail('EKU', `the end-entity certificate is not valid for ${purpose}`);
|
||||
}
|
||||
if (host) {
|
||||
const h = host.toLowerCase();
|
||||
const ok = /^\d+\.\d+\.\d+\.\d+$/.test(h) ? L.ips.includes(h) : L.dns.some((d) => hostMatches(d, h));
|
||||
if (!ok) return fail('HOSTNAME', `"${cnOf(L)}" is not valid for ${host}`);
|
||||
}
|
||||
return { ok: true, code: 'OK', reason: 'valid', chain: path.map(cnOf) };
|
||||
}
|
||||
|
||||
// 3. revocarea lui c de catre emitatorul p. [A2] Dintre listele emitentului care VERIFICA sub cheia lui si nu sunt datate in viitor se
|
||||
// ia cea cu thisUpdate cel mai nou (la egalitate, crlNumber cel mai mare), cum face si OpenSSL; "prima din intrare" lasa o revocare
|
||||
// proaspata sa fie ascunsa de o lista veche pusa inaintea ei. [A3] O lista cu o extensie refuzata e verdict CRL_EXT, nu e sarita.
|
||||
function revocare(c, p) {
|
||||
const ale = lists.filter((l) => l.issuerRaw.equals(p.subjectRaw));
|
||||
if (!ale.length) return requireCrl ? fail('CRL_MISSING', `no revocation list from "${cnOf(p)}"`) : null;
|
||||
const verificate = ale.filter((l) => verifySig(l.tbs, l.signature, p.spki, cnOf(p)));
|
||||
if (!verificate.length) return fail('CRL_SIGNATURE', `the revocation list of "${cnOf(p)}" does not verify`);
|
||||
const rea = verificate.find((l) => l.refusedExt);
|
||||
if (rea) return fail('CRL_EXT', `the revocation list of "${cnOf(p)}" carries ${rea.refusedExt}`);
|
||||
const curente = verificate.filter((l) => at >= l.thisUpdate);
|
||||
if (!curente.length) return fail('CRL_STALE', `the revocation list of "${cnOf(p)}" is dated in the future`);
|
||||
curente.sort((a, b) => (b.thisUpdate - a.thisUpdate) || cmpBig(b.crlNumber, a.crlNumber));
|
||||
const list = curente[0];
|
||||
if (list.nextUpdate && at > list.nextUpdate) return fail('CRL_STALE', `the revocation list of "${cnOf(p)}" is not current (nextUpdate ${list.nextUpdate.toISOString()})`);
|
||||
if (list.revoked.has(c.serial.toString('hex'))) return fail('REVOKED', `"${cnOf(c)}" is revoked by "${cnOf(p)}"`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Semnatura unui certificat auto-semnat, verificata cu propria cheie (interoperabilitatea inversa: certificate facute de altii). */
|
||||
export function selfSignatureValid(der) {
|
||||
const c = parseCert(der);
|
||||
return c.subjectRaw.equals(c.issuerRaw) && verifySig(c.tbs, c.signature, c.spki, cnOf(c));
|
||||
}
|
||||
|
||||
export function cnOf(c) {
|
||||
try {
|
||||
for (const rdn of D.children(D.parse(c.subjectRaw))) for (const atv of D.children(rdn)) {
|
||||
const [o, v] = D.children(atv);
|
||||
if (D.oidToString(o) === OID.CN) return v.content.toString('utf8');
|
||||
}
|
||||
} catch { /* nume necitibil */ }
|
||||
return '?';
|
||||
}
|
||||
|
||||
export const pem = (label, der) => `-----BEGIN ${label}-----\n${der.toString('base64').match(/.{1,64}/g).join('\n')}\n-----END ${label}-----\n`;
|
||||
export function unpem(text, label = 'CERTIFICATE') {
|
||||
const re = new RegExp(`-----BEGIN ${label}-----([\\s\\S]*?)-----END ${label}-----`, 'g');
|
||||
const out = []; let m;
|
||||
while ((m = re.exec(text))) out.push(Buffer.from(m[1].replace(/\s+/g, ''), 'base64'));
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Controlul negativ al probei PKI: fiecare paznic din pki.mjs / der.mjs se strica pe rand, la RULARE (conditie falsa, ca sa compileze),
|
||||
// intr-o COPIE a modulului (pki.mjs, der.mjs, cli.mjs), iar proba, chemata cu PKI_MODULE pe copie, trebuie sa iasa ROSIE pe EXACT proba
|
||||
// numita. O ancora care nu apare o singura data e un ESEC al controlului, nu o trecere (ancorele stau pe partea STABILA a randului).
|
||||
// Martorul (proba pe original) ruleaza INTAI: din el se deriva numarul de probe pe care fiecare plantare trebuie sa il ruleze intreg
|
||||
// (nu e scris fix: o constanta de ieri minte in ziua in care suita creste). La sfarsit originalul trebuie sa fie identic (sha256).
|
||||
// Plantarile ruleaza cate PARALEL deodata (fiecare proba costa ~10 deschideri scrypt de ~0,7 s).
|
||||
// node test/control-negativ.mjs
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const AICI = path.dirname(fileURLToPath(import.meta.url));
|
||||
const SRC = path.join(AICI, '..');
|
||||
const PROBA = path.join(AICI, 'proba.mjs');
|
||||
const FISIERE = ['pki.mjs', 'der.mjs', 'cli.mjs'];
|
||||
const PARALEL = Math.max(1, Math.min(4, Number(process.env.PKI_PARALEL) || 4));
|
||||
const sha = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
|
||||
const inainte = Object.fromEntries(FISIERE.map((n) => [n, sha(path.join(SRC, n))]));
|
||||
|
||||
// [nume, fisier, ancora (exact o data), inlocuitor, prefixul probei care trebuie sa cada]
|
||||
const PLANTARI = [
|
||||
['semnatura oricum valida', 'pki.mjs', ' return crypto.verify(null, tbs, key, signature);', " return crypto.verify(null, tbs, key, signature) || Boolean(Number('1'));", 'un octet schimbat'],
|
||||
['pathLen ignorat', 'pki.mjs', 'if (p.pathLen !== undefined && casBelow > p.pathLen)', "if (p.pathLen !== undefined && casBelow > p.pathLen && Boolean(Number('0')))", 'pathLen'],
|
||||
['revocarea ignorata', 'pki.mjs', "if (list.revoked.has(c.serial.toString('hex')))", "if (list.revoked.has(c.serial.toString('hex')) && Boolean(Number('0')))", 'revocarea'],
|
||||
['emitentul fara basicConstraints CA', 'pki.mjs', " if (!p.isCA) return fail('NOT_CA'", " if (!p.isCA && Boolean(Number('0'))) return fail('NOT_CA'", 'un certificat de entitate folosit ca emitent'],
|
||||
['numele gazdei ignorat', 'pki.mjs', " if (!ok) return fail('HOSTNAME'", " if (!ok && Boolean(Number('0'))) return fail('HOSTNAME'", 'frunza pentru alt nume'],
|
||||
['expirarea ignorata', 'pki.mjs', " if (at > c.notAfter) return fail('EXPIRED'", " if (at > c.notAfter && Boolean(Number('0'))) return fail('EXPIRED'", 'timpul'],
|
||||
['parametri acceptati pe ML-DSA', 'pki.mjs', " if (f.length !== 1) throw new PkiError('ALG_PARAMS'", " if (f.length !== 1 && Boolean(Number('0'))) throw new PkiError('ALG_PARAMS'", 'forma'],
|
||||
['extensia critica necunoscuta ignorata', 'pki.mjs', ' for (const [id, x] of exts) if (x.critical && !EXT_STIUTE.has(id))', " for (const [id, x] of exts) if (x.critical && !EXT_STIUTE.has(id) && Boolean(Number('0')))", 'extensie critica necunoscuta'],
|
||||
['scopul (EKU) pe frunza ignorat', 'pki.mjs', ' if (L.eku && !L.eku.has(OID[purpose]))', " if (L.eku && !L.eku.has(OID[purpose]) && Boolean(Number('0')))", 'scopul'],
|
||||
['cheia privata scrisa in clar (PKCS#8)', 'pki.mjs', ' return pem(KEY_LABEL, D.seq(header, D.octets(tag), D.octets(ct)));', " return key.export({ type: 'pkcs8', format: 'pem' });", 'linia de comanda'],
|
||||
['DER necanonic acceptat', 'der.mjs', " if (l < 0x80) throw new Error('DER: lungime scurta scrisa in forma lunga (necanonica)');", " if (l < 0x80 && Boolean(Number('0'))) throw new Error('DER: lungime scurta scrisa in forma lunga (necanonica)');", 'forma'],
|
||||
// revizuirea din 2026-09-25
|
||||
['[A1] scrypt coborat la N=2^10', 'pki.mjs', 'N: 2 ** 17,', 'N: 2 ** 10,', 'sigilarea cheii'],
|
||||
['[A1] politica de parola redusa la 12 caractere (accepta aaaaaaaaaaaa)', 'pki.mjs', 'export function checkPassphrase(p) {', "export function checkPassphrase(p) { if (typeof p === 'string' && p.length >= 12 && Boolean(Number('1'))) return p;", 'politica de parola'],
|
||||
['[A1] parolele evidente acceptate', 'pki.mjs', " if (PAROLE_EVIDENTE.has(nucleu) || PAROLE_EVIDENTE.has(nucleu.replace(/[0-9]+$/, '')))", " if ((PAROLE_EVIDENTE.has(nucleu) || PAROLE_EVIDENTE.has(nucleu.replace(/[0-9]+$/, ''))) && Boolean(Number('0')))", 'politica de parola'],
|
||||
['[A2] prima lista din intrare in loc de cea mai noua', 'pki.mjs', ' curente.sort((a, b) => (b.thisUpdate - a.thisUpdate) || cmpBig(b.crlNumber, a.crlNumber));', ' curente.sort(() => 0);', 'cea mai noua lista'],
|
||||
['[A3] extensiile listei ignorate', 'pki.mjs', ' const rea = verificate.find((l) => l.refusedExt);', " const rea = verificate.find((l) => l.refusedExt && Boolean(Number('0')));", 'extensiile listei'],
|
||||
['[A5] lungimea cheii publice neverificata', 'pki.mjs', ' if (pkBits.unused !== 0 || pkBits.bytes.length !== PK_LEN[pkAlg])', " if ((pkBits.unused !== 0 || pkBits.bytes.length !== PK_LEN[pkAlg]) && Boolean(Number('0')))", 'cheie publica malformata'],
|
||||
['[A6] EKU pe autoritati ignorat', 'pki.mjs', ' if (purpose && p.eku && !p.eku.has(OID[purpose]))', " if (purpose && p.eku && !p.eku.has(OID[purpose]) && Boolean(Number('0')))", 'EKU pe autoritati'],
|
||||
['[A7] numai prima ancora candidata', 'pki.mjs', ' const ancore = certs.roots.filter((r) => emite(r, cur));', ' const ancore = certs.roots.filter((r) => emite(r, cur)).slice(0, 1);', 'reinnoirea radacinii'],
|
||||
['[A7] numai primul intermediar candidat', 'pki.mjs', 'certs.inter.filter((c) => c !== cur && !stiva.includes(c) && emite(c, cur)) : [];', 'certs.inter.filter((c) => c !== cur && !stiva.includes(c) && emite(c, cur)).slice(0, 1) : [];', 'reinnoirea radacinii'],
|
||||
['[A10] primul subidentificator OID scris pe un singur octet', 'der.mjs', ' const out = base128(p[0] * 40n + p[1]);', ' const out = [Number((p[0] * 40n + p[1]) & 0x7fn)];', 'OID'],
|
||||
['[A10] arcul OID dedus fara regula de 80', 'der.mjs', ' const arc = first < 80n ? first / 40n : 2n;', ' const arc = first / 40n;', 'OID'],
|
||||
];
|
||||
|
||||
// 1. martorul: originalul trebuie sa fie verde, si din el se ia numarul de probe
|
||||
const martorJson = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pki-martor-')), 'rez.json');
|
||||
const martor = spawnSync(process.execPath, [PROBA], { encoding: 'utf8', env: { ...process.env, PKI_JSON: martorJson }, timeout: 600000 });
|
||||
if (!fs.existsSync(martorJson)) { console.log('STRICAT: martorul nu a scris rezultatul (cod ' + martor.status + ')\n' + (martor.stdout || '').slice(-600)); process.exit(2); }
|
||||
const rezMartor = JSON.parse(fs.readFileSync(martorJson, 'utf8'));
|
||||
const N = rezMartor.length, verde = martor.status === 0 && rezMartor.every((x) => x.ok);
|
||||
console.log(`martorul: ${rezMartor.filter((x) => x.ok).length}/${N} probe trecute pe original${verde ? '' : ' (NU e verde: ' + rezMartor.filter((x) => !x.ok).map((x) => x.nume.slice(0, 40)).join(' | ') + ')'}`);
|
||||
for (const [, , , , tinta] of PLANTARI) if (!rezMartor.some((x) => x.nume.startsWith(tinta))) console.log(` ESEC tinta "${tinta}..." nu exista printre probele martorului`);
|
||||
fs.rmSync(path.dirname(martorJson), { recursive: true, force: true });
|
||||
|
||||
// 2. plantarile, cate PARALEL deodata
|
||||
function planteaza([nume, fis, vechi, nou, tinta]) {
|
||||
return new Promise((gata) => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pki-plantat-'));
|
||||
const sfarsit = (linie, ok) => { fs.rmSync(dir, { recursive: true, force: true }); gata({ nume, linie, ok }); };
|
||||
for (const n of FISIERE) fs.copyFileSync(path.join(SRC, n), path.join(dir, n));
|
||||
const t = fs.readFileSync(path.join(dir, fis), 'utf8');
|
||||
const ap = t.split(vechi).length - 1;
|
||||
if (ap !== 1) return sfarsit(` ESEC ${nume}: ancora apare de ${ap} ori (cerut 1), plantarea nu s-a pus`, false);
|
||||
fs.writeFileSync(path.join(dir, fis), t.replace(vechi, nou));
|
||||
const out = path.join(dir, 'rez.json');
|
||||
const p = spawn(process.execPath, [PROBA], { env: { ...process.env, PKI_MODULE: path.join(dir, 'pki.mjs'), PKI_JSON: out }, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let log = ''; p.stdout.on('data', (d) => { log += d; }); p.stderr.on('data', (d) => { log += d; });
|
||||
const timer = setTimeout(() => p.kill(), 600000);
|
||||
p.on('close', (cod) => {
|
||||
clearTimeout(timer);
|
||||
if (!fs.existsSync(out)) return sfarsit(` STRICAT ${nume}: proba nu a scris rezultatul (cod ${cod}) ${log.slice(-200).replace(/\s+/g, ' ')}`, false);
|
||||
const rez = JSON.parse(fs.readFileSync(out, 'utf8'));
|
||||
const rosii = rez.filter((x) => !x.ok).map((x) => x.nume);
|
||||
const prins = rosii.some((n) => n.startsWith(tinta));
|
||||
if (rez.length !== N) return sfarsit(` STRICAT ${nume}: au rulat ${rez.length} probe din ${N}`, false);
|
||||
if (prins) return sfarsit(` PRINS ${nume}: ${rosii.length} rosii, intre ele "${tinta}..."`, true);
|
||||
return sfarsit(` NEPRINS ${nume}: proba "${tinta}..." a ramas verde (rosii: ${rosii.map((r) => r.slice(0, 40)).join(' | ').slice(0, 200)})`, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
const rezultate = new Array(PLANTARI.length);
|
||||
let urm = 0;
|
||||
async function lucrator() { while (urm < PLANTARI.length) { const k = urm++; rezultate[k] = await planteaza(PLANTARI[k]); process.stdout.write(`\r ${rezultate.filter(Boolean).length}/${PLANTARI.length} plantari rulate`); } }
|
||||
await Promise.all(Array.from({ length: PARALEL }, lucrator));
|
||||
process.stdout.write('\r');
|
||||
for (const r of rezultate) console.log(r.linie);
|
||||
const bune = rezultate.filter((r) => r.ok).length, rele = rezultate.length - bune;
|
||||
|
||||
// 3. originalul e neatins
|
||||
const dupa = Object.fromEntries(FISIERE.map((n) => [n, sha(path.join(SRC, n))]));
|
||||
const neatins = JSON.stringify(inainte) === JSON.stringify(dupa);
|
||||
const tinteOk = PLANTARI.every(([, , , , tinta]) => rezMartor.some((x) => x.nume.startsWith(tinta)));
|
||||
console.log(`\ncontrol negativ: ${bune}/${PLANTARI.length} plantari prinse; originalul ${neatins ? 'identic' : 'SCHIMBAT'}; martorul ${verde ? `verde ${N}/${N}` : 'NU e verde'}`);
|
||||
process.exitCode = bune === PLANTARI.length && rele === 0 && neatins && verde && tinteOk ? 0 : 1;
|
||||
@@ -0,0 +1,417 @@
|
||||
// Proba autoritatii de certificare post-cuantice (pki.mjs, cli.mjs, der.mjs). Fiecare verdict al verificatorului nostru e comparat cu cel al
|
||||
// unei implementari STRAINE, OpenSSL 3.5 in linia de comanda (verificarea lui de lant, cu -x509_strict), iar TLS-ul e un handshake
|
||||
// real: server Node cu lantul nostru, client OpenSSL si client Node. Fiecare refuz cere MOTIVUL (codul), nu doar refuzul.
|
||||
// Cere `openssl` 3.5+ in PATH (Git for Windows il are); fara el proba iese STRICAT, nu verde.
|
||||
// node test/proba.mjs (PKI_MODULE=<cale catre pki.mjs> o ruleaza pe o copie; asa o cheama controlul negativ)
|
||||
// Iesire: 0 toate trec, 1 cel putin una cade, 2 STRICAT (unealta straina lipseste).
|
||||
// Probele marcate [A1]..[A10] sunt regresiile celor sapte defecte ale revizuirii adversariale din 2026-09-25.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import tls from 'node:tls';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawnSync, spawn } from 'node:child_process';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
|
||||
const AICI = path.dirname(fileURLToPath(import.meta.url));
|
||||
const MOD = process.env.PKI_MODULE ? path.resolve(process.env.PKI_MODULE) : path.join(AICI, '..', 'pki.mjs');
|
||||
const P = await import(pathToFileURL(MOD).href);
|
||||
const Dm = await import(pathToFileURL(path.join(path.dirname(MOD), 'der.mjs')).href);
|
||||
const CLI = path.join(path.dirname(MOD), 'cli.mjs');
|
||||
const T = fs.mkdtempSync(path.join(os.tmpdir(), 'aere-pki-'));
|
||||
const f = (n) => path.join(T, n);
|
||||
const rez = [];
|
||||
async function test(nume, fn) {
|
||||
try { await fn(); rez.push({ nume, ok: true }); console.log(' OK ' + nume); }
|
||||
catch (e) { rez.push({ nume, ok: false, motiv: String(e.message || e) }); console.log(' ESEC ' + nume + ' -> ' + String(e.message || e).slice(0, 300)); }
|
||||
}
|
||||
const eq = (a, b, m) => { if (a !== b) throw new Error(`${m}: ${JSON.stringify(a)} != ${JSON.stringify(b)}`); };
|
||||
const has = (s, sub, m) => { if (!String(s).includes(sub)) throw new Error(`${m}: lipseste "${sub}" in ${String(s).slice(0, 300)}`); };
|
||||
/** fn trebuie sa arunce PkiError cu codul cerut. */
|
||||
const code = (fn, c, m) => { let e = null; try { fn(); } catch (x) { e = x; } if (!e) throw new Error(m + ': nu a aruncat, asteptat ' + c); if (e.code !== c) throw new Error(`${m}: cod ${e.code} (${e.message}), asteptat ${c}`); };
|
||||
const env = { ...process.env, MSYS_NO_PATHCONV: '1', MSYS2_ARG_CONV_EXCL: '*' };
|
||||
function ossl(args, input) {
|
||||
const r = spawnSync('openssl', args, { encoding: 'utf8', env, input: input ?? '', timeout: 30000 });
|
||||
return { code: r.status, out: (r.stdout || '') + (r.stderr || ''), err: r.error };
|
||||
}
|
||||
// AERE-SINTETIC: parola de proba, valabila numai pentru cheile generate in aceasta rulare, intr-un dosar temporar sters la sfarsit
|
||||
const PASS_PROBA = 'proba-parola-lunga-1';
|
||||
const penv = { ...env, AERE_PKI_PASSPHRASE: PASS_PROBA };
|
||||
const run = (a, e = penv) => { const r = spawnSync(process.execPath, [CLI, ...a], { encoding: 'utf8', env: e, timeout: 120000 }); return { code: r.status, out: (r.stdout || '') + (r.stderr || '') }; };
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ OpenSSL de fata
|
||||
const v = ossl(['version']);
|
||||
if (v.err || !/OpenSSL 3\.(5|6|7|8|9)/.test(v.out)) { console.log('STRICAT: nu exista OpenSSL 3.5+ in PATH (' + (v.err ? v.err.message : v.out.trim()) + ')'); process.exit(2); }
|
||||
console.log('unealta straina: ' + v.out.trim());
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ lantul de baza
|
||||
const kr = P.generateKey('ml-dsa-87'), ki = P.generateKey('ml-dsa-65'), kl = P.generateKey('ml-dsa-65');
|
||||
const root = P.issue({ issuer: null, signingKey: kr.privateKey, subject: { cn: 'Proba Root', o: 'Aere Proba' }, publicKey: kr.publicKey, ca: true, pathLen: 1, days: 3650 });
|
||||
const inter = P.issue({ issuer: root, signingKey: kr.privateKey, subject: { cn: 'Proba Issuing', o: 'Aere Proba' }, publicKey: ki.publicKey, ca: true, pathLen: 0, days: 1825 });
|
||||
const leaf = P.issue({ issuer: inter, signingKey: ki.privateKey, subject: { cn: 'localhost' }, publicKey: kl.publicKey, days: 30, dns: ['localhost'], ips: ['127.0.0.1'], eku: ['serverAuth'] });
|
||||
const w = (n, der, lbl = 'CERTIFICATE') => { fs.writeFileSync(f(n), P.pem(lbl, der)); return f(n); };
|
||||
w('root.pem', root); w('inter.pem', inter); w('leaf.pem', leaf);
|
||||
fs.writeFileSync(f('leaf.key'), kl.privateKey.export({ type: 'pkcs8', format: 'pem' }));
|
||||
fs.writeFileSync(f('inter.key'), ki.privateKey.export({ type: 'pkcs8', format: 'pem' })); // pentru `openssl ca -gencrl` (liste facute de unealta straina)
|
||||
const V = (o) => P.verifyChain({ leaf, intermediates: [inter], roots: [root], host: 'localhost', ...o });
|
||||
const osslVerify = (extra, leafFile = f('leaf.pem'), chain = [f('inter.pem')]) =>
|
||||
ossl(['verify', '-x509_strict', '-purpose', 'sslserver', '-CAfile', f('root.pem'), ...chain.flatMap((c) => ['-untrusted', c]), ...extra, leafFile]);
|
||||
/** O lista de revocare a intermediarului facuta de OpenSSL (`openssl ca -gencrl`), cu extensiile din crlExt si intrarile din index. */
|
||||
function gencrl(crlExt, outName, index = '') {
|
||||
fs.writeFileSync(f('ca.index'), index); fs.writeFileSync(f('ca.crlnumber'), '05\n');
|
||||
fs.writeFileSync(f('ca.cnf'), `[ ca ]\ndefault_ca = CA_default\n[ CA_default ]\ndir = ${T.replace(/\\/g, '/')}\ndatabase = $dir/ca.index\ncrlnumber = $dir/ca.crlnumber\n` +
|
||||
`default_crl_days = 7\ndefault_md = default\ncrl_extensions = crl_ext\n[ crl_ext ]\n${crlExt}\n[ idp ]\nfullname = URI:http://crl.example/issuing.crl\n`);
|
||||
const r = ossl(['ca', '-config', f('ca.cnf'), '-gencrl', '-keyfile', f('inter.key'), '-cert', f('inter.pem'), '-out', f(outName)]);
|
||||
if (r.code !== 0) throw new Error('openssl ca -gencrl: ' + r.out.slice(0, 300));
|
||||
return P.unpem(fs.readFileSync(f(outName), 'utf8'), 'X509 CRL')[0];
|
||||
}
|
||||
const utc = (d) => d.toISOString().replace(/[-:T]/g, '').slice(2, 14) + 'Z'; // YYMMDDHHMMSSZ pentru index.txt
|
||||
|
||||
await test('lantul ML-DSA-87 / ML-DSA-65 / ML-DSA-65: valid la noi SI la OpenSSL (-x509_strict, sslserver)', () => {
|
||||
const r = V({}); eq(r.ok, true, 'noi ' + r.reason); eq(r.chain.join('<'), 'localhost<Proba Issuing<Proba Root', 'lantul');
|
||||
const o = osslVerify([]); eq(o.code, 0, 'openssl ' + o.out); has(o.out, ': OK', 'openssl');
|
||||
});
|
||||
await test('OpenSSL citeste certificatele: algoritmii ML-DSA, cheile, SAN, KeyUsage critic, CA:FALSE pe frunza', () => {
|
||||
const t = ossl(['x509', '-in', f('leaf.pem'), '-noout', '-text']).out;
|
||||
has(t, 'Signature Algorithm: ML-DSA-65', 'semnatura'); has(t, 'Public Key Algorithm: ML-DSA-65', 'cheia');
|
||||
has(t, 'DNS:localhost, IP Address:127.0.0.1', 'SAN'); has(t, 'X509v3 Key Usage: critical', 'KU'); has(t, 'CA:FALSE', 'bc');
|
||||
has(ossl(['x509', '-in', f('root.pem'), '-noout', '-text']).out, 'Signature Algorithm: ML-DSA-87', 'radacina');
|
||||
});
|
||||
await test('interoperabilitatea inversa: un certificat ML-DSA facut de OpenSSL e citit si verificat de noi; unul stricat nu', () => {
|
||||
const o = ossl(['req', '-x509', '-newkey', 'mldsa44', '-keyout', f('o.key'), '-out', f('o.pem'), '-days', '2', '-nodes', '-subj', '/CN=openssl-made']);
|
||||
eq(o.code, 0, 'openssl req ' + o.out);
|
||||
const der = P.unpem(fs.readFileSync(f('o.pem'), 'utf8'))[0];
|
||||
eq(P.selfSignatureValid(der), true, 'semnatura OpenSSL la noi'); eq(P.parseCert(der).alg, 'ml-dsa-44', 'algoritmul');
|
||||
const bad = Buffer.from(der); bad[bad.length - 5] ^= 1; eq(P.selfSignatureValid(bad), false, 'semnatura stricata');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ revocarea
|
||||
const crlRev = P.crl({ issuer: inter, signingKey: ki.privateKey, revoked: [{ serial: P.parseCert(leaf).serial, date: new Date() }], days: 7, number: 2 });
|
||||
const crlOk = P.crl({ issuer: inter, signingKey: ki.privateKey, revoked: [], days: 7, number: 1 });
|
||||
const crlRoot = P.crl({ issuer: root, signingKey: kr.privateKey, revoked: [], days: 7, number: 1 });
|
||||
w('crl-rev.pem', crlRev, 'X509 CRL'); w('crl-ok.pem', crlOk, 'X509 CRL'); w('crl-root.pem', crlRoot, 'X509 CRL');
|
||||
await test('revocarea: frunza revocata e REFUZATA (REVOKED) la noi si "certificate revoked" la OpenSSL; nerevocata trece la amandoi', () => {
|
||||
const r = V({ crls: [crlRev] }); eq(r.code, 'REVOKED', 'noi');
|
||||
const o = osslVerify(['-crl_check_all', '-CRLfile', f('crl-rev.pem'), '-CRLfile', f('crl-root.pem')]); has(o.out, 'certificate revoked', 'openssl'); eq(o.code === 0, false, 'openssl cod');
|
||||
eq(V({ crls: [crlOk, crlRoot], requireCrl: true }).ok, true, 'noi, nerevocata');
|
||||
eq(osslVerify(['-crl_check_all', '-CRLfile', f('crl-ok.pem'), '-CRLfile', f('crl-root.pem')]).code, 0, 'openssl, nerevocata');
|
||||
});
|
||||
await test('lista ceruta si lipsa: CRL_MISSING; lista semnata de alta cheie: CRL_SIGNATURE; lista expirata: CRL_STALE', () => {
|
||||
eq(V({ crls: [crlOk], requireCrl: true }).code, 'CRL_MISSING', 'radacina fara lista');
|
||||
const altCa = P.generateKey('ml-dsa-65');
|
||||
const fals = P.issue({ issuer: null, signingKey: altCa.privateKey, subject: { cn: 'Proba Issuing', o: 'Aere Proba' }, publicKey: altCa.publicKey, ca: true, days: 10 });
|
||||
const crlFals = P.crl({ issuer: fals, signingKey: altCa.privateKey, revoked: [], days: 7, number: 9 });
|
||||
eq(V({ crls: [crlFals] }).code, 'CRL_SIGNATURE', 'lista unei chei straine cu acelasi nume');
|
||||
eq(V({ crls: [crlOk], at: new Date(Date.now() + 9 * 86400000) }).code, 'CRL_STALE', 'lista dupa nextUpdate');
|
||||
});
|
||||
// [A2] prima lista din intrare nu e lista; e cea mai noua dintre cele care verifica
|
||||
await test('cea mai noua lista castiga [A2]: [veche goala, noua cu seria] in ambele ordini: REVOKED la noi si "certificate revoked" la OpenSSL; [veche cu seria, noua goala]: OK la amandoi; thisUpdate egal: crlNumber mai mare; o lista datata in viitor nu conteaza', () => {
|
||||
const serial = P.parseCert(leaf).serial;
|
||||
const L = (revoked, number, thisUpdate) => P.crl({ issuer: inter, signingKey: ki.privateKey, revoked, days: 7, number, thisUpdate });
|
||||
const veche = L([], 1, new Date(Date.now() - 3600000)), noua = L([{ serial, date: new Date() }], 2, new Date(Date.now() - 60000));
|
||||
eq(V({ crls: [veche, noua] }).code, 'REVOKED', 'veche intai'); eq(V({ crls: [noua, veche] }).code, 'REVOKED', 'noua intai');
|
||||
w('c-veche.pem', veche, 'X509 CRL'); w('c-noua.pem', noua, 'X509 CRL');
|
||||
has(osslVerify(['-crl_check_all', '-CRLfile', f('c-veche.pem'), '-CRLfile', f('c-noua.pem'), '-CRLfile', f('crl-root.pem')]).out, 'certificate revoked', 'openssl veche intai');
|
||||
has(osslVerify(['-crl_check_all', '-CRLfile', f('c-noua.pem'), '-CRLfile', f('c-veche.pem'), '-CRLfile', f('crl-root.pem')]).out, 'certificate revoked', 'openssl noua intai');
|
||||
const vecheCuSeria = L([{ serial, date: new Date() }], 2, new Date(Date.now() - 7200000)), nouaGoala = L([], 3, new Date(Date.now() - 30000));
|
||||
const r = V({ crls: [vecheCuSeria, nouaGoala] }); eq(r.ok, true, 'noua goala castiga ' + r.reason);
|
||||
w('c-vs.pem', vecheCuSeria, 'X509 CRL'); w('c-ng.pem', nouaGoala, 'X509 CRL');
|
||||
eq(osslVerify(['-crl_check_all', '-CRLfile', f('c-vs.pem'), '-CRLfile', f('c-ng.pem'), '-CRLfile', f('crl-root.pem')]).code, 0, 'openssl noua goala castiga');
|
||||
const t = new Date(Date.now() - 120000);
|
||||
const n1 = L([], 1, t), n2 = L([{ serial, date: new Date() }], 2, t);
|
||||
eq(V({ crls: [n1, n2] }).code, 'REVOKED', 'egalitate: #2 castiga'); eq(V({ crls: [n2, n1] }).code, 'REVOKED', 'egalitate: #2 castiga, invers');
|
||||
const viitor = L([{ serial, date: new Date() }], 9, new Date(Date.now() + 3600000));
|
||||
eq(V({ crls: [viitor, veche] }).ok, true, 'lista din viitor nu conteaza langa una curenta'); eq(V({ crls: [viitor] }).code, 'CRL_STALE', 'singura lista e din viitor');
|
||||
w('c-viitor.pem', viitor, 'X509 CRL');
|
||||
eq(osslVerify(['-crl_check_all', '-CRLfile', f('c-viitor.pem'), '-CRLfile', f('c-veche.pem'), '-CRLfile', f('crl-root.pem')]).code, 0, 'openssl: viitor + curenta = OK');
|
||||
eq(osslVerify(['-crl_check_all', '-CRLfile', f('c-viitor.pem'), '-CRLfile', f('crl-root.pem')]).code === 0, false, 'openssl: numai viitor = refuz');
|
||||
});
|
||||
// [A3] extensiile listei
|
||||
await test('extensiile listei [A3]: delta (deltaCRLIndicator, critic sau nu), IDP critic (lista OpenSSL) si o extensie critica necunoscuta (lista OpenSSL) dau CRL_EXT cu numele ei; la OpenSSL "different CRL scope", "unhandled critical CRL extension", delta refuzat cu -extended_crl; necritica necunoscuta ignorata la amandoi; intrare cu extensie critica refuzata', () => {
|
||||
const c = P.parseCert(inter); const alg = Dm.seq(Dm.oid(P.ALG['ml-dsa-65']));
|
||||
const ex = (oid, critical, val) => Dm.seq(Dm.oid(oid), critical ? Dm.bool(true) : null, Dm.octets(val));
|
||||
const aki = ex('2.5.29.35', false, Dm.seq(Dm.tlv(0x80, c.ski))), num = ex('2.5.29.20', false, Dm.int(3));
|
||||
const lista = (exts, rev = null) => { const tbs = Dm.seq(Dm.int(1), alg, c.subjectRaw, Dm.time(new Date(Date.now() - 60000)), Dm.time(new Date(Date.now() + 7 * 86400000)), rev, Dm.ctx(0, Dm.seq(...exts))); return Dm.seq(tbs, alg, Dm.bits(crypto.sign(null, tbs, ki.privateKey))); };
|
||||
const delta = lista([aki, num, ex('2.5.29.27', true, Dm.int(1))]), deltaNecritic = lista([aki, num, ex('2.5.29.27', false, Dm.int(1))]);
|
||||
const r1 = V({ crls: [delta] }); eq(r1.code, 'CRL_EXT', 'delta critic'); has(r1.reason, 'deltaCRLIndicator', 'motivul delta');
|
||||
eq(V({ crls: [deltaNecritic] }).code, 'CRL_EXT', 'delta necritic, tot refuzat');
|
||||
has(P.parseCrl(delta).refusedExt, 'delta', 'parseCrl il vede fara sa arunce');
|
||||
w('c-delta.pem', delta, 'X509 CRL');
|
||||
has(osslVerify(['-crl_check', '-extended_crl', '-CRLfile', f('c-delta.pem')]).out, 'unable to get certificate CRL', 'openssl -extended_crl nu foloseste un delta');
|
||||
const idp = gencrl('authorityKeyIdentifier = keyid\nissuingDistributionPoint = critical, @idp', 'c-idp.crl');
|
||||
const r2 = V({ crls: [idp] }); eq(r2.code, 'CRL_EXT', 'IDP'); has(r2.reason, 'issuingDistributionPoint', 'motivul IDP');
|
||||
has(osslVerify(['-crl_check', '-CRLfile', f('c-idp.crl')]).out, 'different CRL scope', 'openssl IDP');
|
||||
const crit = gencrl('authorityKeyIdentifier = keyid\n1.2.3.4.5 = critical, ASN1:UTF8String:x', 'c-crit.crl');
|
||||
const r3 = V({ crls: [crit] }); eq(r3.code, 'CRL_EXT', 'critica necunoscuta'); has(r3.reason, '1.2.3.4.5', 'motivul critica');
|
||||
has(osslVerify(['-crl_check', '-CRLfile', f('c-crit.crl')]).out, 'unhandled critical CRL extension', 'openssl critica');
|
||||
const nec = gencrl('authorityKeyIdentifier = keyid\n1.2.3.4.5 = ASN1:UTF8String:x', 'c-nec.crl');
|
||||
const r4 = V({ crls: [nec], requireCrl: false }); eq(r4.ok, true, 'necritica necunoscuta ignorata ' + r4.reason);
|
||||
eq(osslVerify(['-crl_check', '-CRLfile', f('c-nec.crl')]).code, 0, 'openssl necritica');
|
||||
const intrare = Dm.seq(Dm.seq(Dm.int(P.parseCert(leaf).serial), Dm.time(new Date()), Dm.seq(ex('2.5.29.29', true, Dm.seq(Dm.tlv(0xa4, c.subjectRaw)))))); // certificateIssuer critic (lista indirecta)
|
||||
const r5 = V({ crls: [lista([aki, num], intrare)] }); eq(r5.code, 'CRL_EXT', 'intrare cu extensie critica'); has(r5.reason, 'entry extension', 'motivul intrarii');
|
||||
const r6 = V({ crls: [lista([aki, num], Dm.seq(Dm.seq(Dm.int(P.parseCert(leaf).serial), Dm.time(new Date()), Dm.seq(ex('2.5.29.21', false, Dm.tlv(0x0a, Buffer.from([1])))))))] });
|
||||
eq(r6.code, 'REVOKED', 'intrare cu reasonCode necritic: seria conteaza');
|
||||
});
|
||||
await test('lista facuta de OpenSSL (openssl ca -gencrl, AKI + crlNumber, reasonCode pe intrare): OK la noi cand e goala, REVOKED cand poarta seria frunzei; AKI si crlNumber citite', () => {
|
||||
const goala = gencrl('authorityKeyIdentifier = keyid', 'o-goala.crl');
|
||||
const r = V({ crls: [goala] }); eq(r.ok, true, 'goala ' + r.reason);
|
||||
const pc = P.parseCrl(goala); eq(pc.crlNumber, 5n, 'crlNumber'); eq(pc.aki && pc.aki.equals(P.parseCert(inter).ski), true, 'AKI = SKI-ul emitentului'); eq(pc.refusedExt, null, 'nimic refuzat');
|
||||
const serial = P.parseCert(leaf).serial.toString('hex').toUpperCase();
|
||||
const rev = gencrl('authorityKeyIdentifier = keyid', 'o-rev.crl', `R\t${utc(new Date(Date.now() + 30 * 86400000))}\t${utc(new Date())},keyCompromise\t${serial}\tunknown\t/CN=localhost\n`);
|
||||
eq(V({ crls: [rev] }).code, 'REVOKED', 'revocata de lista OpenSSL'); eq(P.parseCrl(rev).revoked.size, 1, 'o intrare');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ refuzuri, cu perechea OpenSSL
|
||||
await test('un octet schimbat in frunza: SIGNATURE la noi, refuz la OpenSSL', () => {
|
||||
const p = P.parseCert(leaf); const bad = Buffer.from(leaf); const o = bad.indexOf(Buffer.from('localhost'), 0); bad[o] = 0x4c; // "Localhost"
|
||||
eq(P.verifyChain({ leaf: bad, intermediates: [inter], roots: [root] }).code, 'SIGNATURE', 'noi');
|
||||
eq(osslVerify([], w('bad.pem', bad)).code === 0, false, 'openssl'); eq(p.serial.length > 0, true, 'seria');
|
||||
});
|
||||
await test('alta radacina: UNTRUSTED la noi, "unable to get local issuer" la OpenSSL', () => {
|
||||
const k = P.generateKey('ml-dsa-65');
|
||||
const alt = P.issue({ issuer: null, signingKey: k.privateKey, subject: { cn: 'Alt Root' }, publicKey: k.publicKey, ca: true, days: 10 });
|
||||
const r = P.verifyChain({ leaf, intermediates: [inter], roots: [alt], host: 'localhost' }); eq(r.code, 'UNTRUSTED', 'noi'); has(r.reason, 'Proba Issuing', 'numeste certificatul ramas fara emitent');
|
||||
const o = ossl(['verify', '-x509_strict', '-CAfile', w('alt.pem', alt), '-untrusted', f('inter.pem'), f('leaf.pem')]); has(o.out, 'unable to get local issuer', 'openssl');
|
||||
});
|
||||
await test('timpul: EXPIRED dupa notAfter si NOT_YET_VALID inainte de notBefore, la noi si la OpenSSL (-attime)', () => {
|
||||
const tarziu = new Date(Date.now() + 40 * 86400000), devreme = new Date(Date.now() - 86400000);
|
||||
eq(V({ at: tarziu }).code, 'EXPIRED', 'noi tarziu'); eq(V({ at: devreme }).code, 'NOT_YET_VALID', 'noi devreme');
|
||||
has(osslVerify(['-attime', String(Math.floor(tarziu / 1000))]).out, 'certificate has expired', 'openssl tarziu');
|
||||
has(osslVerify(['-attime', String(Math.floor(devreme / 1000))]).out, 'not yet valid', 'openssl devreme');
|
||||
});
|
||||
await test('pathLen: o autoritate cu pathLen 0 care are sub ea inca o autoritate: PATH_LEN la noi, refuz la OpenSSL', () => {
|
||||
const k2 = P.generateKey('ml-dsa-65'), k3 = P.generateKey('ml-dsa-65');
|
||||
const sub = P.issue({ issuer: inter, signingKey: ki.privateKey, subject: { cn: 'Sub CA' }, publicKey: k2.publicKey, ca: true, days: 30 });
|
||||
const l2 = P.issue({ issuer: sub, signingKey: k2.privateKey, subject: { cn: 'localhost' }, publicKey: k3.publicKey, days: 30, dns: ['localhost'], eku: ['serverAuth'] });
|
||||
eq(P.verifyChain({ leaf: l2, intermediates: [sub, inter], roots: [root], host: 'localhost' }).code, 'PATH_LEN', 'noi');
|
||||
const o = osslVerify([], w('l2.pem', l2), [w('sub.pem', sub), f('inter.pem')]); eq(o.code === 0, false, 'openssl ' + o.out); has(o.out, 'path length', 'openssl motivul');
|
||||
});
|
||||
await test('un certificat de entitate folosit ca emitent: NOT_CA la noi, "invalid CA certificate" la OpenSSL (lant facut de OpenSSL)', () => {
|
||||
// frunza noastra nu poate semna: o face OpenSSL, care semneaza cu orice certificat
|
||||
let o = ossl(['req', '-new', '-newkey', 'mldsa65', '-keyout', f('x.key'), '-out', f('x.csr'), '-nodes', '-subj', '/CN=victim']);
|
||||
eq(o.code, 0, 'csr ' + o.out);
|
||||
o = ossl(['x509', '-req', '-in', f('x.csr'), '-CA', f('leaf.pem'), '-CAkey', f('leaf.key'), '-out', f('x.pem'), '-days', '2', '-set_serial', '7']);
|
||||
eq(o.code, 0, 'semnat de frunza ' + o.out);
|
||||
const x = P.unpem(fs.readFileSync(f('x.pem'), 'utf8'))[0];
|
||||
const r = P.verifyChain({ leaf: x, intermediates: [leaf, inter], roots: [root], purpose: null });
|
||||
eq(r.code, 'NOT_CA', 'noi ' + r.reason);
|
||||
const ov = ossl(['verify', '-CAfile', f('root.pem'), '-untrusted', f('inter.pem'), '-untrusted', f('leaf.pem'), f('x.pem')]);
|
||||
eq(ov.code === 0, false, 'openssl ' + ov.out);
|
||||
});
|
||||
await test('frunza pentru alt nume: HOSTNAME la noi, "hostname mismatch" la OpenSSL; IP-ul din SAN trece la amandoi', () => {
|
||||
eq(V({ host: 'aere.example' }).code, 'HOSTNAME', 'noi'); has(osslVerify(['-verify_hostname', 'aere.example']).out, 'hostname mismatch', 'openssl');
|
||||
eq(V({ host: '127.0.0.1' }).ok, true, 'noi IP'); eq(osslVerify(['-verify_ip', '127.0.0.1']).code, 0, 'openssl IP');
|
||||
});
|
||||
await test('scopul: o frunza numai clientAuth folosita ca server: EKU la noi, "unsuitable certificate purpose" la OpenSSL', () => {
|
||||
const k = P.generateKey('ml-dsa-65');
|
||||
const cl = P.issue({ issuer: inter, signingKey: ki.privateKey, subject: { cn: 'client' }, publicKey: k.publicKey, days: 30, eku: ['clientAuth'] });
|
||||
eq(P.verifyChain({ leaf: cl, intermediates: [inter], roots: [root], purpose: 'serverAuth' }).code, 'EKU', 'noi');
|
||||
eq(P.verifyChain({ leaf: cl, intermediates: [inter], roots: [root], purpose: 'clientAuth' }).ok, true, 'noi ca client');
|
||||
has(osslVerify([], w("cl.pem", cl)).out, "unsuitable certificate purpose", "openssl");
|
||||
});
|
||||
// [A6] EKU pe autoritati
|
||||
await test('EKU pe autoritati [A6]: o CA restransa la clientAuth cu o frunza serverAuth sub ea: EKU numind autoritatea la noi, "unsuitable certificate purpose" la adancimea 1 la OpenSSL; aceeasi CA cu o frunza clientAuth, ca client: OK la amandoi; o RADACINA restransa e aplicata la fel', () => {
|
||||
const k2 = P.generateKey('ml-dsa-65'), k3 = P.generateKey('ml-dsa-65');
|
||||
const caClient = P.issue({ issuer: root, signingKey: kr.privateKey, subject: { cn: 'Client Only CA' }, publicKey: k2.publicKey, ca: true, pathLen: 0, days: 100, eku: ['clientAuth'] });
|
||||
const srv = P.issue({ issuer: caClient, signingKey: k2.privateKey, subject: { cn: 'localhost' }, publicKey: k3.publicKey, days: 30, dns: ['localhost'], eku: ['serverAuth'] });
|
||||
const cli = P.issue({ issuer: caClient, signingKey: k2.privateKey, subject: { cn: 'client' }, publicKey: k3.publicKey, days: 30, eku: ['clientAuth'] });
|
||||
const r = P.verifyChain({ leaf: srv, intermediates: [caClient], roots: [root], host: 'localhost', purpose: 'serverAuth' });
|
||||
eq(r.code, 'EKU', 'noi'); has(r.reason, 'Client Only CA', 'numeste autoritatea');
|
||||
const o = osslVerify([], w('a6-srv.pem', srv), [w('a6-ca.pem', caClient)]); has(o.out, 'unsuitable certificate purpose', 'openssl'); has(o.out, 'at 1 depth', 'openssl: la autoritate');
|
||||
eq(P.verifyChain({ leaf: cli, intermediates: [caClient], roots: [root], purpose: 'clientAuth' }).ok, true, 'client sub CA de client');
|
||||
eq(ossl(['verify', '-x509_strict', '-purpose', 'sslclient', '-CAfile', f('root.pem'), '-untrusted', f('a6-ca.pem'), w('a6-cli.pem', cli)]).code, 0, 'openssl client');
|
||||
const k4 = P.generateKey('ml-dsa-65');
|
||||
const rootC = P.issue({ issuer: null, signingKey: k4.privateKey, subject: { cn: 'Client Only Root' }, publicKey: k4.publicKey, ca: true, pathLen: 1, days: 100, eku: ['clientAuth'] });
|
||||
const srv2 = P.issue({ issuer: rootC, signingKey: k4.privateKey, subject: { cn: 'localhost' }, publicKey: k3.publicKey, days: 30, dns: ['localhost'], eku: ['serverAuth'] });
|
||||
const r2 = P.verifyChain({ leaf: srv2, roots: [rootC], host: 'localhost' }); eq(r2.code, 'EKU', 'radacina restransa'); has(r2.reason, 'Client Only Root', 'numeste radacina');
|
||||
has(ossl(['verify', '-x509_strict', '-purpose', 'sslserver', '-CAfile', w('a6-rootc.pem', rootC), w('a6-srv2.pem', srv2)]).out, 'unsuitable certificate purpose', 'openssl radacina');
|
||||
});
|
||||
await test('o autoritate folosita ca frunza de server: LEAF_IS_CA', () => {
|
||||
eq(P.verifyChain({ leaf: inter, intermediates: [], roots: [root] }).code, 'LEAF_IS_CA', 'noi');
|
||||
});
|
||||
// [A7] toate ancorele candidate
|
||||
await test('reinnoirea radacinii [A7]: roots [expirata, valida] cu aceeasi cheie si acelasi nume: OK la noi si la OpenSSL (amandoua in CAfile); numai [expirata]: EXPIRED si "certificate has expired"; intermediar semnat incrucisat de o radacina straina pus inaintea celui bun: OK la noi pe drumul bun', () => {
|
||||
const rootExp = P.issue({ issuer: null, signingKey: kr.privateKey, subject: { cn: 'Proba Root', o: 'Aere Proba' }, publicKey: kr.publicKey, ca: true, pathLen: 1, days: 1, notBefore: new Date(Date.now() - 10 * 86400000) });
|
||||
const r = P.verifyChain({ leaf, intermediates: [inter], roots: [rootExp, root], host: 'localhost' }); eq(r.ok, true, 'expirata intai ' + r.reason);
|
||||
eq(P.verifyChain({ leaf, intermediates: [inter], roots: [root, rootExp], host: 'localhost' }).ok, true, 'valida intai');
|
||||
eq(P.verifyChain({ leaf, intermediates: [inter], roots: [rootExp], host: 'localhost' }).code, 'EXPIRED', 'numai expirata');
|
||||
fs.writeFileSync(f('roots2.pem'), P.pem('CERTIFICATE', rootExp) + P.pem('CERTIFICATE', root));
|
||||
const o = ossl(['verify', '-x509_strict', '-purpose', 'sslserver', '-CAfile', f('roots2.pem'), '-untrusted', f('inter.pem'), f('leaf.pem')]); eq(o.code, 0, 'openssl rollover ' + o.out);
|
||||
has(ossl(['verify', '-x509_strict', '-purpose', 'sslserver', '-CAfile', w('rootexp.pem', rootExp), '-untrusted', f('inter.pem'), f('leaf.pem')]).out, 'certificate has expired', 'openssl numai expirata');
|
||||
const k2 = P.generateKey('ml-dsa-87');
|
||||
const root2 = P.issue({ issuer: null, signingKey: k2.privateKey, subject: { cn: 'Alt Root 2' }, publicKey: k2.publicKey, ca: true, pathLen: 1, days: 3650 });
|
||||
const cross = P.issue({ issuer: root2, signingKey: k2.privateKey, subject: { cn: 'Proba Issuing', o: 'Aere Proba' }, publicKey: ki.publicKey, ca: true, pathLen: 0, days: 1825 });
|
||||
const rc = P.verifyChain({ leaf, intermediates: [cross, inter], roots: [root], host: 'localhost' }); eq(rc.ok, true, 'cross intai ' + rc.reason); eq(rc.chain.join('<'), 'localhost<Proba Issuing<Proba Root', 'drumul bun');
|
||||
const rn = P.verifyChain({ leaf, intermediates: [cross], roots: [root], host: 'localhost' }); eq(rn.code, 'UNTRUSTED', 'numai cross: niciun drum');
|
||||
const oc = ossl(['verify', '-x509_strict', '-purpose', 'sslserver', '-CAfile', f('root.pem'), '-untrusted', w('cross.pem', cross), '-untrusted', f('inter.pem'), f('leaf.pem')]);
|
||||
console.log(` (OpenSSL cu [cross, inter]: cod ${oc.code}; OpenSSL nu revine pe pasi intre intermediari, noi da)`);
|
||||
});
|
||||
await test('extensie critica necunoscuta (facuta de OpenSSL): CRITICAL_EXT la noi, "unhandled critical extension" la OpenSSL', () => {
|
||||
const o = ossl(['req', '-x509', '-newkey', 'mldsa65', '-keyout', f('c.key'), '-out', f('c.pem'), '-days', '2', '-nodes', '-subj', '/CN=crit',
|
||||
'-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign,digitalSignature', '-addext', '1.2.3.4.5=critical,ASN1:UTF8String:x']);
|
||||
eq(o.code, 0, 'openssl req ' + o.out);
|
||||
const c = P.unpem(fs.readFileSync(f('c.pem'), 'utf8'))[0];
|
||||
eq(P.verifyChain({ leaf: c, roots: [c], purpose: null }).code, 'CRITICAL_EXT', 'noi');
|
||||
has(ossl(['verify', '-CAfile', f('c.pem'), f('c.pem')]).out, 'unhandled critical extension', 'openssl');
|
||||
});
|
||||
await test('forma: algoritm exterior diferit de cel interior (ALG_MISMATCH), parametri pe ML-DSA (ALG_PARAMS), DER necanonic, octeti in plus', () => {
|
||||
const oid65 = Buffer.from('0609608648016503040312', 'hex'), oid44 = Buffer.from('0609608648016503040311', 'hex');
|
||||
const last = leaf.lastIndexOf(oid65); const m = Buffer.from(leaf); oid44.copy(m, last);
|
||||
let e = null; try { P.parseCert(m); } catch (x) { e = x; } eq(e && e.code, 'ALG_MISMATCH', 'exterior 44 / interior 65');
|
||||
const withNull = Buffer.concat([Buffer.from('300d', 'hex'), oid65, Buffer.from('0500', 'hex')]);
|
||||
const src = Buffer.concat([Buffer.from('300b', 'hex'), oid65]);
|
||||
const j = leaf.lastIndexOf(src);
|
||||
const lung = leaf.readUInt16BE(2) + 2; // continutul SEQUENCE-ului de sus (forma 30 82 LL LL)
|
||||
const n = Buffer.concat([Buffer.from([0x30, 0x82]), Buffer.alloc(2), leaf.subarray(4, j), withNull, leaf.subarray(j + src.length)]);
|
||||
n.writeUInt16BE(lung, 2);
|
||||
e = null; try { P.parseCert(n); } catch (x) { e = x; } eq(e && e.code, 'ALG_PARAMS', 'NULL pe ML-DSA');
|
||||
e = null; try { P.parseCert(Buffer.concat([leaf, Buffer.from([0])])); } catch (x) { e = x; } has(e && e.message, 'octeti dupa structura', 'coada');
|
||||
const nc = Buffer.from([0x30, 0x81, 0x03, 0x02, 0x01, 0x05]); e = null; try { P.parseCert(nc); } catch (x) { e = x; } has(e && e.message, 'necanonica', 'lungime lunga pentru una scurta');
|
||||
});
|
||||
// [A5] SPKI
|
||||
const cuSpkiRau = (der) => { const c = P.parseCert(der); const [algEl] = Dm.children(Dm.parse(c.spki)); const s = Dm.seq(algEl.raw, Dm.bits(Buffer.alloc(10, 7))); return { c, tbs: Dm.seq(...Dm.children(Dm.parse(c.tbs)).map((k) => (k.raw.equals(c.spki) ? s : k.raw))) }; };
|
||||
await test('cheie publica malformata [A5]: SPKI de 10 octeti sub id-ml-dsa pe frunza, pe intermediar si pe radacina: verdict SPKI (cu lungimea) la noi, fara exceptie; "decode error" la OpenSSL; o cheie de 1312 octeti sub id-ml-dsa-65 e tot SPKI', () => {
|
||||
const resemn = (der, key, alg) => { const { tbs } = cuSpkiRau(der); return Dm.seq(tbs, Dm.seq(Dm.oid(P.ALG[alg])), Dm.bits(crypto.sign(null, tbs, key))); };
|
||||
const leafRau = resemn(leaf, ki.privateKey, 'ml-dsa-65'), interRau = resemn(inter, kr.privateKey, 'ml-dsa-87');
|
||||
const rootRau = (() => { const { c, tbs } = cuSpkiRau(root); return Dm.seq(tbs, Dm.seq(Dm.oid(P.ALG['ml-dsa-87'])), Dm.bits(c.signature)); })();
|
||||
for (const [nume, o] of [['frunza', { leaf: leafRau, intermediates: [inter], roots: [root] }], ['intermediar', { leaf, intermediates: [interRau], roots: [root] }], ['radacina', { leaf, intermediates: [inter], roots: [rootRau] }]]) {
|
||||
let r; try { r = P.verifyChain({ host: 'localhost', ...o }); } catch (e) { throw new Error(nume + ': EXCEPTIE ' + e.message); }
|
||||
eq(r.code, 'SPKI', nume); has(r.reason, 'this one has 10', nume + ': motivul');
|
||||
}
|
||||
has(osslVerify([], w('a5-leaf.pem', leafRau)).out, 'decode error', 'openssl frunza');
|
||||
has(osslVerify([], f('leaf.pem'), [w('a5-inter.pem', interRau)]).out, 'decode error', 'openssl intermediar');
|
||||
const k44 = P.generateKey('ml-dsa-44'); const pk44 = Dm.bitString(Dm.children(Dm.parse(k44.publicKey.export({ type: 'spki', format: 'der' })))[1]).bytes;
|
||||
const c = P.parseCert(leaf); const s65 = Dm.seq(Dm.seq(Dm.oid(P.ALG['ml-dsa-65'])), Dm.bits(pk44));
|
||||
const tbs = Dm.seq(...Dm.children(Dm.parse(c.tbs)).map((k) => (k.raw.equals(c.spki) ? s65 : k.raw)));
|
||||
const gresit = Dm.seq(tbs, Dm.seq(Dm.oid(P.ALG['ml-dsa-65'])), Dm.bits(crypto.sign(null, tbs, ki.privateKey)));
|
||||
const r = V({ leaf: gresit }); eq(r.code, 'SPKI', 'cheie 44 sub OID 65'); has(r.reason, '1312', 'lungimea gasita');
|
||||
});
|
||||
await test('orice octeti dau verdict, nu exceptie [A5]: mutatii aleatoare ale frunzei, ale intermediarului si ale listei, trunchieri si gunoi trec prin verifyChain fara sa arunce', () => {
|
||||
let verdicte = 0;
|
||||
const incearca = (o) => { let r; try { r = P.verifyChain(o); } catch (e) { throw new Error('EXCEPTIE: ' + e.message); } if (typeof r.ok !== 'boolean' || !r.code) throw new Error('fara verdict'); verdicte++; };
|
||||
for (let i = 0; i < 300; i++) { const b = Buffer.from(leaf); for (let j = 0; j <= i % 4; j++) b[crypto.randomInt(b.length)] ^= 1 << crypto.randomInt(8); incearca({ leaf: b, intermediates: [inter], roots: [root], host: 'localhost', crls: [crlOk] }); }
|
||||
for (const len of [0, 1, 2, 3, 4, 10, 100, 700, leaf.length - 1]) incearca({ leaf: leaf.subarray(0, len), intermediates: [inter], roots: [root] });
|
||||
for (let i = 0; i < 50; i++) incearca({ leaf: crypto.randomBytes(1 + crypto.randomInt(400)), roots: [root] });
|
||||
for (let i = 0; i < 100; i++) { const b = Buffer.from(crlOk); b[crypto.randomInt(b.length)] ^= 0xff; incearca({ leaf, intermediates: [inter], roots: [root], crls: [b], requireCrl: true }); }
|
||||
for (let i = 0; i < 100; i++) { const b = Buffer.from(inter); b[crypto.randomInt(b.length)] ^= 0xff; incearca({ leaf, intermediates: [b], roots: [root] }); }
|
||||
for (let i = 0; i < 50; i++) { const b = Buffer.from(root); b[crypto.randomInt(b.length)] ^= 0xff; incearca({ leaf, intermediates: [inter], roots: [b] }); }
|
||||
eq(verdicte >= 609, true, 'numarul de verdicte ' + verdicte);
|
||||
});
|
||||
// [A10] OID
|
||||
await test('OID [A10]: 2.999 se codifica 06 02 88 37 si se decodifica inapoi; 2.100.3 si alte sase OID-uri identice octet cu octet cu OpenSSL (asn1parse -genstr) si round-trip; 0x80 initial refuzat ca necanonic; un certificat OpenSSL cu extensia critica 2.999.1 e numit corect in CRITICAL_EXT', () => {
|
||||
eq(Dm.oid('2.999').toString('hex'), '06028837', '2.999');
|
||||
for (const o of ['2.999', '2.100.3', '2.16.840.1.101.3.4.3.18', '1.3.6.1.5.5.7.3.1', '2.5.29.19', '0.9.2342.19200300.100.1.25', '1.2.840.113549.1.1.11', '2.25.329800735698586629295641978511506172918']) {
|
||||
const noi = Dm.oid(o);
|
||||
eq(Dm.oidToString(Dm.parse(noi)), o, 'round-trip ' + o);
|
||||
const r = ossl(['asn1parse', '-genstr', 'OID:' + o, '-noout', '-out', f('oid.der')]); eq(r.code, 0, 'openssl genstr ' + o + ' ' + r.out);
|
||||
eq(fs.readFileSync(f('oid.der')).toString('hex'), noi.toString('hex'), 'octetii OpenSSL pentru ' + o);
|
||||
}
|
||||
let e = null; try { Dm.oidToString(Dm.parse(Buffer.from('06028001', 'hex'))); } catch (x) { e = x; } has(e && e.message, 'necanonic', '0x80 initial');
|
||||
e = null; try { Dm.oid('1.40'); } catch (x) { e = x; } has(e && e.message, 'arc nevalid', '1.40');
|
||||
const o = ossl(['req', '-x509', '-newkey', 'mldsa44', '-keyout', f('c9.key'), '-out', f('c9.pem'), '-days', '2', '-nodes', '-subj', '/CN=crit999',
|
||||
'-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign,digitalSignature', '-addext', '2.999.1=critical,ASN1:UTF8String:x']);
|
||||
eq(o.code, 0, 'req ' + o.out);
|
||||
const c = P.unpem(fs.readFileSync(f('c9.pem'), 'utf8'))[0]; const r = P.verifyChain({ leaf: c, roots: [c], purpose: null });
|
||||
eq(r.code, 'CRITICAL_EXT', 'verdict'); has(r.reason, 'extension 2.999.1', 'numele adevarat al extensiei');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ TLS real
|
||||
await test('TLS 1.3 complet post-cuantic: server Node cu lantul nostru, X25519MLKEM768 + semnatura mldsa65; OpenSSL si Node il accepta', async () => {
|
||||
const srv = tls.createServer({ key: fs.readFileSync(f('leaf.key')), cert: fs.readFileSync(f('leaf.pem')) + fs.readFileSync(f('inter.pem')),
|
||||
minVersion: 'TLSv1.3', ecdhCurve: 'X25519MLKEM768' }, (c) => c.end('aere\n'));
|
||||
await new Promise((ok) => srv.listen(0, '127.0.0.1', ok));
|
||||
const port = srv.address().port;
|
||||
try {
|
||||
const out = await new Promise((ok) => {
|
||||
const c = spawn('openssl', ['s_client', '-connect', '127.0.0.1:' + port, '-servername', 'localhost', '-verify_hostname', 'localhost',
|
||||
'-CAfile', f('root.pem'), '-verify_return_error', '-groups', 'X25519MLKEM768'], { env });
|
||||
let s = ''; c.stdout.on('data', (d) => { s += d; }); c.stderr.on('data', (d) => { s += d; });
|
||||
c.stdin.end(); const t = setTimeout(() => c.kill(), 15000); c.on('close', () => { clearTimeout(t); ok(s); });
|
||||
});
|
||||
has(out, 'Verify return code: 0 (ok)', 'openssl verificarea'); has(out, 'Peer signature type: mldsa65', 'semnatura'); has(out, 'Negotiated TLS1.3 group: X25519MLKEM768', 'grupul');
|
||||
const nod = await new Promise((ok) => {
|
||||
const s = tls.connect({ host: '127.0.0.1', port, servername: 'localhost', ca: fs.readFileSync(f('root.pem')), ecdhCurve: 'X25519MLKEM768' }, () => {
|
||||
ok({ auth: s.authorized, err: s.authorizationError, proto: s.getProtocol() }); s.end();
|
||||
}); s.on('error', (e) => ok({ auth: false, err: e.message }));
|
||||
});
|
||||
eq(nod.auth, true, 'clientul Node ' + nod.err); eq(nod.proto, 'TLSv1.3', 'protocolul');
|
||||
const alt = P.generateKey('ml-dsa-65');
|
||||
const altRoot = P.issue({ issuer: null, signingKey: alt.privateKey, subject: { cn: 'Alt' }, publicKey: alt.publicKey, ca: true, days: 5 });
|
||||
const neg = await new Promise((ok) => {
|
||||
const s = tls.connect({ host: '127.0.0.1', port, servername: 'localhost', ca: P.pem('CERTIFICATE', altRoot), rejectUnauthorized: true }, () => { ok('conectat'); s.end(); });
|
||||
s.on('error', (e) => ok('refuzat: ' + e.message));
|
||||
});
|
||||
has(neg, 'refuzat', 'clientul Node cu alta radacina');
|
||||
} finally { srv.close(); }
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ cheia pe disc [A1]
|
||||
await test('sigilarea cheii [A1]: fisierul poarta scrypt N=2^17 r=8 p=1 si AES-256-GCM cu antetul ca AAD (citit si direct din DER); o incercare de parola costa peste 25 ms (masurat si tiparit); parola gresita, text cifrat sau antet atins: KEY_LOCKED; PKCS#8 cifrat sau in clar: KEY_FORMAT; OpenSSL nu il deschide', () => {
|
||||
const pass = 'Proba-sigiliu-2026'; // AERE-SINTETIC
|
||||
const sealed = P.exportPrivateKey(ki.privateKey, pass);
|
||||
has(sealed, '-----BEGIN AERE PQ PKI PRIVATE KEY-----', 'eticheta');
|
||||
eq(/-----BEGIN (ENCRYPTED )?PRIVATE KEY-----/.test(sealed), false, 'fara PKCS#8');
|
||||
const h = P.readSealedKeyHeader(sealed);
|
||||
eq(h.N, 2 ** 17, 'N'); eq(h.r, 8, 'r'); eq(h.p, 1, 'p'); eq(h.kdf, 'scrypt', 'kdf'); eq(h.cipher, 'aes-256-gcm', 'cifrul');
|
||||
eq(h.salt.length, 16, 'salt'); eq(h.iv.length, 12, 'iv'); eq(h.tag.length, 16, 'tag'); eq(h.ct.length > 4000, true, 'PKCS#8 cifrat inauntru');
|
||||
const blob = P.unpem(sealed, P.KEY_LABEL)[0]; const [hdr] = Dm.children(Dm.parse(blob)); const hk = Dm.children(hdr);
|
||||
eq(Number(Dm.intToBigInt(hk[3])), 131072, 'N citit direct din DER'); eq(Number(Dm.intToBigInt(hk[4])), 8, 'r din DER'); eq(Number(Dm.intToBigInt(hk[0])), 1, 'versiunea formatului');
|
||||
const back = P.importPrivateKey(sealed, pass);
|
||||
eq(crypto.createPublicKey(back).export({ type: 'spki', format: 'der' }).equals(ki.publicKey.export({ type: 'spki', format: 'der' })), true, 'aceeasi cheie dupa deschidere');
|
||||
const t0 = process.hrtime.bigint(); let n = 0;
|
||||
for (let i = 0; i < 3; i++) { try { P.importPrivateKey(sealed, 'Gresita-parola-' + i); } catch (e) { if (e.code === 'KEY_LOCKED') n++; } }
|
||||
const ms = Number(process.hrtime.bigint() - t0) / 3e6; eq(n, 3, 'parola gresita = KEY_LOCKED');
|
||||
console.log(` cost masurat: ${ms.toFixed(0)} ms per incercare de parola (scrypt N=${h.N}, r=${h.r}, p=${h.p}, ${os.cpus()[0]?.model?.trim() || 'cpu'})`);
|
||||
if (ms < 25) throw new Error('o incercare de parola costa ' + ms.toFixed(1) + ' ms, sub 25 ms: KDF-ul e prea ieftin');
|
||||
const atins = (off) => { const b = Buffer.from(blob); b[off] ^= 1; return P.pem(P.KEY_LABEL, b); };
|
||||
code(() => P.importPrivateKey(atins(blob.length - 1), pass), 'KEY_LOCKED', 'text cifrat atins');
|
||||
code(() => P.importPrivateKey(atins(hk[2].content.byteOffset - blob.byteOffset), pass), 'KEY_LOCKED', 'salt atins (antetul e AAD)');
|
||||
code(() => P.importPrivateKey(atins(hk[7].content.byteOffset - blob.byteOffset), pass), 'KEY_LOCKED', 'iv atins');
|
||||
code(() => P.importPrivateKey(sealed, ''), 'KEY_LOCKED', 'fara parola');
|
||||
code(() => P.importPrivateKey(ki.privateKey.export({ type: 'pkcs8', format: 'pem', cipher: 'aes-256-cbc', passphrase: pass }), pass), 'KEY_FORMAT', 'PKCS#8 cifrat (formatul vechi)');
|
||||
code(() => P.importPrivateKey(ki.privateKey.export({ type: 'pkcs8', format: 'pem' }), pass), 'KEY_FORMAT', 'PKCS#8 in clar');
|
||||
fs.writeFileSync(f('sealed.pem'), sealed);
|
||||
eq(ossl(['pkey', '-in', f('sealed.pem'), '-noout']).code === 0, false, 'openssl nu poate deschide formatul sigilat');
|
||||
});
|
||||
await test('politica de parola [A1]: sub 12 caractere, o singura clasa sub 20, toate identice, evidente (password1234, Password123!, Qwerty123456): PASSPHRASE; 3 clase la 12 sau 20+ caractere trec; linia de comanda refuza init cu o parola slaba si nu scrie nimic', () => {
|
||||
// AERE-SINTETIC: parole de proba pentru politica, niciuna folosita pentru vreo cheie
|
||||
for (const p of ['scurta1A!', 'aaaaaaaaaaaa', 'abcdefghijkl', 'password1234', 'Password123!', 'Qwerty123456', '123456789012', 'AAAAAAAAAAAAAAAAAAAAAAAA', 'Letmein-2026', 'ABCDEFGHIJKL']) code(() => P.checkPassphrase(p), 'PASSPHRASE', p);
|
||||
for (const p of ['Abcdefghijk1', PASS_PROBA, 'abcdefghijklmnopqrstu', 'correct horse battery staple', 'Zx9!Zx9!Zx9!']) eq(P.checkPassphrase(p), p, p);
|
||||
code(() => P.exportPrivateKey(ki.privateKey, 'aaaaaaaaaaaa'), 'PASSPHRASE', 'exportul aplica politica');
|
||||
const r = run(['init', '--dir', f('ca-slaba'), '--name', 'r'], { ...env, AERE_PKI_PASSPHRASE: 'aaaaaaaaaaaa' }); eq(r.code, 2, 'cli'); has(r.out, 'PASSPHRASE', 'motivul');
|
||||
eq(fs.existsSync(path.join(f('ca-slaba'), 'r.key')), false, 'nimic scris'); eq(fs.existsSync(path.join(f('ca-slaba'), 'r.crt')), false, 'niciun certificat scris');
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ linia de comanda
|
||||
await test('linia de comanda: init, intermediate, issue, revoke, crl, verify, unseal; cheile scrise sigilate (nu PKCS#8); fara parola si cu parola gresita refuza; nimic suprascris', () => {
|
||||
const D = f('ca');
|
||||
eq(run(['init', '--dir', D, '--name', 'root', '--org', 'Aere Proba']).code, 0, 'init');
|
||||
eq(run(['intermediate', '--dir', D, '--ca', 'root', '--name', 'issuing']).code, 0, 'intermediate');
|
||||
eq(run(['issue', '--dir', D, '--ca', 'issuing', '--cn', 'svc.local', '--dns', 'svc.local', '--out', f('svc')]).code, 0, 'issue');
|
||||
const rk = fs.readFileSync(path.join(D, 'root.key'), 'utf8'), sk = fs.readFileSync(f('svc.key'), 'utf8');
|
||||
has(rk, 'AERE PQ PKI PRIVATE KEY', 'cheia radacinii sigilata'); has(sk, 'AERE PQ PKI PRIVATE KEY', 'cheia frunzei sigilata');
|
||||
eq(/-----BEGIN (ENCRYPTED )?PRIVATE KEY-----/.test(rk + sk), false, 'niciun PKCS#8 pe disc');
|
||||
eq(P.readSealedKeyHeader(rk).N, 2 ** 17, 'N al cheii radacinii');
|
||||
const ok1 = run(['verify', '--roots', path.join(D, 'root.crt'), '--chain', f('svc.chain.pem'), '--host', 'svc.local']); eq(ok1.code, 0, 'verify ' + ok1.out);
|
||||
eq(run(['revoke', '--dir', D, '--ca', 'issuing', '--cert', f('svc.crt')]).code, 0, 'revoke');
|
||||
eq(run(['crl', '--dir', D, '--ca', 'issuing', '--out', f('svc-crl.pem')]).code, 0, 'crl');
|
||||
const rv = run(['verify', '--roots', path.join(D, 'root.crt'), '--chain', f('svc.chain.pem'), '--host', 'svc.local', '--crl', f('svc-crl.pem')]);
|
||||
eq(rv.code, 1, 'verify revocat'); has(rv.out, 'REFUSED (REVOKED)', 'motivul');
|
||||
const us = run(['unseal', '--key', f('svc.key'), '--out', f('svc.p8.pem')]); eq(us.code, 0, 'unseal ' + us.out);
|
||||
has(fs.readFileSync(f('svc.p8.pem'), 'utf8'), '-----BEGIN PRIVATE KEY-----', 'PKCS#8 in clar, la cerere');
|
||||
has(ossl(['pkey', '-in', f('svc.p8.pem'), '-noout', '-text']).out, 'ML-DSA-65', 'openssl citeste cheia desigilata');
|
||||
const us2 = run(['unseal', '--key', f('svc.key'), '--out', f('svc.p8.pem')]); eq(us2.code, 2, 'unseal peste un fisier existent'); has(us2.out, 'EXISTS', 'nimic suprascris la unseal');
|
||||
// AERE-SINTETIC: parola gresita dinadins (proba refuzului)
|
||||
const us3 = run(['unseal', '--key', f('svc.key'), '--out', f('svc.p8b.pem')], { ...env, AERE_PKI_PASSPHRASE: 'parola-gresita-lunga' }); eq(us3.code, 2, 'unseal cu parola gresita'); has(us3.out, 'KEY_LOCKED', 'motivul');
|
||||
const np = run(['issue', '--dir', D, '--ca', 'issuing', '--cn', 'x', '--out', f('x2')], { ...env, AERE_PKI_PASSPHRASE: '' }); eq(np.code, 2, 'fara parola'); has(np.out, 'PASSPHRASE', 'motivul fara parola');
|
||||
// AERE-SINTETIC: parola gresita dinadins (proba refuzului la emitere)
|
||||
const wp = run(['issue', '--dir', D, '--ca', 'issuing', '--cn', 'x', '--out', f('x3')], { ...env, AERE_PKI_PASSPHRASE: 'parola-gresita-lunga' }); eq(wp.code, 2, 'parola gresita'); has(wp.out, 'KEY_LOCKED', 'motivul parolei gresite');
|
||||
const ow = run(['init', '--dir', D, '--name', 'root']); eq(ow.code, 2, 'suprascriere'); has(ow.out, 'EXISTS', 'nimic suprascris');
|
||||
eq(/-----BEGIN PRIVATE KEY-----/.test(np.out + wp.out + ow.out + us.out + us2.out + us3.out), false, 'niciun material de cheie in mesaje');
|
||||
});
|
||||
|
||||
fs.rmSync(T, { recursive: true, force: true });
|
||||
const picate = rez.filter((r) => !r.ok);
|
||||
console.log(`\n${rez.length - picate.length}/${rez.length} probe trecute`);
|
||||
if (process.env.PKI_JSON) fs.writeFileSync(process.env.PKI_JSON, JSON.stringify(rez, null, 1));
|
||||
process.exitCode = picate.length ? 1 : 0;
|
||||
Reference in new issue
Block a user