Add crypto-inventory: a cryptographic inventory of source code as a CycloneDX 1.6 CBOM, with linear cost on hostile input; PKI DER messages in English
This commit is contained in:
1 parent
7d814d1bb8
commit
0f081f0847
49 files changed
+4342
-33
No files matched your search
@@ -0,0 +1,80 @@
|
||||
// Controlul negativ al probei de cost (test/proba-timp.mjs): proba trebuie sa iasa ROSIE pe cazul numit cand forma patratica e
|
||||
// pusa inapoi. Trei stari pe caz: PRINS (proba a masurat si cazul tinta e ROSU), SCAPAT (a ramas VERDE), STRICAT (copia nu s-a
|
||||
// putut face, ancora nu apare exact o data, sau proba nu a masurat).
|
||||
// V0 inventarul de dinainte de reparatie, din git (sarit si spus daca revizia nu e in istoricul depozitului)
|
||||
// -> rosii: pem, py-triplu, js-regex, js-linie, java-linie, java-kpg
|
||||
// P1 rezolvarea variabilelor fara memorie (fiecare apel reciteste fisierul) -> js-linie rosu
|
||||
// P2 esecurile literalului regex JS netinute minte -> js-regex rosu
|
||||
// P3 cautarea PEM fara pozitiile tinute minte (sfarsitul cautat de la fiecare antet) -> pem rosu
|
||||
// node test/control-negativ-timp.mjs -> 0 toate prinse, 1 unul scapat, 2 STRICAT
|
||||
import { mkdtempSync, cpSync, readFileSync, writeFileSync, readdirSync, rmSync, mkdirSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const AICI = dirname(fileURLToPath(import.meta.url));
|
||||
const RADACINA = join(AICI, '..');
|
||||
const PROBA = join(AICI, 'proba-timp.mjs');
|
||||
const REV = process.env.AERE_INV_REV_VECHE || 'db9d9543';
|
||||
let prinse = 0, stricate = 0, total = 0;
|
||||
|
||||
const copiaza = () => {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-timp-control-'));
|
||||
cpSync(join(RADACINA, 'inventar.mjs'), join(d, 'inventar.mjs'));
|
||||
cpSync(join(RADACINA, 'lib'), join(d, 'lib'), { recursive: true });
|
||||
return d;
|
||||
};
|
||||
|
||||
function ruleaza(id, d, tinte, doar) {
|
||||
const r = spawnSync(process.execPath, [PROBA, ...(doar ? ['--doar', doar.join(',')] : [])], { encoding: 'utf8', timeout: 600000, env: { ...process.env, CRYPTO_INVENTORY_MODULE: join(d, 'inventar.mjs') } });
|
||||
const out = r.stdout || '';
|
||||
if (!out.includes(`(modul: ${join(d, 'inventar.mjs')})`) || /^STRICAT/m.test(out)) { stricate++; console.log(` STRICAT ${id}: proba nu a masurat copia (cod ${r.status}) ${out.split('\n').filter((l) => /^STRICAT/.test(l)).join(' | ').slice(0, 160)}`); return; }
|
||||
const rosii = out.split('\n').filter((l) => /^ROSU/.test(l)).map((l) => l.split(/\s+/)[1].replace(/:$/, ''));
|
||||
const lipsa = tinte.filter((t) => !rosii.includes(t));
|
||||
if (r.status === 1 && !lipsa.length) { prinse++; console.log(` PRINS ${id}: rosii ${rosii.join(', ')}`); }
|
||||
else console.log(` SCAPAT ${id}: cod ${r.status}, au ramas verzi: ${lipsa.join(', ')}`);
|
||||
}
|
||||
|
||||
// V0: codul de dinainte, din git, in forma comisa (fara conversia capetelor de rand)
|
||||
total++;
|
||||
const git = (...a) => spawnSync('git', ['-c', 'core.autocrlf=false', ...a], { cwd: RADACINA, encoding: 'buffer', maxBuffer: 64 << 20 });
|
||||
const ls = git('ls-tree', '-r', '--name-only', '--full-tree', REV, 'tools/crypto-inventory/inventar.mjs', 'tools/crypto-inventory/lib');
|
||||
const fisiere = ls.status === 0 ? ls.stdout.toString().split('\n').filter(Boolean) : [];
|
||||
if (!fisiere.length) { total--; console.log(` SARIT V0: revizia ${REV} nu e in istoricul acestui depozit; NEMASURAT aici`); }
|
||||
else {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-timp-v0-'));
|
||||
try {
|
||||
let ok = true;
|
||||
for (const f of fisiere) {
|
||||
const b = git('show', `${REV}:${f}`);
|
||||
if (b.status !== 0) { ok = false; break; }
|
||||
const t = join(d, f.slice('tools/crypto-inventory/'.length));
|
||||
mkdirSync(dirname(t), { recursive: true });
|
||||
writeFileSync(t, b.stdout);
|
||||
}
|
||||
if (!ok || readFileSync(join(d, 'lib', 'pem.mjs'), 'utf8').includes('blocuriPem')) { stricate++; console.log(' STRICAT V0: revizia veche nu se citeste sau are deja reparatia'); }
|
||||
else ruleaza('V0', d, ['pem.txt', 'py-triplu.py', 'js-regex.js', 'js-linie.js', 'java-linie.java', 'java-kpg.java']);
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
const P = [
|
||||
['P1', 'lib/context.mjs', 'if (ctx.rezolvari.has(nume)) return ctx.rezolvari.get(nume);', "if (ctx.rezolvari.has(nume) && process.env.AERE_PLANTA_NICIODATA === 'da') return ctx.rezolvari.get(nume);", ['js-linie.js']],
|
||||
['P2', 'lib/lexer.mjs', 'if (esecRegex && esecRegex[j] & (inClasa ? 2 : 1)) break;', "if (esecRegex && esecRegex[j] & (inClasa ? 2 : 1) && process.env.AERE_PLANTA_NICIODATA === 'da') break;", ['js-regex.js']],
|
||||
['P3', 'lib/pem.mjs', 'const valabil = (c, de) => c && c.la <= de && (c.poz < 0 || c.poz >= de);', "const valabil = (c, de) => process.env.AERE_PLANTA_NICIODATA === 'da' && c && c.la <= de && (c.poz < 0 || c.poz >= de);", ['pem.txt']],
|
||||
];
|
||||
for (const [id, fisier, ancora, cu, tinte] of P) {
|
||||
total++;
|
||||
const d = copiaza();
|
||||
try {
|
||||
const cale = join(d, fisier);
|
||||
const text = readFileSync(cale, 'utf8');
|
||||
if (text.split(ancora).length !== 2) { stricate++; console.log(` STRICAT ${id}: ancora nu apare exact o data in ${fisier}`); continue; }
|
||||
writeFileSync(cale, text.replace(ancora, cu));
|
||||
const dif = ['inventar.mjs', ...readdirSync(join(d, 'lib')).map((f) => `lib/${f}`)].filter((f) => readFileSync(join(d, f), 'utf8') !== readFileSync(join(RADACINA, f), 'utf8'));
|
||||
if (dif.length !== 1 || dif[0] !== fisier) { stricate++; console.log(` STRICAT ${id}: copia difera in ${dif.join(', ') || 'nimic'}`); continue; }
|
||||
ruleaza(id, d, tinte, tinte);
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
}
|
||||
console.log(`\ncontrolul negativ al probei de cost: prinse ${prinse}/${total}, stricate ${stricate}`);
|
||||
process.exitCode = stricate ? 2 : prinse === total ? 0 : 1;
|
||||
@@ -0,0 +1,242 @@
|
||||
// Controlul negativ al suitei: strica, intr-o COPIE a modulului, cate o regula sau un detector si
|
||||
// cere ca proba tinta sa iasa ROSIE pe numele ei, ca suita sa fi rulat INTREAGA (aceleasi nume ca
|
||||
// linia de baza) si ca martorul neatins sa ramana VERDE. Altfel verdictul e STRICAT, nu "prins".
|
||||
// Un ciot care nu se poate pune (ancora lipsa sau dubla) e tot STRICAT: un control care nu a
|
||||
// plantat nimic nu a masurat nimic.
|
||||
// Folosire: node test/control-negativ.mjs (cod 0 doar daca toate mutatiile sunt PRINSE)
|
||||
import { mkdtempSync, cpSync, readFileSync, writeFileSync, readdirSync, rmSync, statSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const AICI = dirname(fileURLToPath(import.meta.url));
|
||||
const RADACINA = join(AICI, '..');
|
||||
const SUITA = join(AICI, 'proba.mjs');
|
||||
|
||||
const B = 'negativ: fisierul binar e sarit si numarat';
|
||||
const MUTATII = [
|
||||
{
|
||||
nume: 'secp256k1 clasificat quantum-safe',
|
||||
fisier: 'lib/catalog.mjs',
|
||||
ancora: "return f({ ...baza, ...rez({ c: CLS.V, qv: true, motiv, rec, q: 0, cl, oid: '1.2.840.10045.2.1' }) });",
|
||||
cu: "return f({ ...baza, ...rez({ c: e256k1 ? CLS.S : CLS.V, qv: true, motiv, rec, q: 0, cl, oid: '1.2.840.10045.2.1' }) });",
|
||||
tinta: 'clasificare: secp256k1 este quantum-vulnerable, cu recomandare de cont post-cuantic',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'comentariile // nu mai sunt ignorate (JS/Java/Go)',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: "if (c === '/' && d === '/') {",
|
||||
cu: "if (false && c === '/' && d === '/') {",
|
||||
tinta: 'negativ: comentariile JS nu produc gasiri',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'linia raportata cu unu mai mult',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: 'return { line: lo + 1, column: pos - inceputuri[lo] + 1 };',
|
||||
cu: 'return { line: lo + 2, column: pos - inceputuri[lo] + 1 };',
|
||||
tinta: 'pozitiv: js/node-crypto.mjs',
|
||||
martor: 'negativ: fisier fara criptografie da zero gasiri, si a fost citit',
|
||||
},
|
||||
{
|
||||
nume: 'variabila reasignata e "rezolvata" la prima valoare (ghicit)',
|
||||
fisier: 'lib/context.mjs',
|
||||
ancora: 'if (atribuiri.length !== 1) return null;',
|
||||
cu: 'if (atribuiri.length < 1) return null;',
|
||||
tinta: 'negativ: algoritm din variabila reasignata sau din parametru iese unknown, nu ghicit',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'fisierele binare nu mai sunt sarite',
|
||||
fisier: 'lib/scan.mjs',
|
||||
ancora: "if (eBinar(buf)) { noteaza('binary', rel); continue; }",
|
||||
cu: "if (false && eBinar(buf)) { noteaza('binary', rel); continue; }",
|
||||
tinta: B,
|
||||
martor: 'negativ: comentariile JS nu produc gasiri',
|
||||
},
|
||||
{
|
||||
nume: 'comentariile # nu mai sunt ignorate (Python)',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: " if (c === '#') {",
|
||||
cu: " if (false && c === '#') {",
|
||||
tinta: 'negativ: comentariile si docstring-urile Python nu produc gasiri',
|
||||
martor: 'pozitiv: js/node-crypto.mjs',
|
||||
},
|
||||
// 2026-09-29, revizuirea adversariala: formele liniare trebuie sa dea exact ce dadeau cele vechi
|
||||
{
|
||||
nume: 'cautarea PEM nu mai reia de la caracterul urmator dupa un antet fara sfarsit',
|
||||
fisier: 'lib/pem.mjs',
|
||||
ancora: '{ reBegin.lastIndex = m.index + 1; continue; }',
|
||||
cu: "{ if (process.env.AERE_PLANTA_NICIODATA === 'da') reBegin.lastIndex = m.index + 1; continue; }",
|
||||
tinta: 'limite: un bloc PEM care incepe in liniutele unui antet fara sfarsit e gasit',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'esecul unui literal regex JS tinut minte fara starea "in clasa"',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: 'if (esecRegex && esecRegex[j] & (inClasa ? 2 : 1)) break;',
|
||||
cu: "if (esecRegex && (esecRegex[j] & (inClasa ? 2 : 1) || (process.env.AERE_PLANTA_NICIODATA !== 'da' && esecRegex[j]))) break;",
|
||||
tinta: 'limite: literalul regex JS se cauta din starea lui, nu din ce a esuat alt literal pe acelasi rand',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'sirul neterminat Python nu mai muta inceputul randului',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: 'if (ultimaLinieNoua >= 0) primulPeRand = ultimaLinieNoua === j - 1 ? -1 : ultimaLinieNoua + 1;',
|
||||
cu: "if (ultimaLinieNoua >= 0) primulPeRand = ultimaLinieNoua === j - 1 && process.env.AERE_PLANTA_NICIODATA === 'da' ? -1 : ultimaLinieNoua + 1;",
|
||||
tinta: 'limite: docstring Python pe randul lui (si dupa un sir neterminat), dar nu dupa cod pe acelasi rand',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'plafonul de variabile pe fisier scos',
|
||||
fisier: 'lib/context.mjs',
|
||||
ancora: 'if (ctx.rezolvari.size >= REZOLVARI_PE_FISIER) {',
|
||||
cu: "if (ctx.rezolvari.size >= REZOLVARI_PE_FISIER && process.env.AERE_PLANTA_NICIODATA === 'da') {",
|
||||
tinta: 'limite: peste plafonul de variabile pe fisier numele ies unknown si fisierul se numara',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'caracterele de control din rezumat nu mai sunt inlocuite',
|
||||
fisier: 'lib/rezumat.mjs',
|
||||
ancora: "return L.map((l) => l.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, '?')).join('\\n');",
|
||||
cu: "return L.map((l) => (process.env.AERE_PLANTA_NICIODATA === 'da' ? l.replace(/[\\u0000-\\u001f\\u007f-\\u009f]/g, '?') : l)).join('\\n');",
|
||||
tinta: 'rezumat: caracterele de control din numele de fisiere nu ajung in terminal',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'MD5 clasificat quantum-safe',
|
||||
fisier: 'lib/catalog.mjs',
|
||||
ancora: "MD5: { n: 'MD5', c: CLS.W, oid: '1.2.840.113549.2.5' },",
|
||||
cu: "MD5: { n: 'MD5', c: CLS.S, oid: '1.2.840.113549.2.5' },",
|
||||
tinta: 'clasificare: MD5 si SHA-1 sunt weak-now, SHA-256 quantum-safe',
|
||||
martor: 'negativ: fisier prea mare sarit si numarat',
|
||||
},
|
||||
{
|
||||
nume: 'bom-ref fara amprenta (coliziuni)',
|
||||
fisier: 'lib/cbom.mjs',
|
||||
ancora: ":${createHash('sha256').update(k).digest('hex').slice(0, 12)}`;\n const cp",
|
||||
cu: '`;\n const cp',
|
||||
tinta: 'cbom: bom-ref unice si stabile intre doua rulari',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: '--fail-on vulnerable ignorat',
|
||||
fisier: 'lib/rezumat.mjs',
|
||||
ancora: "if ((cer.has('vulnerable') || cer.has('any')) && vuln.length)",
|
||||
cu: "if (false && (cer.has('vulnerable') || cer.has('any')) && vuln.length)",
|
||||
tinta: 'cli: --fail-on vulnerable iese 1 pe cod vulnerabil si 0 pe cod fara criptografie',
|
||||
martor: 'cbom: structura CycloneDX 1.6 (campuri obligatorii, tipuri, enumerari)',
|
||||
},
|
||||
{
|
||||
nume: 'apelurile din siruri numarate ca folosire',
|
||||
fisier: 'lib/context.mjs',
|
||||
ancora: 'for (const m of code.matchAll(g)) if (!inSir(siruri, m.index)) r.push(m);',
|
||||
cu: 'for (const m of code.matchAll(g)) r.push(m);',
|
||||
tinta: 'negativ: apelul scris intr-un sir JS nu e folosire',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'fisierul prea mare sarit fara sa fie numarat',
|
||||
fisier: 'lib/scan.mjs',
|
||||
ancora: "if (marime > o.maxFileBytes) { noteaza('tooLarge', rel, `${marime} bytes`); continue; }",
|
||||
cu: 'if (marime > o.maxFileBytes) { continue; }',
|
||||
tinta: 'negativ: fisier prea mare sarit si numarat',
|
||||
martor: 'pozitiv: js/node-crypto.mjs',
|
||||
},
|
||||
{
|
||||
nume: 'suprimarea importurilor acoperite de apeluri scoasa (numarare dubla)',
|
||||
fisier: 'lib/context.mjs',
|
||||
ancora: " if (g.evidenceKind !== 'import' || !g.suppressedBy) return true;",
|
||||
cu: ' return true;',
|
||||
tinta: 'pozitiv: go/crypto.go',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'blocul PEM intreg (cu cheia privata) pus in contextul gasirii',
|
||||
fisier: 'lib/pem.mjs',
|
||||
ancora: '{ bucata: `-----BEGIN ${tip}-----` }',
|
||||
cu: '{ bucata: m[0] }',
|
||||
tinta: 'pozitiv: cheie privata generata la rulare e raportata, iar valoarea ei nu apare in iesire',
|
||||
martor: B,
|
||||
},
|
||||
];
|
||||
|
||||
function copiaza() {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-control-'));
|
||||
cpSync(join(RADACINA, 'inventar.mjs'), join(d, 'inventar.mjs'));
|
||||
cpSync(join(RADACINA, 'lib'), join(d, 'lib'), { recursive: true });
|
||||
return d;
|
||||
}
|
||||
|
||||
function fisiereModul(d) {
|
||||
return ['inventar.mjs', ...readdirSync(join(d, 'lib')).map((f) => `lib/${f}`)].filter((f) => statSync(join(d, f)).isFile()).sort();
|
||||
}
|
||||
|
||||
function ruleaza(d) {
|
||||
const r = spawnSync(process.execPath, [SUITA, '--json'], {
|
||||
encoding: 'utf8',
|
||||
timeout: 300000,
|
||||
env: { ...process.env, CRYPTO_INVENTORY_MODULE: join(d, 'inventar.mjs') },
|
||||
});
|
||||
const ultima = (r.stdout || '').trim().split('\n').pop() || '';
|
||||
try {
|
||||
const j = JSON.parse(ultima);
|
||||
return { ok: true, j, status: r.status };
|
||||
} catch {
|
||||
return { ok: false, motiv: `suita nu a raportat JSON (status ${r.status}): ${(r.stderr || '').trim().split('\n').slice(0, 3).join(' | ')}` };
|
||||
}
|
||||
}
|
||||
|
||||
// linia de baza: o copie neatinsa, toata verde, si suita chiar a masurat COPIA
|
||||
const baza = copiaza();
|
||||
let linieBaza;
|
||||
try {
|
||||
const r = ruleaza(baza);
|
||||
if (!r.ok) { console.log(`STRICAT linia de baza: ${r.motiv}`); process.exitCode = 3; }
|
||||
else if (r.j.modul !== join(baza, 'inventar.mjs')) { console.log(`STRICAT linia de baza: suita a masurat ${r.j.modul}, nu copia`); process.exitCode = 3; }
|
||||
else if (r.j.verzi !== r.j.rulate) { console.log(`STRICAT linia de baza: ${r.j.rosii} probe rosii pe copia neatinsa: ${Object.keys(r.j.erori).join('; ')}`); process.exitCode = 3; }
|
||||
else linieBaza = r.j;
|
||||
} finally { rmSync(baza, { recursive: true, force: true }); }
|
||||
|
||||
if (linieBaza) {
|
||||
const numeBaza = Object.keys(linieBaza.rezultate).sort();
|
||||
console.log(`linia de baza: ${linieBaza.rulate} probe, toate verzi, pe o copie neatinsa a modulului\n`);
|
||||
const verdicte = [];
|
||||
for (const mu of MUTATII) {
|
||||
const d = copiaza();
|
||||
let verdict;
|
||||
let detaliu = '';
|
||||
try {
|
||||
const cale = join(d, mu.fisier);
|
||||
const text = readFileSync(cale, 'utf8');
|
||||
const n = text.split(mu.ancora).length - 1;
|
||||
if (!numeBaza.includes(mu.tinta) || !numeBaza.includes(mu.martor)) {
|
||||
verdict = 'STRICAT'; detaliu = 'tinta sau martorul nu exista in suita';
|
||||
} else if (n !== 1) {
|
||||
verdict = 'STRICAT'; detaliu = `ciotul nu s-a putut pune: ancora apare de ${n} ori`;
|
||||
} else {
|
||||
writeFileSync(cale, text.replace(mu.ancora, mu.cu));
|
||||
// cmp: exact un fisier difera de original, si acela e cel mutat
|
||||
const diferite = fisiereModul(d).filter((f) => readFileSync(join(d, f), 'utf8') !== readFileSync(join(RADACINA, f), 'utf8'));
|
||||
if (diferite.length !== 1 || diferite[0] !== mu.fisier) {
|
||||
verdict = 'STRICAT'; detaliu = `copia difera in: ${diferite.join(', ') || 'nimic'}`;
|
||||
} else {
|
||||
const r = ruleaza(d);
|
||||
if (!r.ok) { verdict = 'STRICAT'; detaliu = r.motiv; }
|
||||
else if (r.j.modul !== join(d, 'inventar.mjs')) { verdict = 'STRICAT'; detaliu = `suita a masurat ${r.j.modul}`; }
|
||||
else if (JSON.stringify(Object.keys(r.j.rezultate).sort()) !== JSON.stringify(numeBaza)) { verdict = 'STRICAT'; detaliu = `suita nu a rulat intreaga: ${r.j.rulate} din ${linieBaza.rulate}`; }
|
||||
else if (r.j.rezultate[mu.tinta] !== 'ROSU') { verdict = 'NEPRINS'; detaliu = 'proba tinta a ramas verde'; }
|
||||
else if (r.j.rezultate[mu.martor] !== 'VERDE') { verdict = 'STRICAT'; detaliu = `martorul a iesit rosu: ${r.j.erori[mu.martor]}`; }
|
||||
else { verdict = 'PRINS'; detaliu = `tinta rosie (${r.j.erori[mu.tinta].slice(0, 110)}); ${r.j.rosii} din ${r.j.rulate} rosii in total; martor verde`; }
|
||||
}
|
||||
}
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
verdicte.push(verdict);
|
||||
console.log(`${verdict.padEnd(8)} ${mu.nume}\n tinta: ${mu.tinta}\n ${detaliu}`);
|
||||
}
|
||||
const prinse = verdicte.filter((v) => v === 'PRINS').length;
|
||||
console.log(`\n${prinse} din ${MUTATII.length} mutatii PRINSE; ${verdicte.filter((v) => v === 'NEPRINS').length} neprinse; ${verdicte.filter((v) => v === 'STRICAT').length} stricate`);
|
||||
process.exitCode = prinse === MUTATII.length ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// Echivalenta formelor liniare din 0.2.0 cu formele din 0.1.0 (2026-09-29, revizuirea adversariala): aceleasi gasiri si biblioteci
|
||||
// pe arbori reali, si aceleasi rezultate ale lexerului si ale cautarii PEM pe texte generate din jetoanele care conteaza.
|
||||
// 0.1.0 se ia din git (revizia AERE_INV_REV_VECHE, implicit db9d9543), in forma comisa; intr-o copie fara istoric iese SARIT.
|
||||
// node test/echivalenta-0.1.0.mjs [--iteratii N] [dosar...] (implicit: fixturile si dosarul uneltei)
|
||||
// -> 0 identic, 1 o diferenta (tiparita), 2 NEMASURAT (revizia veche lipseste sau nimic comparat)
|
||||
// Singura diferenta asteptata e textul motivului pentru "unknown" (spune acum si plafonul de variabile); se normalizeaza.
|
||||
import { mkdtempSync, writeFileSync, mkdirSync, rmSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const AICI = dirname(fileURLToPath(import.meta.url));
|
||||
const RAD = join(AICI, '..');
|
||||
const REV = process.env.AERE_INV_REV_VECHE || 'db9d9543';
|
||||
let ITER = 20000;
|
||||
const dosare = [];
|
||||
for (let k = 2; k < process.argv.length; k++) {
|
||||
if (process.argv[k] === '--iteratii') ITER = Number(process.argv[++k]);
|
||||
else dosare.push(process.argv[k]);
|
||||
}
|
||||
const DOSARE = dosare.length ? dosare : [join(AICI, 'fixturi'), RAD];
|
||||
|
||||
const git = (...a) => spawnSync('git', ['-c', 'core.autocrlf=false', ...a], { cwd: RAD, encoding: 'buffer', maxBuffer: 64 << 20 });
|
||||
const ls = git('ls-tree', '-r', '--name-only', '--full-tree', REV, 'tools/crypto-inventory/inventar.mjs', 'tools/crypto-inventory/lib');
|
||||
const fis = ls.status === 0 ? ls.stdout.toString().split('\n').filter(Boolean) : [];
|
||||
if (!fis.length) { console.log(`SARIT: revizia ${REV} nu e in istoricul acestui depozit; NEMASURAT aici`); process.exit(2); }
|
||||
const vechi = mkdtempSync(join(tmpdir(), 'ci-v010-'));
|
||||
let dif = 0, comparate = 0;
|
||||
try {
|
||||
for (const f of fis) {
|
||||
const b = git('show', `${REV}:${f}`);
|
||||
if (b.status !== 0) { console.log(`NEMASURAT: git show ${f}`); process.exit(2); }
|
||||
const t = join(vechi, f.slice('tools/crypto-inventory/'.length));
|
||||
mkdirSync(dirname(t), { recursive: true });
|
||||
writeFileSync(t, b.stdout);
|
||||
}
|
||||
const imp = (r, m) => import(pathToFileURL(join(r, 'lib', m)).href);
|
||||
const [SV, SN, LV, LN, PN] = await Promise.all([imp(vechi, 'scan.mjs'), imp(RAD, 'scan.mjs'), imp(vechi, 'lexer.mjs'), imp(RAD, 'lexer.mjs'), imp(RAD, 'pem.mjs')]);
|
||||
if (SV.VERSIUNE !== '0.1.0') { console.log(`NEMASURAT: revizia ${REV} are versiunea ${SV.VERSIUNE}, nu 0.1.0`); process.exit(2); }
|
||||
|
||||
// 1. arbori reali
|
||||
const norm = (g) => JSON.stringify({ ...g, reason: String(g.reason).replace(/, which (cannot be resolved statically|this tool does not resolve statically).*$/, ', which [motiv]') });
|
||||
for (const d of DOSARE) {
|
||||
const a = SV.scaneaza(d), b = SN.scaneaza(d);
|
||||
const ka = a.findings.map(norm), kb = b.findings.map(norm);
|
||||
const sa = new Set(ka), sb = new Set(kb);
|
||||
const doarV = ka.filter((x) => !sb.has(x)), doarN = kb.filter((x) => !sa.has(x));
|
||||
const ok = !doarV.length && !doarN.length && ka.length === kb.length && JSON.stringify(a.libraries) === JSON.stringify(b.libraries);
|
||||
comparate += ka.length;
|
||||
if (!ok) dif++;
|
||||
console.log(`${ok ? 'IDENTIC ' : 'DIFERIT '} ${d}: ${a.stats.filesSeen} fisiere, gasiri ${ka.length}/${kb.length}, biblioteci ${a.libraries.length}/${b.libraries.length}`);
|
||||
for (const x of [...doarV.slice(0, 3).map((x) => 'numai 0.1.0: ' + x), ...doarN.slice(0, 3).map((x) => 'numai 0.2.0: ' + x)]) console.log(' ' + x.slice(0, 260));
|
||||
}
|
||||
|
||||
// 2. texte generate: lexerul pe patru limbaje si cautarea PEM (fata de regexul din 0.1.0)
|
||||
const RE_010 = /-----BEGIN ((?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY|PUBLIC KEY|RSA PUBLIC KEY|CERTIFICATE)-----([A-Za-z0-9+/=\s:,\-\r\n]*?)-----END \1-----/g;
|
||||
let seed = 12345;
|
||||
const rnd = (n) => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed % n; };
|
||||
const gen = (jet, max) => { let s = ''; const L = rnd(max); for (let i = 0; i < L; i++) s += jet[rnd(jet.length)]; return s; };
|
||||
const JET = {
|
||||
python: ['"', "'", '"""', "'''", '\\', '\n', ' ', '\t', 'r', 'b', 'f', 'u', 'x', '#', '=', '(', ')', 'rb', '\r\n', 'a1'],
|
||||
javascript: ['=/[', '=/', ' x/', '"', "'", '`', '${', '}', '{', '/', '//', '/*', '*/', '[', ']', '\\', '\n', ' ', '=', '(', ')', 'return', 'x', '1', '.', ',', 'typeof'],
|
||||
java: ['"', "'", '"""', '\\', '\n', ' ', '/', '//', '/*', '*/', 'x', '=', '(', ')'],
|
||||
go: ['"', "'", '`', '\\', '\n', ' ', '/', '//', '/*', '*/', 'x', '=', '(', ')'],
|
||||
};
|
||||
const JET_PEM = ['-----BEGIN CERTIFICATE-----', '-----END CERTIFICATE-----', '-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----',
|
||||
'-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----', '-----BEGIN PUBLIC KEY-----', '-----END PUBLIC KEY-----',
|
||||
'BEGIN CERTIFICATE-----', 'BEGIN PRIVATE KEY-----', 'AAAA', 'QUJD', '\n', ' ', '.', '-', '--', '-----', '"', 'BEGIN', '=', ':', ' ', '\r\n'];
|
||||
const cat = {};
|
||||
for (let k = 0; k < ITER; k++) {
|
||||
for (const [limbaj, jet] of Object.entries(JET)) {
|
||||
const t = gen(jet, 40);
|
||||
const a = LV.curata(t, limbaj), b = LN.curata(t, limbaj);
|
||||
comparate++;
|
||||
if (a.code !== b.code || JSON.stringify(a.siruri) !== JSON.stringify(b.siruri)) { cat[limbaj] = (cat[limbaj] || 0) + 1; if (dif++ < 5) console.log(`DIFERIT lexer ${limbaj}: ${JSON.stringify(t)}`); }
|
||||
}
|
||||
const t = gen(JET_PEM, 30);
|
||||
const a = [...t.matchAll(RE_010)].map((m) => [m.index, m[1], m[2]]);
|
||||
const b = [...PN.blocuriPem(t)].map((x) => [x.index, x.tip, x.corp]);
|
||||
comparate++;
|
||||
if (JSON.stringify(a) !== JSON.stringify(b)) { cat.pem = (cat.pem || 0) + 1; if (dif++ < 5) console.log(`DIFERIT pem: ${JSON.stringify(t)}`); }
|
||||
}
|
||||
console.log(`texte generate: ${ITER} runde (lexer x4 + PEM), diferente ${JSON.stringify(cat)}`);
|
||||
} finally { rmSync(vechi, { recursive: true, force: true }); }
|
||||
console.log(`\n${dif ? 'DIFERIT' : 'IDENTIC'}: ${dif} diferente in ${comparate} comparatii (0.1.0 din ${REV} fata de 0.2.0)`);
|
||||
process.exitCode = dif ? 1 : comparate ? 0 : 2;
|
||||
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
// Fixtura: Go. In Go un import nefolosit nu compileaza, deci importul e dovada de folosire.
|
||||
package fixturi
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/md5"
|
||||
"crypto/mlkem"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/sha256" // EXPECT: SHA-256 | quantum-safe
|
||||
"crypto/tls"
|
||||
_ "crypto/sha512" // EXPECT: SHA-512 | quantum-safe
|
||||
)
|
||||
|
||||
func Exemple(data []byte) {
|
||||
k, _ := rsa.GenerateKey(rand.Reader, 3072) // EXPECT: RSA-3072 | quantum-vulnerable
|
||||
e, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) // EXPECT: ECDSA-secp256r1 | quantum-vulnerable
|
||||
s := md5.Sum(data) // EXPECT: MD5 | weak-now
|
||||
m := hmac.New(sha1.New, data) // EXPECT: HMAC-SHA-1 | weak-now
|
||||
dk, _ := mlkem.GenerateKey768() // EXPECT: ML-KEM-768 | quantum-safe
|
||||
cfg := &tls.Config{
|
||||
MinVersion: tls.VersionTLS12, // EXPECT: TLSv1.2 | quantum-vulnerable
|
||||
CurvePreferences: []tls.CurveID{tls.X25519MLKEM768, tls.CurveP256}, // EXPECT: X25519MLKEM768 | quantum-safe ; ECDH-secp256r1 | quantum-vulnerable
|
||||
}
|
||||
f := sha256.New
|
||||
_, _, _, _, _, _, _ = k, e, s, m, dk, cfg, f
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Fixtura: JCA, JSSE si Bouncy Castle. Fisierul nu se compileaza; e doar text pentru scaner.
|
||||
package fixturi;
|
||||
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import org.bouncycastle.crypto.engines.RC4Engine; // EXPECT: RC4 | weak-now
|
||||
import org.bouncycastle.pqc.crypto.mlkem.MLKEMParameters;
|
||||
|
||||
public class Crypto {
|
||||
private static final String DIGEST = "SHA-256";
|
||||
|
||||
public void exemple(String algDinParametru) throws Exception {
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); // EXPECT: RSA-4096 | quantum-vulnerable
|
||||
kpg.initialize(4096);
|
||||
KeyPairGenerator ec = KeyPairGenerator.getInstance("EC"); // EXPECT: EC-secp256r1 | quantum-vulnerable
|
||||
ec.initialize(new ECGenParameterSpec("secp256r1"));
|
||||
Signature s1 = Signature.getInstance("SHA256withECDSA"); // EXPECT: ECDSA | quantum-vulnerable
|
||||
Signature s2 = Signature.getInstance("SHA1withRSA"); // EXPECT: RSA | weak-now
|
||||
Signature s3 = Signature.getInstance("ML-DSA-65"); // EXPECT: ML-DSA-65 | quantum-safe
|
||||
Cipher c1 = Cipher.getInstance("AES"); // EXPECT: AES-ECB | weak-now
|
||||
Cipher c2 = Cipher.getInstance("AES/GCM/NoPadding"); // EXPECT: AES-GCM | quantum-safe
|
||||
Cipher c3 = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); // EXPECT: RSA | quantum-vulnerable
|
||||
Cipher c4 = Cipher.getInstance("DESede/CBC/PKCS5Padding"); // EXPECT: 3DES-CBC | weak-now
|
||||
KeyAgreement ka = KeyAgreement.getInstance("X25519"); // EXPECT: X25519 | quantum-vulnerable
|
||||
MessageDigest md = MessageDigest.getInstance("MD5"); // EXPECT: MD5 | weak-now
|
||||
MessageDigest md2 = MessageDigest.getInstance(DIGEST); // EXPECT: SHA-256 | quantum-safe
|
||||
MessageDigest md3 = MessageDigest.getInstance(algDinParametru); // EXPECT: MessageDigest.getInstance | unknown
|
||||
SSLContext tls = SSLContext.getInstance("TLSv1.1"); // EXPECT: TLSv1.1 | weak-now
|
||||
Object p = MLKEMParameters.ml_kem_768; // EXPECT: ML-KEM-768 | quantum-safe
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Fixtura: biblioteci recunoscute din importuri (TypeScript).
|
||||
import { Wallet, verifyMessage } from 'ethers';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { secp256k1 } from '@noble/curves/secp256k1'; // EXPECT: ECDSA-secp256k1 | quantum-vulnerable
|
||||
import { ml_dsa65 } from '@noble/post-quantum/ml-dsa'; // EXPECT: ML-DSA-65 | quantum-safe
|
||||
import { ml_kem768 } from '@noble/post-quantum/ml-kem'; // EXPECT: ML-KEM-768 | quantum-safe
|
||||
import elliptic from 'elliptic';
|
||||
import { sha1 } from '../vendor/node_modules/@noble/hashes/legacy.js'; // EXPECT: SHA-1 | weak-now
|
||||
|
||||
const ec = new elliptic.ec('p256'); // EXPECT: EC-secp256r1 | quantum-vulnerable
|
||||
|
||||
export async function semneaza(privateKey: string, payload: object) {
|
||||
const w = new Wallet(privateKey); // EXPECT: ECDSA-secp256k1 | quantum-vulnerable
|
||||
const sig = await w.signMessage('hello'); // EXPECT: ECDSA-secp256k1 | quantum-vulnerable
|
||||
const ok = verifyMessage('hello', sig); // EXPECT: ECDSA-secp256k1 | quantum-vulnerable
|
||||
const t1 = jwt.sign(payload, privateKey, { algorithm: 'RS256' }); // EXPECT: JWS RS256 | quantum-vulnerable
|
||||
const t2 = jwt.verify(t1, privateKey, { algorithms: ['ES256', 'HS256'] }); // EXPECT: JWS ES256 | quantum-vulnerable ; JWS HS256 | quantum-safe
|
||||
return { ec, ok, t2, secp256k1, ml_dsa65, ml_kem768, sha1 };
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// Fixtura: node:crypto. Fiecare rand cu o folosire poarta marcajul EXPECT al gasirii asteptate.
|
||||
// Fisierul nu se executa niciodata; e doar text pentru scaner.
|
||||
import crypto from 'node:crypto';
|
||||
import { createHash, generateKeyPairSync } from 'crypto';
|
||||
|
||||
const HASH_ALG = 'sha256';
|
||||
|
||||
export function exemple(data, key, iv, algDinParametru, pemDinConfig) {
|
||||
const a = createHash('md5').update(data).digest('hex'); // EXPECT: MD5 | weak-now
|
||||
const b = crypto.createHash('sha1'); // EXPECT: SHA-1 | weak-now
|
||||
const c = crypto.createHash(HASH_ALG); // EXPECT: SHA-256 | quantum-safe
|
||||
const d = crypto.createHash(algDinParametru); // EXPECT: createHash | unknown
|
||||
const { publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }); // EXPECT: RSA-2048 | quantum-vulnerable
|
||||
const k2 = crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1' }); // EXPECT: EC-secp256k1 | quantum-vulnerable
|
||||
const k3 = crypto.generateKeyPairSync('ed25519'); // EXPECT: Ed25519 | quantum-vulnerable
|
||||
const k4 = crypto.generateKeyPairSync('ml-dsa-65'); // EXPECT: ML-DSA-65 | quantum-safe
|
||||
const k5 = crypto.generateKeyPairSync('ml-kem-768'); // EXPECT: ML-KEM-768 | quantum-safe
|
||||
const s = crypto.createSign('RSA-SHA256'); // EXPECT: RSA | quantum-vulnerable
|
||||
const v = crypto.createVerify('SHA1'); // EXPECT: signature-with-SHA-1 | weak-now
|
||||
const e = crypto.createECDH('prime256v1'); // EXPECT: ECDH-secp256r1 | quantum-vulnerable
|
||||
const c1 = crypto.createCipheriv('aes-256-gcm', key, iv); // EXPECT: AES-256-GCM | quantum-safe
|
||||
const c2 = crypto.createCipheriv('des-ede3-cbc', key, iv); // EXPECT: 3DES-CBC | weak-now
|
||||
const c3 = crypto.createCipheriv('aes-128-ecb', key, null); // EXPECT: AES-128-ECB | weak-now
|
||||
const c4 = crypto.createDecipheriv('aes-128-cbc', key, iv); // EXPECT: AES-128-CBC | quantum-safe
|
||||
const enc = crypto.publicEncrypt(publicKey, data); // EXPECT: RSA | quantum-vulnerable
|
||||
const h = crypto.createHmac('sha256', key); // EXPECT: HMAC-SHA-256 | quantum-safe
|
||||
const dh = crypto.getDiffieHellman('modp2'); // EXPECT: DH-1024 | weak-now
|
||||
const sig = crypto.sign(null, data, key); // EXPECT: crypto.sign | unknown
|
||||
const pk = crypto.createPrivateKey(pemDinConfig); // EXPECT: createPrivateKey | unknown
|
||||
return [a, b, c, d, k2, k3, k4, k5, s, v, e, c1, c2, c3, c4, enc, h, dh, sig, pk];
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Fixtura: optiuni TLS in Node.
|
||||
const tls = require('node:tls');
|
||||
const https = require('https');
|
||||
|
||||
const server = tls.createServer({
|
||||
minVersion: 'TLSv1', // EXPECT: TLSv1.0 | weak-now
|
||||
ecdhCurve: 'X25519MLKEM768:X25519:prime256v1', // EXPECT: X25519MLKEM768 | quantum-safe ; X25519 | quantum-vulnerable ; ECDH-secp256r1 | quantum-vulnerable
|
||||
});
|
||||
|
||||
const agent = new https.Agent({ minVersion: 'TLSv1.2', maxVersion: 'TLSv1.3' }); // EXPECT: TLSv1.2 | quantum-vulnerable ; TLSv1.3 | unknown
|
||||
|
||||
const PQ = 'X25519MLKEM768';
|
||||
const GRUPURI = { hibrid: 'X25519MLKEM768' };
|
||||
const a2 = tls.connect({ ecdhCurve: PQ }); // EXPECT: X25519MLKEM768 | quantum-safe
|
||||
const a3 = tls.connect({ ecdhCurve: `${PQ}:X25519` }); // EXPECT: X25519MLKEM768 | quantum-safe ; X25519 | quantum-vulnerable
|
||||
const a4 = tls.connect({ ecdhCurve: GRUPURI[process.env.MOD] }); // EXPECT: tls ecdhCurve | unknown
|
||||
|
||||
module.exports = { server, agent, a2, a3, a4 };
|
||||
@@ -0,0 +1,15 @@
|
||||
// Fixtura: WebCrypto (browser sau globalThis.crypto in Node).
|
||||
const subtle = globalThis.crypto.subtle;
|
||||
|
||||
export async function webcrypto(data) {
|
||||
const rsa = await subtle.generateKey(
|
||||
{ name: 'RSA-OAEP', modulusLength: 3072, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, // EXPECT: RSA-3072 | quantum-vulnerable
|
||||
true, ['encrypt', 'decrypt']);
|
||||
const ec = await subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-384' }, true, ['sign', 'verify']); // EXPECT: ECDSA-secp384r1 | quantum-vulnerable
|
||||
const ed = await subtle.generateKey('Ed25519', true, ['sign', 'verify']); // EXPECT: Ed25519 | quantum-vulnerable
|
||||
const x = await subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']); // EXPECT: X25519 | quantum-vulnerable
|
||||
const aes = await subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']); // EXPECT: AES-256-GCM | quantum-safe
|
||||
const d1 = await subtle.digest('SHA-1', data); // EXPECT: SHA-1 | weak-now
|
||||
const d2 = await subtle.digest({ name: 'SHA-384' }, data); // EXPECT: SHA-384 | quantum-safe
|
||||
return [rsa, ec, ed, x, aes, d1, d2];
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import crypto from 'node:crypto';
|
||||
export const h = crypto.createHash('md5');
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
// umplutura pentru limita de marime
|
||||
@@ -0,0 +1,2 @@
|
||||
import crypto from 'node:crypto';
|
||||
export const h = crypto.createHash('sha256');
|
||||
@@ -0,0 +1,9 @@
|
||||
module example.com/fixtura
|
||||
|
||||
go 1.24
|
||||
|
||||
require (
|
||||
github.com/cloudflare/circl v1.6.1
|
||||
golang.org/x/crypto v0.36.0
|
||||
golang.org/x/text v0.23.0
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "fixtura-manifest",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"ethers": "^6.13.0",
|
||||
"lodash": "^4.17.21",
|
||||
"jsonwebtoken": "9.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@noble/post-quantum": "0.4.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<project>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk18on</artifactId>
|
||||
<version>1.78.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.13.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,3 @@
|
||||
requests==2.32.3
|
||||
cryptography==43.0.1
|
||||
PyJWT[crypto]>=2.8
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBmzCCAUGgAwIBAgIUSB9o0oiJeX65E+oyUE6ukzrvT2MwCgYIKoZIzj0EAwIw
|
||||
IzEhMB8GA1UEAwwYY3J5cHRvLWludmVudG9yeS1maXh0dXJlMB4XDTI2MDkyNTA4
|
||||
NTAwM1oXDTM2MDkyMjA4NTAwM1owIzEhMB8GA1UEAwwYY3J5cHRvLWludmVudG9y
|
||||
eS1maXh0dXJlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEPwYXPWSiw0/Y4M2Q
|
||||
zkQHHXLNkRJv0W0Ml7C3vN9HyKl1C9LrNB5evAruKJVTTh+J5KJaxfjDLFldkczR
|
||||
2IKBEaNTMFEwHQYDVR0OBBYEFPE/ChbrkN4O/z7KgfHWZR/+XBBmMB8GA1UdIwQY
|
||||
MBaAFPE/ChbrkN4O/z7KgfHWZR/+XBBmMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZI
|
||||
zj0EAwIDSAAwRQIhAMAK5Uxt090TnPPp5xn3cG1vD1BSNEc+ZJBI0JPPeCl1AiAM
|
||||
egBkNslxucBd5XhFrWbvxCIRBedHr0dZGJYrHIZqrg==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,10 @@
|
||||
Test-only public key generated for the crypto-inventory fixtures.
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvhFbgeI5qpI+99IZBwOt
|
||||
nuwndPRr+gpT5oLNlXVqjOhWSJZWPGgt4cNGw7XgeSujl91Wl8TGCoRAgq4xOxmw
|
||||
d+WVycVlCMKK7Peaepe/wL+DMEABVDuqlkiFEe90/6Kk6sIge555qBGBa/tsvkxX
|
||||
trU1khKI9A7g1YAkSkmUiCAPTktvZ/ED8r6P61j5u8lXnbGeNU7a7vivgWF4CaF4
|
||||
a4m4oAVHUxWLKmeSLN8CeIn6AZSmqc5e/0DMEMGuzqC/XBKWz55bhkzq/CAMdPcI
|
||||
1zbFcXkUM7tWJzLbgAW4R3Bpe1GUD8+h0fG9v8xnJOf1vQ1M4veJ1OQrEhFwuI4+
|
||||
TQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,14 @@
|
||||
// MessageDigest.getInstance("MD5") intr-un comentariu nu e o folosire.
|
||||
package fixturi;
|
||||
|
||||
public class Comentarii {
|
||||
/* Cipher.getInstance("DES") intr-un comentariu bloc */
|
||||
/**
|
||||
* Signature.getInstance("SHA1withRSA") in Javadoc.
|
||||
*/
|
||||
private final String doc = "KeyPairGenerator.getInstance(\"RSA\") in a string";
|
||||
|
||||
public String doc() {
|
||||
return doc;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Fixtura negativa Go: niciun import criptografic.
|
||||
package fixturi
|
||||
|
||||
/*
|
||||
import "crypto/md5"
|
||||
*/
|
||||
|
||||
// md5.Sum(data) intr-un comentariu nu e o folosire.
|
||||
func Nimic() string {
|
||||
return "crypto/rsa rsa.GenerateKey(rand.Reader, 1024)"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Fixtura negativa: fisierul importa node:crypto doar pentru UUID-uri. Comentariile pomenesc
|
||||
// API-uri reale; niciunul nu e o folosire si scanerul trebuie sa dea ZERO gasiri.
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
// crypto.createHash('md5') intr-un comentariu nu e o folosire.
|
||||
// const k = crypto.generateKeyPairSync('rsa', { modulusLength: 1024 });
|
||||
/* crypto.createCipheriv('des-ede3-cbc', key, iv) intr-un comentariu bloc */
|
||||
/**
|
||||
* Exemplu din documentatie: crypto.createSign('RSA-SHA1').
|
||||
* RSA, ECDSA, secp256k1 si X25519 sunt aici doar cuvinte.
|
||||
*/
|
||||
export function id() {
|
||||
return crypto.randomUUID(); // crypto.createHmac('sha1', k) tot comentariu
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Modul fara criptografie.
|
||||
|
||||
Documentatia pomeneste rsa.generate_private_key(public_exponent=65537, key_size=1024)
|
||||
si hashlib.md5(data), dar nu le cheama.
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
|
||||
def f(x):
|
||||
"""Returneaza x. Nu foloseste hashlib.sha1(x)."""
|
||||
# hashlib.md5(x) intr-un comentariu nu e o folosire
|
||||
text = "hashlib.md5 apare aici doar ca text"
|
||||
return x, text, hashlib
|
||||
@@ -0,0 +1,9 @@
|
||||
export function sign(x) {
|
||||
return Math.sign(x);
|
||||
}
|
||||
|
||||
export function createHash(n) {
|
||||
return { n, hash: n * 31 };
|
||||
}
|
||||
|
||||
export const rezultat = [sign(-3), createHash(7)].map((v) => JSON.stringify(v));
|
||||
@@ -0,0 +1,9 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
export const doc = "Call crypto.createHash('md5') to hash (documentation string).";
|
||||
export const tpl = `Use crypto.createCipheriv('des-ede3-cbc', key, iv) at ${Date.now()}`;
|
||||
export const eticheta = 'crypto.generateKeyPairSync("rsa", { modulusLength: 1024 })';
|
||||
export const re = /createHash\('sha1'\)/;
|
||||
export function id() {
|
||||
return crypto.randomUUID();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Fixtura: algoritmi dati prin variabile care NU se pot rezolva static. Trebuie "unknown", nu ghicit.
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
let alg = 'md5';
|
||||
alg = 'sha256';
|
||||
|
||||
export function h(data, algDinApel, opts) {
|
||||
const a = crypto.createHash(alg); // EXPECT: createHash | unknown
|
||||
const b = crypto.createHash(algDinApel); // EXPECT: createHash | unknown
|
||||
const c = crypto.createCipheriv(opts.cipher, opts.key, opts.iv); // EXPECT: createCipheriv | unknown
|
||||
return [a, b, c, data];
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Fixtura: criptografie in Python. Fisierul nu se executa; e doar text pentru scaner."""
|
||||
import hashlib
|
||||
import hmac
|
||||
import ssl
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa, ec, ed25519, padding
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from Crypto.Cipher import AES, DES3
|
||||
from ecdsa import SigningKey, SECP256k1
|
||||
import jwt
|
||||
import oqs
|
||||
|
||||
DIGEST = "sha256"
|
||||
|
||||
|
||||
def exemple(data, key, alg_din_parametru):
|
||||
k1 = rsa.generate_private_key(public_exponent=65537, key_size=1024) # EXPECT: RSA-1024 | weak-now
|
||||
k2 = ec.generate_private_key(ec.SECP384R1()) # EXPECT: EC-secp384r1 | quantum-vulnerable
|
||||
k3 = ed25519.Ed25519PrivateKey.generate() # EXPECT: Ed25519 | quantum-vulnerable
|
||||
sig = k2.sign(data, ec.ECDSA(hashes.SHA256())) # EXPECT: ECDSA | quantum-vulnerable ; SHA-256 | quantum-safe
|
||||
ct = k1.public_key().encrypt(data, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # EXPECT: RSA | quantum-vulnerable ; SHA-256 | quantum-safe
|
||||
h1 = hashlib.md5(data).hexdigest() # EXPECT: MD5 | weak-now
|
||||
h2 = hashlib.new(DIGEST) # EXPECT: SHA-256 | quantum-safe
|
||||
h3 = hashlib.new(alg_din_parametru) # EXPECT: hashlib.new | unknown
|
||||
mac = hmac.new(key, data, digestmod="sha1") # EXPECT: HMAC-SHA-1 | weak-now
|
||||
c1 = AES.new(key, AES.MODE_ECB) # EXPECT: AES-ECB | weak-now
|
||||
c2 = DES3.new(key, DES3.MODE_CBC) # EXPECT: 3DES-CBC | weak-now
|
||||
sk = SigningKey.generate(curve=SECP256k1) # EXPECT: ECDSA-secp256k1 | quantum-vulnerable
|
||||
tok = jwt.encode({"a": 1}, key, algorithm="ES256K") # EXPECT: JWS ES256K | quantum-vulnerable
|
||||
kem = oqs.KeyEncapsulation("ML-KEM-768") # EXPECT: ML-KEM-768 | quantum-safe
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # EXPECT: TLS (negotiated) | unknown
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2 # EXPECT: TLSv1.2 | quantum-vulnerable
|
||||
return [k3, sig, ct, h1, h2, h3, mac, c1, c2, sk, tok, kem]
|
||||
@@ -0,0 +1,72 @@
|
||||
// Proba de cost: inventarul trebuie sa ramana LINIAR pe fisiere facute anume (2026-09-29, revizuirea adversariala). Formele vechi
|
||||
// ale cautarii PEM, ale literalului regex JS, ale docstring-ului Python, ale rezolvarii variabilelor si ale variabilei atribuite
|
||||
// in Java costau patratic: un singur fisier de 1 MB (marimea maxima implicita) tinea scanarea minute intregi.
|
||||
// Fiecare caz se scaneaza la doua marimi, a doua de 4 ori prima (64 si 256 KB; PEM 256 KB si 1 MB), fiecare intr-un proces
|
||||
// separat cu termen; liniar inseamna ~4x, patratic ~16x. Verdict pe caz: VERDE daca t2 <= 6 * t1 + 250 ms si t2 < 10 s; ROSU
|
||||
// altfel (si la depasirea termenului).
|
||||
// node test/proba-timp.mjs [--doar caz1,caz2] -> 0 toate verzi, 1 unul rosu, 2 STRICAT (o masurare nu a pornit)
|
||||
// Modulul masurat se schimba cu CRYPTO_INVENTORY_MODULE=<cale>/inventar.mjs (asa il foloseste controlul negativ).
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
||||
import { join, resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const AICI = dirname(fileURLToPath(import.meta.url));
|
||||
const CALE_MODUL = process.env.CRYPTO_INVENTORY_MODULE ? resolve(process.env.CRYPTO_INVENTORY_MODULE) : join(AICI, '..', 'inventar.mjs');
|
||||
const TERMEN_MS = 20000;
|
||||
|
||||
// unitatea se repeta pana la marime; '@' se inlocuieste cu un contor (nume distincte)
|
||||
export const CAZURI = {
|
||||
// pem: cautarea sfarsitului e nativa (indexOf), deci forma patratica se vede abia spre marimea maxima implicita
|
||||
'pem.txt': ['-----BEGIN CERTIFICATE-----AAAA\n', 256, 1024],
|
||||
'py-triplu.py': 'x="""a"""+',
|
||||
'py-linie.py': 'hashlib.new(x)+',
|
||||
'js-regex.js': '=/[',
|
||||
'js-linie.js': 'crypto.createHash(x)+',
|
||||
'js-func.js': 'crypto.createHash(q)\nfunction (',
|
||||
'java-linie.java': 'Cipher.getInstance(x)+',
|
||||
'java-kpg.java': 'k = KeyPairGenerator.getInstance("EC")+',
|
||||
};
|
||||
|
||||
const marimi = (nume) => (Array.isArray(CAZURI[nume]) ? CAZURI[nume].slice(1) : [64, 256]);
|
||||
const unitate = (nume) => (Array.isArray(CAZURI[nume]) ? CAZURI[nume][0] : CAZURI[nume]);
|
||||
const genereaza = (unit, kb) => unit.repeat(Math.max(1, Math.floor((kb * 1024) / unit.length)));
|
||||
|
||||
const arg = (f) => { const i = process.argv.indexOf(f); return i >= 0 ? process.argv[i + 1] : null; };
|
||||
|
||||
if (arg('--caz')) {
|
||||
// copilul: scaneaza un singur fisier si tipareste milisecundele
|
||||
const nume = arg('--caz'); const kb = Number(arg('--kb'));
|
||||
const inv = await import(pathToFileURL(CALE_MODUL).href);
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-timp-'));
|
||||
try {
|
||||
writeFileSync(join(d, nume), genereaza(unitate(nume), kb));
|
||||
const t0 = process.hrtime.bigint();
|
||||
const rez = inv.scan(d);
|
||||
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
|
||||
if (rez.stats.filesSeen !== 1 || rez.stats.codeFilesTotal + rez.stats.textFilesPemOnly !== 1) throw new Error('fisierul nu a fost citit');
|
||||
console.log(JSON.stringify({ ms }));
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
} else {
|
||||
const doar = arg('--doar') ? arg('--doar').split(',') : Object.keys(CAZURI);
|
||||
const masoara = (nume, kb) => {
|
||||
const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--caz', nume, '--kb', String(kb)], { encoding: 'utf8', timeout: TERMEN_MS, env: process.env });
|
||||
if (r.error && r.error.code === 'ETIMEDOUT') return { termen: true };
|
||||
try { return { ms: JSON.parse((r.stdout || '').trim().split('\n').pop()).ms }; } catch { return { stricat: `cod ${r.status}: ${(r.stderr || '').trim().split('\n').slice(-1)[0]}` }; }
|
||||
};
|
||||
let rosii = 0, stricate = 0;
|
||||
for (const nume of doar) {
|
||||
if (!CAZURI[nume]) { stricate++; console.log(`STRICAT ${nume}: caz necunoscut`); continue; }
|
||||
const [k1, k2] = marimi(nume);
|
||||
const a = masoara(nume, k1);
|
||||
const b = a.ms !== undefined ? masoara(nume, k2) : a.termen ? {} : { stricat: `nemasurat (${k1} KB a cazut)` };
|
||||
if (a.stricat || b.stricat) { stricate++; console.log(`STRICAT ${nume}: ${a.stricat || b.stricat}`); continue; }
|
||||
if (a.termen || b.termen) { rosii++; console.log(`ROSU ${nume}: peste ${TERMEN_MS / 1000} s la ${a.termen ? k1 : k2} KB`); continue; }
|
||||
const ok = b.ms <= 6 * a.ms + 250 && b.ms < 10000;
|
||||
if (!ok) rosii++;
|
||||
console.log(`${ok ? 'VERDE ' : 'ROSU '} ${nume.padEnd(16)} ${String(k1).padStart(4)} KB ${a.ms.toFixed(0).padStart(6)} ms | ${String(k2).padStart(4)} KB ${b.ms.toFixed(0).padStart(6)} ms x${(b.ms / Math.max(a.ms, 1)).toFixed(1)}`);
|
||||
}
|
||||
console.log(`\ncostul inventarului: ${doar.length - rosii - stricate}/${doar.length} liniare, ${rosii} rosii, ${stricate} stricate (modul: ${CALE_MODUL})`);
|
||||
process.exitCode = stricate ? 2 : rosii ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
// Suita de probe a inventarului criptografic.
|
||||
// Folosire: node test/proba.mjs [--json]
|
||||
// Modulul masurat se poate schimba cu CRYPTO_INVENTORY_MODULE=<cale>/inventar.mjs (asa il foloseste
|
||||
// control-negativ.mjs pe o copie stricata). Fixturile raman mereu cele din test/fixturi.
|
||||
// Fiecare proba ruleaza izolat: o proba care arunca iese ROSU cu mesajul ei, restul ruleaza mai departe.
|
||||
import { readFileSync, readdirSync, statSync, existsSync, mkdtempSync, writeFileSync, rmSync, copyFileSync } from 'node:fs';
|
||||
import { join, resolve, dirname } from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { generateKeyPairSync } from 'node:crypto';
|
||||
|
||||
const AICI = dirname(fileURLToPath(import.meta.url));
|
||||
const FIX = join(AICI, 'fixturi');
|
||||
const CALE_MODUL = process.env.CRYPTO_INVENTORY_MODULE ? resolve(process.env.CRYPTO_INVENTORY_MODULE) : join(AICI, '..', 'inventar.mjs');
|
||||
const inv = await import(pathToFileURL(CALE_MODUL).href);
|
||||
const CA_JSON = process.argv.includes('--json');
|
||||
|
||||
// numarul total de marcaje EXPECT scrise de mana in fixturi; o schimbare aici se face constient
|
||||
const MARCAJE_ASTEPTATE = 96;
|
||||
const FISIERE_CU_MARCAJE = ['js/node-crypto.mjs', 'js/webcrypto.js', 'js/biblioteci.ts', 'js/tls.cjs', 'python/crypto_py.py', 'java/Crypto.java', 'go/crypto.go', 'negative/variabile.js'];
|
||||
|
||||
const probe = [];
|
||||
const proba = (nume, fn) => probe.push({ nume, fn });
|
||||
function asigura(cond, mesaj) { if (!cond) throw new Error(mesaj); }
|
||||
|
||||
const memo = new Map();
|
||||
function scan(dir, optiuni = {}) {
|
||||
const k = dir + JSON.stringify(optiuni);
|
||||
if (!memo.has(k)) {
|
||||
try { memo.set(k, { rez: inv.scan(dir, optiuni) }); } catch (err) { memo.set(k, { err }); }
|
||||
}
|
||||
const r = memo.get(k);
|
||||
if (r.err) throw r.err;
|
||||
return r.rez;
|
||||
}
|
||||
|
||||
function marcaje(rel) {
|
||||
const r = [];
|
||||
readFileSync(join(FIX, rel), 'utf8').split('\n').forEach((l, i) => {
|
||||
const m = /EXPECT:\s*(.+?)\s*$/.exec(l);
|
||||
if (!m) return;
|
||||
for (const p of m[1].split(' ; ')) {
|
||||
const [n, c] = p.split(' | ').map((s) => s.trim());
|
||||
r.push(`${i + 1}|${n}|${c}`);
|
||||
}
|
||||
});
|
||||
return r.sort();
|
||||
}
|
||||
|
||||
function gasiriDin(rez, rel) {
|
||||
return rez.findings.filter((g) => g.file === rel);
|
||||
}
|
||||
|
||||
function comparaExact(rel) {
|
||||
const rez = scan(FIX);
|
||||
const ast = marcaje(rel);
|
||||
asigura(ast.length > 0, `${rel}: fixtura nu are marcaje`);
|
||||
const real = gasiriDin(rez, rel).map((g) => `${g.line}|${g.name}|${g.classification}`).sort();
|
||||
const lipsa = ast.filter((x) => !real.includes(x));
|
||||
const extra = real.filter((x) => !ast.includes(x));
|
||||
asigura(!lipsa.length && !extra.length && ast.length === real.length,
|
||||
`${rel}: lipsa [${lipsa.join(', ')}] extra [${extra.join(', ')}] (asteptate ${ast.length}, gasite ${real.length})`);
|
||||
}
|
||||
|
||||
// --- pozitive: fiecare gasire asteptata, cu linia si clasa ei, si nimic in plus ---
|
||||
for (const rel of FISIERE_CU_MARCAJE.filter((f) => !f.startsWith('negative/'))) {
|
||||
proba(`pozitiv: ${rel}`, () => comparaExact(rel));
|
||||
}
|
||||
|
||||
proba('pozitiv: numarul total de marcaje EXPECT este cel scris', () => {
|
||||
const n = FISIERE_CU_MARCAJE.reduce((s, f) => s + marcaje(f).length, 0);
|
||||
asigura(n === MARCAJE_ASTEPTATE, `marcaje citite ${n}, scrise ${MARCAJE_ASTEPTATE}`);
|
||||
const rez = scan(FIX);
|
||||
const inFisiere = rez.findings.filter((g) => FISIERE_CU_MARCAJE.includes(g.file)).length;
|
||||
asigura(inFisiere === MARCAJE_ASTEPTATE, `gasiri in fisierele cu marcaje: ${inFisiere}, marcaje ${MARCAJE_ASTEPTATE}`);
|
||||
});
|
||||
|
||||
proba('pozitiv: variabila rezolvata la un literal unic poarta resolvedFrom', () => {
|
||||
const g = gasiriDin(scan(FIX), 'js/node-crypto.mjs').find((x) => x.name === 'SHA-256');
|
||||
asigura(g && /HASH_ALG \(line 6\)/.test(g.resolvedFrom || ''), `resolvedFrom: ${g && g.resolvedFrom}`);
|
||||
const j = gasiriDin(scan(FIX), 'java/Crypto.java').find((x) => x.name === 'SHA-256');
|
||||
asigura(j && /DIGEST/.test(j.resolvedFrom || ''), `java resolvedFrom: ${j && j.resolvedFrom}`);
|
||||
});
|
||||
|
||||
proba('pozitiv: manifestele dau biblioteci declarate, nu gasiri', () => {
|
||||
const rez = scan(join(FIX, 'manifeste'));
|
||||
asigura(rez.findings.length === 0, `gasiri din manifeste: ${rez.findings.length}`);
|
||||
const libs = rez.libraries.map((b) => `${b.file}:${b.line} ${b.name}`).sort();
|
||||
const ast = ['go.mod:6 github.com/cloudflare/circl', 'go.mod:7 golang.org/x/crypto', 'package.json:10 @noble/post-quantum',
|
||||
'package.json:5 ethers', 'package.json:7 jsonwebtoken', 'pom.xml:5 org.bouncycastle:bcprov-jdk18on',
|
||||
'requirements.txt:2 cryptography', 'requirements.txt:3 pyjwt'].sort();
|
||||
asigura(JSON.stringify(libs) === JSON.stringify(ast), `biblioteci: ${libs.join(' | ')}`);
|
||||
const bom = inv.buildCbom(rez, { deterministic: true });
|
||||
const c = bom.components.filter((x) => x.type === 'library');
|
||||
asigura(c.length === 8 && c.every((x) => x.properties.some((p) => p.name.endsWith('declared-only') && p.value === 'true')), 'componentele library nu poarta declared-only');
|
||||
});
|
||||
|
||||
proba('pozitiv: material PEM (certificat si cheie publica)', () => {
|
||||
const rez = scan(FIX);
|
||||
const c = gasiriDin(rez, 'material/certificat-proba.pem');
|
||||
asigura(c.length === 1 && c[0].assetType === 'certificate' && c[0].name === 'EC-secp256r1' && c[0].classification === 'quantum-vulnerable' && c[0].line === 1, `certificat: ${JSON.stringify(c.map((x) => [x.assetType, x.name, x.line]))}`);
|
||||
asigura(/crypto-inventory-fixture/.test(c[0].certificate.subjectName), 'subiectul certificatului lipseste');
|
||||
const p = gasiriDin(rez, 'material/cheie-publica-proba.pem');
|
||||
asigura(p.length === 1 && p[0].assetType === 'related-crypto-material' && p[0].material.type === 'public-key' && p[0].name === 'RSA-2048' && p[0].line === 2, `cheie publica: ${JSON.stringify(p.map((x) => [x.assetType, x.name, x.line]))}`);
|
||||
});
|
||||
|
||||
proba('pozitiv: cheie privata generata la rulare e raportata, iar valoarea ei nu apare in iesire', () => {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-cheie-'));
|
||||
try {
|
||||
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||
const pem = privateKey.export({ type: 'pkcs8', format: 'pem' });
|
||||
writeFileSync(join(d, 'config.txt'), `setari\n${pem}`);
|
||||
const rez = inv.scan(d);
|
||||
asigura(rez.findings.length === 1, `gasiri: ${rez.findings.length}`);
|
||||
const g = rez.findings[0];
|
||||
asigura(g.assetType === 'related-crypto-material' && g.material.type === 'private-key' && g.name === 'EC-secp256r1' && g.line === 2, `gasirea: ${JSON.stringify([g.assetType, g.material, g.name, g.line])}`);
|
||||
const corp = pem.split('\n').filter((l) => l && !l.startsWith('-----')).join('');
|
||||
const iesire = JSON.stringify(inv.buildCbom(rez)) + JSON.stringify(rez.findings) + inv.renderSummary(rez);
|
||||
for (let i = 0; i + 24 <= corp.length; i += 8) asigura(!iesire.includes(corp.slice(i, i + 24)), `o bucata din cheia privata apare in iesire (offset ${i})`);
|
||||
} finally {
|
||||
rmSync(d, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// --- clasificare ---
|
||||
proba('clasificare: secp256k1 este quantum-vulnerable, cu recomandare de cont post-cuantic', () => {
|
||||
const a = inv.classify({ grup: 'SECP256K1' });
|
||||
asigura(a.classification === 'quantum-vulnerable' && a.quantumVulnerable === true, `clasa ${a.classification}`);
|
||||
asigura(/post-quantum key/.test(a.recommendation) && /not a library swap/.test(a.recommendation), 'recomandarea nu vorbeste de contul post-cuantic');
|
||||
const f = gasiriDin(scan(FIX), 'js/node-crypto.mjs').find((x) => x.curve === 'secp256k1');
|
||||
asigura(f && f.classification === 'quantum-vulnerable', 'gasirea secp256k1 din fixtura nu e quantum-vulnerable');
|
||||
});
|
||||
|
||||
proba('clasificare: MD5 si SHA-1 sunt weak-now, SHA-256 quantum-safe', () => {
|
||||
const c = (h) => inv.classify({ grup: 'HASH', hash: h }).classification;
|
||||
asigura(c('MD5') === 'weak-now' && c('SHA1') === 'weak-now' && c('SHA256') === 'quantum-safe', `MD5 ${c('MD5')} SHA1 ${c('SHA1')} SHA256 ${c('SHA256')}`);
|
||||
});
|
||||
|
||||
proba('clasificare: AES-128 quantum-safe cu nota Grover, ECB weak-now, DES weak-now', () => {
|
||||
const a = inv.classify({ grup: 'CIPHER', nume: 'AES', param: '128', mod: 'gcm' });
|
||||
asigura(a.classification === 'quantum-safe' && /Grover/.test(a.reason + a.recommendation) && a.nistQuantumSecurityLevel === 1, `AES-128: ${a.classification} ${a.nistQuantumSecurityLevel}`);
|
||||
asigura(inv.classify({ grup: 'CIPHER', nume: 'AES', param: '256', mod: 'ecb' }).classification === 'weak-now', 'ECB nu e weak-now');
|
||||
asigura(inv.classify({ grup: 'CIPHER', nume: 'DES' }).classification === 'weak-now', 'DES nu e weak-now');
|
||||
asigura(inv.classify({ grup: 'TLS', param: '1.1', rol: 'min' }).classification === 'weak-now', 'TLS 1.1 nu e weak-now');
|
||||
});
|
||||
|
||||
proba('clasificare: fiecare gasire vulnerabila sau slaba are motiv si recomandare', () => {
|
||||
const rez = scan(FIX);
|
||||
for (const g of rez.findings) {
|
||||
asigura(g.reason && g.reason.length > 20, `${g.file}:${g.line} ${g.name} fara motiv`);
|
||||
if (g.classification === 'quantum-vulnerable' || g.classification === 'weak-now' || g.classification === 'unknown') {
|
||||
asigura(g.recommendation && g.recommendation.length > 20, `${g.file}:${g.line} ${g.name} (${g.classification}) fara recomandare`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
proba('clasificare: JWT asimetric spune ca standardul post-cuantic nu e final', () => {
|
||||
const g = gasiriDin(scan(FIX), 'js/biblioteci.ts').find((x) => x.name === 'JWS RS256');
|
||||
asigura(g && /no final standard/.test(g.recommendation) && /draft/.test(g.recommendation), 'recomandarea JWT nu spune ca nu exista standard final');
|
||||
});
|
||||
|
||||
// --- negative ---
|
||||
function controlPozitivMd5() {
|
||||
const g = gasiriDin(scan(FIX), 'js/node-crypto.mjs').find((x) => x.name === 'MD5');
|
||||
asigura(g, 'controlul pozitiv al metodei: MD5 din js/node-crypto.mjs lipseste, deci un zero nu inseamna nimic');
|
||||
}
|
||||
|
||||
proba('negativ: comentariile JS nu produc gasiri', () => {
|
||||
controlPozitivMd5();
|
||||
const g = gasiriDin(scan(FIX), 'negative/comentarii.js');
|
||||
asigura(g.length === 0, `comentariile au produs: ${g.map((x) => `${x.line} ${x.name}`).join(', ')}`);
|
||||
});
|
||||
|
||||
proba('negativ: apelul scris intr-un sir JS nu e folosire', () => {
|
||||
controlPozitivMd5();
|
||||
const g = gasiriDin(scan(FIX), 'negative/siruri.js');
|
||||
asigura(g.length === 0, `sirurile au produs: ${g.map((x) => `${x.line} ${x.name}`).join(', ')}`);
|
||||
});
|
||||
|
||||
proba('negativ: comentariile si docstring-urile Python nu produc gasiri', () => {
|
||||
const rez = scan(FIX);
|
||||
asigura(gasiriDin(rez, 'python/crypto_py.py').some((x) => x.name === 'MD5'), 'controlul pozitiv: hashlib.md5 din fixtura Python lipseste');
|
||||
const g = gasiriDin(rez, 'negative/docstring.py');
|
||||
asigura(g.length === 0, `docstring/comentariu au produs: ${g.map((x) => `${x.line} ${x.name}`).join(', ')}`);
|
||||
});
|
||||
|
||||
proba('negativ: comentariile si sirurile Java si Go nu produc gasiri', () => {
|
||||
const rez = scan(FIX);
|
||||
asigura(gasiriDin(rez, 'java/Crypto.java').some((x) => x.name === 'MD5') && gasiriDin(rez, 'go/crypto.go').some((x) => x.name === 'MD5'), 'controlul pozitiv: MD5 din fixturile Java/Go lipseste');
|
||||
const g = [...gasiriDin(rez, 'negative/Comentarii.java'), ...gasiriDin(rez, 'negative/comentarii.go')];
|
||||
asigura(g.length === 0, `au produs: ${g.map((x) => `${x.file}:${x.line} ${x.name}`).join(', ')}`);
|
||||
});
|
||||
|
||||
proba('negativ: fisier fara criptografie da zero gasiri, si a fost citit', () => {
|
||||
const rez = scan(join(FIX, 'negative'));
|
||||
asigura(rez.stats.filesSeen === 7 && rez.stats.codeFilesTotal === 7, `vazute ${rez.stats.filesSeen}, analizate ${rez.stats.codeFilesTotal}`);
|
||||
const g = gasiriDin(rez, 'fara-cripto.js');
|
||||
asigura(g.length === 0, `fara-cripto.js a produs ${g.length}`);
|
||||
});
|
||||
|
||||
proba('negativ: algoritm din variabila reasignata sau din parametru iese unknown, nu ghicit', () => {
|
||||
comparaExact('negative/variabile.js');
|
||||
const g = gasiriDin(scan(FIX), 'negative/variabile.js');
|
||||
asigura(g.every((x) => x.classification === 'unknown' && !x.resolvedFrom), 'o variabila nerezolvabila a primit o valoare');
|
||||
});
|
||||
|
||||
proba('negativ: fisierul binar e sarit si numarat', () => {
|
||||
const rez = scan(join(FIX, 'binar'));
|
||||
asigura(rez.stats.filesSeen === 1 && rez.stats.notRead.binary === 1 && rez.findings.length === 0, `vazute ${rez.stats.filesSeen}, binare ${rez.stats.notRead.binary}, gasiri ${rez.findings.length}`);
|
||||
asigura(rez.stats.notReadExamples.binary.includes('modul.js'), 'exemplul binar lipseste din statistica');
|
||||
// control pozitiv: aceiasi octeti fara NUL dau gasirea, deci zeroul de mai sus vine din saritura
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-binar-'));
|
||||
try {
|
||||
const b = readFileSync(join(FIX, 'binar', 'modul.js'));
|
||||
writeFileSync(join(d, 'modul.js'), Buffer.from([...b].filter((x) => x !== 0)));
|
||||
const r2 = inv.scan(d);
|
||||
asigura(r2.findings.some((x) => x.name === 'MD5'), 'controlul pozitiv: fara NUL, fisierul nu produce MD5');
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
proba('negativ: fisier prea mare sarit si numarat', () => {
|
||||
const rez = scan(join(FIX, 'limite'), { maxFileBytes: 400 });
|
||||
asigura(rez.stats.filesSeen === 2 && rez.stats.notRead.tooLarge === 1, `vazute ${rez.stats.filesSeen}, prea mari ${rez.stats.notRead.tooLarge}`);
|
||||
asigura(/^mare\.js \(\d+ bytes\)$/.test(rez.stats.notReadExamples.tooLarge[0] || ''), `exemplu: ${rez.stats.notReadExamples.tooLarge[0]}`);
|
||||
asigura(!rez.findings.some((x) => x.file === 'mare.js') && rez.findings.some((x) => x.file === 'mic.js'), 'gasirile nu corespund limitei');
|
||||
const tot = scan(join(FIX, 'limite'));
|
||||
asigura(tot.findings.some((x) => x.file === 'mare.js' && x.name === 'MD5'), 'controlul pozitiv: fara limita, mare.js nu da MD5');
|
||||
});
|
||||
|
||||
proba('negativ: limita de fisiere numara restul', () => {
|
||||
const rez = scan(join(FIX, 'limite'), { maxFiles: 1 });
|
||||
asigura(rez.stats.filesSeen === 2 && rez.stats.notRead.fileLimit === 1 && rez.stats.codeFilesTotal === 1, `vazute ${rez.stats.filesSeen}, peste limita ${rez.stats.notRead.fileLimit}`);
|
||||
});
|
||||
|
||||
// --- cazurile-limita ale formelor liniare (2026-09-29, revizuirea adversariala: cautarea PEM, literalul regex JS, docstring-ul
|
||||
// Python si rezolvarea variabilelor aveau cost patratic; formele noi trebuie sa dea EXACT ce dadeau cele vechi, si aici stau
|
||||
// cazurile pe care o forma liniara scrisa gresit le-ar schimba). Modulele se iau de langa modulul masurat (copia controlului).
|
||||
const LIB = join(dirname(CALE_MODUL), 'lib');
|
||||
const lexer = await import(pathToFileURL(join(LIB, 'lexer.mjs')).href);
|
||||
const pem = await import(pathToFileURL(join(LIB, 'pem.mjs')).href);
|
||||
const contextMod = await import(pathToFileURL(join(LIB, 'context.mjs')).href);
|
||||
|
||||
proba('limite: un bloc PEM care incepe in liniutele unui antet fara sfarsit e gasit', () => {
|
||||
const corp = 'A'.repeat(64);
|
||||
const t = `-----BEGIN PRIVATE KEY-----BEGIN CERTIFICATE-----${corp}-----END CERTIFICATE-----`;
|
||||
const b = [...pem.blocuriPem(t)].map((x) => `${x.index}|${x.tip}|${x.corp}`);
|
||||
asigura(JSON.stringify(b) === JSON.stringify([`22|CERTIFICATE|${corp}`]), `blocuri: ${JSON.stringify(b)}`);
|
||||
const fara = [...pem.blocuriPem(`-----BEGIN CERTIFICATE-----${corp}."-----END CERTIFICATE-----`)];
|
||||
asigura(fara.length === 0, 'un caracter din afara alfabetului corpului inainte de sfarsit trebuie sa anuleze blocul');
|
||||
});
|
||||
|
||||
proba('limite: literalul regex JS se cauta din starea lui, nu din ce a esuat alt literal pe acelasi rand', () => {
|
||||
// primul `/` deschide o clasa care nu se inchide (esec pana la capatul randului, trecand prin 8 IN clasa); al doilea porneste
|
||||
// din 8 IN AFARA clasei si se inchide la 10
|
||||
const r = lexer.curata('x =/[ =/ x/;', 'javascript');
|
||||
asigura(JSON.stringify(r.siruri) === JSON.stringify([[7, 11]]), `siruri: ${JSON.stringify(r.siruri)}`);
|
||||
});
|
||||
|
||||
proba('limite: docstring Python pe randul lui (si dupa un sir neterminat), dar nu dupa cod pe acelasi rand', () => {
|
||||
// docstring-ul de dupa sirul neterminat e INDENTAT: spatiile de inainte de el sunt pe randul nou, nu in coada sirului
|
||||
const t = "a = 'abc\n '''doc'''\ny = '''s'''\n r'''d2'''\n";
|
||||
const r = lexer.curata(t, 'python');
|
||||
asigura(!r.code.includes('doc') && !r.code.includes('d2'), `docstring-urile trebuiau golite: ${JSON.stringify(r.code)}`);
|
||||
asigura(r.code.includes("'''s'''"), `sirul triplu de dupa cod trebuia pastrat: ${JSON.stringify(r.code)}`);
|
||||
const s = t.indexOf("'''s'''");
|
||||
asigura(r.siruri.some(([a, b]) => a === s && b === s + 7), `intervalul sirului s lipseste: ${JSON.stringify(r.siruri)}`);
|
||||
});
|
||||
|
||||
proba('limite: peste plafonul de variabile pe fisier numele ies unknown si fisierul se numara', () => {
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-plafon-'));
|
||||
try {
|
||||
const n = contextMod.REZOLVARI_PE_FISIER;
|
||||
const linii = ["import { createHash } from 'node:crypto';"];
|
||||
for (let i = 0; i <= n; i++) linii.push(`const h${i} = 'sha256';`, `createHash(h${i});`);
|
||||
writeFileSync(join(d, 'multe.mjs'), linii.join('\n') + '\n');
|
||||
const rez = inv.scan(d);
|
||||
const rezolvate = rez.findings.filter((g) => g.name === 'SHA-256' && g.resolvedFrom).length;
|
||||
const necunoscute = rez.findings.filter((g) => g.classification === 'unknown').length;
|
||||
asigura(rezolvate === n && necunoscute === 1, `rezolvate ${rezolvate} (cerut ${n}), unknown ${necunoscute} (cerut 1)`);
|
||||
asigura(rez.stats.resolutionLimitFiles === 1 && rez.stats.resolutionLimitExamples[0] === 'multe.mjs', `statistica: ${rez.stats.resolutionLimitFiles}`);
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
// --- CBOM ---
|
||||
const E = {
|
||||
bom: ['$schema', 'bomFormat', 'specVersion', 'serialNumber', 'version', 'metadata', 'components', 'services', 'externalReferences', 'dependencies', 'compositions', 'properties', 'vulnerabilities', 'annotations', 'formulation', 'declarations', 'definitions', 'signature'],
|
||||
component: ['type', 'mime-type', 'bom-ref', 'supplier', 'manufacturer', 'authors', 'author', 'publisher', 'group', 'name', 'version', 'description', 'scope', 'hashes', 'licenses', 'copyright', 'cpe', 'purl', 'omniborId', 'swhid', 'swid', 'modified', 'pedigree', 'externalReferences', 'properties', 'components', 'evidence', 'releaseNotes', 'modelCard', 'data', 'cryptoProperties', 'signature', 'tags'],
|
||||
componentType: ['application', 'framework', 'library', 'container', 'platform', 'operating-system', 'device', 'device-driver', 'firmware', 'file', 'machine-learning-model', 'data', 'cryptographic-asset'],
|
||||
cryptoProperties: ['assetType', 'algorithmProperties', 'certificateProperties', 'relatedCryptoMaterialProperties', 'protocolProperties', 'oid'],
|
||||
assetType: ['algorithm', 'certificate', 'protocol', 'related-crypto-material'],
|
||||
algorithmProperties: ['primitive', 'parameterSetIdentifier', 'curve', 'executionEnvironment', 'implementationPlatform', 'certificationLevel', 'mode', 'padding', 'cryptoFunctions', 'classicalSecurityLevel', 'nistQuantumSecurityLevel'],
|
||||
primitive: ['drbg', 'mac', 'block-cipher', 'stream-cipher', 'signature', 'hash', 'pke', 'xof', 'kdf', 'key-agree', 'kem', 'ae', 'combiner', 'other', 'unknown'],
|
||||
mode: ['cbc', 'ecb', 'ccm', 'gcm', 'cfb', 'ofb', 'ctr', 'other', 'unknown'],
|
||||
padding: ['pkcs5', 'pkcs7', 'pkcs1v15', 'oaep', 'raw', 'other', 'unknown'],
|
||||
cryptoFunctions: ['generate', 'keygen', 'encrypt', 'decrypt', 'digest', 'tag', 'keyderive', 'sign', 'verify', 'encapsulate', 'decapsulate', 'other', 'unknown'],
|
||||
protocolProperties: ['type', 'version', 'cipherSuites', 'ikev2TransformTypes', 'cryptoRefArray'],
|
||||
protocolType: ['tls', 'ssh', 'ipsec', 'ike', 'sstp', 'wpa', 'other', 'unknown'],
|
||||
certificateProperties: ['subjectName', 'issuerName', 'notValidBefore', 'notValidAfter', 'signatureAlgorithmRef', 'subjectPublicKeyRef', 'certificateFormat', 'certificateExtension'],
|
||||
relatedCryptoMaterialProperties: ['type', 'id', 'state', 'algorithmRef', 'creationDate', 'activationDate', 'updateDate', 'expirationDate', 'value', 'size', 'format', 'securedBy'],
|
||||
materialType: ['private-key', 'public-key', 'secret-key', 'key', 'ciphertext', 'signature', 'digest', 'initialization-vector', 'nonce', 'seed', 'salt', 'shared-secret', 'tag', 'additional-data', 'password', 'credential', 'token', 'other', 'unknown'],
|
||||
evidence: ['identity', 'occurrences', 'callstack', 'licenses', 'copyright'],
|
||||
occurrence: ['bom-ref', 'location', 'line', 'offset', 'symbol', 'additionalContext'],
|
||||
};
|
||||
|
||||
export function valideazaCbom(bom) {
|
||||
const err = [];
|
||||
const e = (m) => err.push(m);
|
||||
const chei = (o, perm, unde) => { for (const k of Object.keys(o)) if (!perm.includes(k)) e(`${unde}: cheie nepermisa "${k}"`); };
|
||||
const sir = (v, unde) => { if (typeof v !== 'string' || !v.length) e(`${unde}: trebuie sir nevid`); };
|
||||
const dataIso = (v, unde) => { if (typeof v !== 'string' || Number.isNaN(Date.parse(v)) || !/^\d{4}-\d{2}-\d{2}T/.test(v)) e(`${unde}: nu e date-time`); };
|
||||
chei(bom, E.bom, 'bom');
|
||||
if (bom.bomFormat !== 'CycloneDX') e('bomFormat');
|
||||
if (bom.specVersion !== '1.6') e('specVersion');
|
||||
if (!/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(bom.serialNumber || '')) e(`serialNumber ${bom.serialNumber}`);
|
||||
if (!Number.isInteger(bom.version) || bom.version < 1) e('version');
|
||||
const md = bom.metadata || {};
|
||||
if (md.timestamp !== undefined) dataIso(md.timestamp, 'metadata.timestamp');
|
||||
if (!md.tools || !Array.isArray(md.tools.components) || !md.tools.components.length) e('metadata.tools.components');
|
||||
else for (const t of md.tools.components) { sir(t.name, 'tool.name'); sir(t.version, 'tool.version'); if (!E.componentType.includes(t.type)) e('tool.type'); }
|
||||
if (!Array.isArray(bom.components)) { e('components nu e lista'); return err; }
|
||||
const refs = new Set();
|
||||
for (const [i, c] of bom.components.entries()) {
|
||||
const u = `components[${i}]`;
|
||||
chei(c, E.component, u);
|
||||
if (!E.componentType.includes(c.type)) e(`${u}.type ${c.type}`);
|
||||
sir(c.name, `${u}.name`);
|
||||
sir(c['bom-ref'], `${u}.bom-ref`);
|
||||
if (refs.has(c['bom-ref'])) e(`${u}: bom-ref dublat ${c['bom-ref']}`);
|
||||
refs.add(c['bom-ref']);
|
||||
if (c.properties) for (const p of c.properties) { sir(p.name, `${u}.properties.name`); if (typeof p.value !== 'string') e(`${u}.properties.value`); }
|
||||
if (c.type === 'cryptographic-asset') {
|
||||
const cp = c.cryptoProperties;
|
||||
if (!cp) { e(`${u}: cryptoProperties lipsa`); continue; }
|
||||
chei(cp, E.cryptoProperties, `${u}.cryptoProperties`);
|
||||
if (!E.assetType.includes(cp.assetType)) e(`${u}.assetType ${cp.assetType}`);
|
||||
if (cp.oid !== undefined && !/^[0-2](\.\d+)+$/.test(cp.oid)) e(`${u}.oid ${cp.oid}`);
|
||||
if (cp.assetType === 'algorithm') {
|
||||
const ap = cp.algorithmProperties;
|
||||
if (!ap) { e(`${u}: algorithmProperties lipsa`); continue; }
|
||||
chei(ap, E.algorithmProperties, `${u}.algorithmProperties`);
|
||||
if (!E.primitive.includes(ap.primitive)) e(`${u}.primitive ${ap.primitive}`);
|
||||
if (ap.parameterSetIdentifier !== undefined) sir(ap.parameterSetIdentifier, `${u}.parameterSetIdentifier`);
|
||||
if (ap.curve !== undefined) sir(ap.curve, `${u}.curve`);
|
||||
if (ap.mode !== undefined && !E.mode.includes(ap.mode)) e(`${u}.mode ${ap.mode}`);
|
||||
if (ap.padding !== undefined && !E.padding.includes(ap.padding)) e(`${u}.padding ${ap.padding}`);
|
||||
if (ap.cryptoFunctions !== undefined && (!Array.isArray(ap.cryptoFunctions) || ap.cryptoFunctions.some((f) => !E.cryptoFunctions.includes(f)))) e(`${u}.cryptoFunctions`);
|
||||
if (ap.classicalSecurityLevel !== undefined && (!Number.isInteger(ap.classicalSecurityLevel) || ap.classicalSecurityLevel < 0)) e(`${u}.classicalSecurityLevel`);
|
||||
if (ap.nistQuantumSecurityLevel !== undefined && (!Number.isInteger(ap.nistQuantumSecurityLevel) || ap.nistQuantumSecurityLevel < 0 || ap.nistQuantumSecurityLevel > 6)) e(`${u}.nistQuantumSecurityLevel`);
|
||||
} else if (cp.assetType === 'protocol') {
|
||||
const pp = cp.protocolProperties || {};
|
||||
chei(pp, E.protocolProperties, `${u}.protocolProperties`);
|
||||
if (!E.protocolType.includes(pp.type)) e(`${u}.protocolProperties.type`);
|
||||
if (pp.version !== undefined) sir(pp.version, `${u}.protocolProperties.version`);
|
||||
} else if (cp.assetType === 'certificate') {
|
||||
const cc = cp.certificateProperties || {};
|
||||
chei(cc, E.certificateProperties, `${u}.certificateProperties`);
|
||||
for (const k of ['notValidBefore', 'notValidAfter']) if (cc[k] !== undefined) dataIso(cc[k], `${u}.${k}`);
|
||||
} else if (cp.assetType === 'related-crypto-material') {
|
||||
const rm = cp.relatedCryptoMaterialProperties || {};
|
||||
chei(rm, E.relatedCryptoMaterialProperties, `${u}.relatedCryptoMaterialProperties`);
|
||||
if (!E.materialType.includes(rm.type)) e(`${u}.relatedCryptoMaterialProperties.type`);
|
||||
if (rm.size !== undefined && !Number.isInteger(rm.size)) e(`${u}.size`);
|
||||
if (rm.value !== undefined) e(`${u}: valoarea materialului nu are voie sa apara`);
|
||||
}
|
||||
}
|
||||
if (!c.evidence || !Array.isArray(c.evidence.occurrences) || !c.evidence.occurrences.length) { e(`${u}: evidence.occurrences lipsa`); continue; }
|
||||
chei(c.evidence, E.evidence, `${u}.evidence`);
|
||||
for (const o of c.evidence.occurrences) {
|
||||
chei(o, E.occurrence, `${u}.occurrence`);
|
||||
sir(o.location, `${u}.occurrence.location`);
|
||||
if (o.line !== undefined && (!Number.isInteger(o.line) || o.line < 1)) e(`${u}.occurrence.line`);
|
||||
}
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
proba('cbom: structura CycloneDX 1.6 (campuri obligatorii, tipuri, enumerari)', () => {
|
||||
const rez = scan(FIX);
|
||||
for (const det of [false, true]) {
|
||||
const bom = inv.buildCbom(rez, { deterministic: det });
|
||||
const err = valideazaCbom(bom);
|
||||
asigura(err.length === 0, `erori (${det ? 'determinist' : 'normal'}): ${err.slice(0, 5).join('; ')}`);
|
||||
asigura(det ? bom.metadata.timestamp === undefined : typeof bom.metadata.timestamp === 'string', 'timestamp');
|
||||
}
|
||||
const bom = inv.buildCbom(rez);
|
||||
const tipuri = new Set(bom.components.map((c) => (c.cryptoProperties ? c.cryptoProperties.assetType : c.type)));
|
||||
for (const t of ['algorithm', 'protocol', 'certificate', 'related-crypto-material', 'library']) asigura(tipuri.has(t), `lipseste tipul ${t}`);
|
||||
// controlul negativ al validatorului: o forma stricata trebuie sa fie refuzata
|
||||
const rau = JSON.parse(JSON.stringify(bom));
|
||||
rau.components[0].cryptoProperties = { assetType: 'algorithm', algorithmProperties: { primitive: 'magic' } };
|
||||
rau.components[1]['bom-ref'] = rau.components[2]['bom-ref'];
|
||||
rau.specVersion = '1.5';
|
||||
asigura(valideazaCbom(rau).length >= 3, 'validatorul nu refuza un CBOM stricat');
|
||||
});
|
||||
|
||||
proba('cbom: bom-ref unice si stabile intre doua rulari', () => {
|
||||
const a = inv.buildCbom(inv.scan(FIX), { deterministic: true });
|
||||
const b = inv.buildCbom(inv.scan(FIX), { deterministic: true });
|
||||
const ra = a.components.map((c) => c['bom-ref']);
|
||||
asigura(new Set(ra).size === ra.length, `bom-ref dublate: ${ra.length - new Set(ra).size}`);
|
||||
asigura(JSON.stringify(a) === JSON.stringify(b), 'doua rulari deterministe difera');
|
||||
const gasiri = inv.scan(FIX).findings.length;
|
||||
const occ = a.components.filter((c) => c.type === 'cryptographic-asset').reduce((s, c) => s + c.evidence.occurrences.length, 0);
|
||||
asigura(occ === gasiri, `occurrences ${occ} != gasiri ${gasiri}`);
|
||||
});
|
||||
|
||||
proba('cbom: fiecare occurrence arata un fisier care exista, cu o linie din fisier', () => {
|
||||
const bom = inv.buildCbom(scan(FIX));
|
||||
let n = 0;
|
||||
for (const c of bom.components) {
|
||||
for (const o of c.evidence.occurrences) {
|
||||
const f = join(FIX, o.location);
|
||||
asigura(existsSync(f) && statSync(f).isFile(), `nu exista: ${o.location}`);
|
||||
const linii = readFileSync(f, 'utf8').split('\n').length;
|
||||
asigura(o.line >= 1 && o.line <= linii, `${o.location}: linia ${o.line} din ${linii}`);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
asigura(n > 50, `prea putine occurrences: ${n}`);
|
||||
});
|
||||
|
||||
// --- CLI ---
|
||||
function cli(args) {
|
||||
return spawnSync(process.execPath, [CALE_MODUL, ...args], { encoding: 'utf8', timeout: 60000 });
|
||||
}
|
||||
|
||||
proba('cli: --fail-on vulnerable iese 1 pe cod vulnerabil si 0 pe cod fara criptografie', () => {
|
||||
const r = cli(['scan', join(FIX, 'js'), '--fail-on', 'vulnerable', '--summary']);
|
||||
asigura(r.status === 1 && /quantum-vulnerable finding/.test(r.stderr), `status ${r.status}, stderr ${r.stderr.slice(0, 200)}`);
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-cli-'));
|
||||
try {
|
||||
copyFileSync(join(FIX, 'negative', 'fara-cripto.js'), join(d, 'fara-cripto.js'));
|
||||
const r0 = cli(['scan', d, '--fail-on', 'vulnerable', '--summary']);
|
||||
asigura(r0.status === 0, `fara criptografie: status ${r0.status}`);
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
const r2 = cli(['scan', join(FIX, 'js'), '--fail-on', 'nimic']);
|
||||
asigura(r2.status === 2, `valoare --fail-on invalida: status ${r2.status}`);
|
||||
const r3 = cli(['scan', join(FIX, 'js'), '--fail-on', 'weak', '--summary']);
|
||||
asigura(r3.status === 1 && /weak-now finding/.test(r3.stderr), `--fail-on weak: status ${r3.status}`);
|
||||
});
|
||||
|
||||
proba('cli: --summary spune cate fisiere nu au fost citite si de ce', () => {
|
||||
const r = cli(['scan', FIX, '--summary', '--max-file-bytes', '400']);
|
||||
asigura(r.status === 0, `status ${r.status} ${r.stderr}`);
|
||||
const m = /Not read: (\d+) binary, (\d+) too large \(> 400 bytes\), (\d+) over the file limit/.exec(r.stdout);
|
||||
asigura(m && m[1] === '1' && Number(m[2]) >= 1 && m[3] === '0', `randul "Not read": ${m ? m[0] : 'lipsa'}`);
|
||||
asigura(/e\.g\. binary: binar\/modul\.js/.test(r.stdout), 'exemplul binar lipseste din rezumat');
|
||||
const rj = cli(['scan', join(FIX, 'go'), '--deterministic']);
|
||||
const bom = JSON.parse(rj.stdout);
|
||||
asigura(bom.specVersion === '1.6' && valideazaCbom(bom).length === 0, 'CBOM-ul de pe stdout nu e valid');
|
||||
});
|
||||
|
||||
proba('rezumat: caracterele de control din numele de fisiere nu ajung in terminal', () => {
|
||||
const rez = scan(FIX);
|
||||
const i = rez.findings.findIndex((g) => g.classification === 'quantum-vulnerable');
|
||||
asigura(i >= 0, 'controlul pozitiv: fixturile trebuie sa aiba o gasire vulnerabila');
|
||||
const rau = 'x\u001b]0;titlu\u0007\u001b[31mrosu.js';
|
||||
const t = inv.renderSummary({ ...rez, findings: rez.findings.map((g, k) => (k === i ? { ...g, file: rau } : g)) });
|
||||
asigura(t.includes('x?]0;titlu??[31mrosu.js'), 'numele fisierului trebuia sa apara, cu caracterele de control inlocuite');
|
||||
asigura(!/[\u0000-\u0009\u000b-\u001f\u007f]/.test(t), 'un caracter de control a ajuns in rezumat');
|
||||
});
|
||||
|
||||
proba('rezumat: numaratoarea pe clase egala cu gasirile', () => {
|
||||
const rez = scan(FIX);
|
||||
const c = inv.countByClass(rez.findings);
|
||||
const s = Object.values(c).reduce((a, b) => a + b, 0);
|
||||
asigura(s === rez.findings.length, `suma claselor ${s}, gasiri ${rez.findings.length}`);
|
||||
const t = inv.renderSummary(rez);
|
||||
for (const [k, v] of Object.entries(c)) asigura(new RegExp(`${k}\\s+${v}\\b`).test(t), `rezumatul nu arata ${k} ${v}`);
|
||||
});
|
||||
|
||||
// --- rularea ---
|
||||
const rezultate = {};
|
||||
const erori = {};
|
||||
for (const p of probe) {
|
||||
try { await p.fn(); rezultate[p.nume] = 'VERDE'; } catch (err) { rezultate[p.nume] = 'ROSU'; erori[p.nume] = String(err && err.message || err); }
|
||||
}
|
||||
const verzi = Object.values(rezultate).filter((x) => x === 'VERDE').length;
|
||||
if (CA_JSON) {
|
||||
process.stdout.write(JSON.stringify({ suita: 'crypto-inventory', modul: CALE_MODUL, rulate: probe.length, verzi, rosii: probe.length - verzi, rezultate, erori }) + '\n');
|
||||
} else {
|
||||
for (const p of probe) process.stdout.write(`${rezultate[p.nume].padEnd(6)} ${p.nume}${erori[p.nume] ? `\n ${erori[p.nume]}` : ''}\n`);
|
||||
process.stdout.write(`\n${verzi} din ${probe.length} probe verzi (modul: ${CALE_MODUL})\n`);
|
||||
}
|
||||
process.exitCode = verzi === probe.length ? 0 : 1;
|
||||
Reference in new issue
Block a user