crypto-inventory 0.4.0: Swift and Kotlin detectors (CryptoKit, CommonCrypto, Security.framework, Android Keystore, Tink, OkHttp, the libsignal Swift and Android APIs), Apple and Android manifests; remediation recipes for Apache and HAProxy measured on real servers, HAProxy precondition fixed
This commit is contained in:
1 parent
e453c0c42d
commit
b6ed4d2b71
37 files changed
+1623
-82
No files matched your search
@@ -227,6 +227,8 @@ export function evalueaza(a) {
|
||||
}
|
||||
|
||||
if (g === 'MAC') {
|
||||
// 0.4.0 (2026-10-18): autentificatoare care nu sunt HMAC (Poly1305 din CryptoSwift, AES-CMAC din Tink): numite, fara hash
|
||||
if (!a.hash && a.nume) return f({ nume: a.nume, primitiv: 'mac', ...rez({ c: CLS.S, motiv: `${a.nume}: symmetric authenticator; a quantum attacker gains at most a quadratic speed-up (Grover) on key search.` }) });
|
||||
if (!a.hash) return f({ nume: 'HMAC', primitiv: 'mac', ...rez({ c: CLS.U, motiv: 'HMAC whose hash function is bound to the key object (set where the key is imported or generated), not visible at this call.', rec: REC.UNKNOWN }) });
|
||||
const h = HASH[a.hash];
|
||||
const nume = `HMAC-${h ? h.n : String(a.hash || 'unknown')}`;
|
||||
@@ -295,6 +297,14 @@ export function evalueaza(a) {
|
||||
return f({ nume: a.nume, primitiv: 'kem', ...rez({ c: CLS.S, motiv: `${a.nume}: hybrid key exchange (classical ECDH + ML-KEM); stays secure if either component holds. The NIST category given is that of the ML-KEM component.${nota}`, q: pq }) });
|
||||
}
|
||||
if (g === 'TLS') return tls(a, f);
|
||||
// 0.4.0 (2026-10-18, dupa fisierul 8 din raportul libsignal: rustls folosit NUMAI ca verificator de certificate iesea "X25519, schimba
|
||||
// furnizorul"): verificarea unui lant de certificate (PKIX in JCA, X509TrustManager, SecTrustEvaluate, pinning) e o expunere de
|
||||
// AUTENTIFICARE (lantul e semnat clasic de CA), nu un schimb de cheie; nimic de recoltat acum, nimic de schimbat in codul acesta singur.
|
||||
if (g === 'PKI-VERIFY') {
|
||||
const nume = a.nume || 'X.509 chain validation (PKIX)';
|
||||
const nota = a.nota ? ` ${a.nota}` : '';
|
||||
return f({ nume, primitiv: 'signature', ...rez({ c: CLS.V, qv: true, motiv: `${nume}: the certificate chain is authenticated by the issuing CA's classical signatures (RSA or ECDSA), which a cryptographically relevant quantum computer could forge; this is an authentication exposure (impersonation once such a computer exists), not a harvest-now-decrypt-later exposure, since no key is exchanged here.${nota}`, rec: 'Nothing to change in this code alone: certificate chains move to post-quantum or composite signatures only when the issuing CA offers them (no public CA did when this rule was written). Until then keep the trust store small, prefer short-lived certificates, and plan the switch of the trust anchors when post-quantum roots are published.', q: 0 }) });
|
||||
}
|
||||
if (g === 'JWT-HMAC') {
|
||||
const h = HASH[a.hash];
|
||||
return f({ nume: a.nume, primitiv: 'mac', ...rez({ c: CLS.S, motiv: `${a.nume} is HMAC-${h ? h.n : a.hash}: symmetric, so a quantum attacker gains at most a quadratic speed-up (Grover); the shared secret must be long and random.` }) });
|
||||
|
||||
@@ -172,6 +172,13 @@ function rezolvaOData(ctx, nume) {
|
||||
const m = new RegExp(`^\\s*(?:(?:const|var)\\s+)?${e}\\s*(?:string\\s*)?(?::=|=)\\s*"([^"\\n\\\\]*)"\\s*$`).exec(c.slice(ls, le));
|
||||
return !parametru && m ? { valoare: m[1], line: ctx.poz(k).line } : null;
|
||||
}
|
||||
// 0.4.0 (2026-10-18): Kotlin `val X = "..."` / `const val X = "..."`, Swift `let X = "..."`; un parametru `X: String` in paranteze
|
||||
// nu se rezolva; un sir cu $ (sablon) sau \( (interpolare) nu e un literal simplu
|
||||
if (ctx.limbaj === 'kotlin' || ctx.limbaj === 'swift') {
|
||||
parametru = new RegExp(`\\(([^()]{0,2000}(?<![\\w.])${e}\\s*:\\s*String\\b[^()]{0,2000})\\)`).test(c);
|
||||
const m = new RegExp(`\\b(?:val|var|let)\\s+${e}\\s*(?::\\s*String\\s*)?=\\s*"([^"\\n\\\\$]*)"\\s*;?\\s*$`).exec(linie);
|
||||
return !parametru && m ? { valoare: m[1], line: ctx.poz(k).line } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
// Detectorul Java: JCA getInstance("..."), SSLContext, protocoale activate, Bouncy Castle.
|
||||
import { argumente, imparteArgumente, valoareArgument, necunoscut } from './context.mjs';
|
||||
// 0.4.0 (2026-10-18): acelasi cod serveste si Kotlin (`detecteazaJvm(ctx, true)`, chemat din detect-kotlin.mjs): JCA e acelasi API,
|
||||
// fara `new`, fara `;`, cu `val`/`var` si `arrayOf(...)`; si regulile noi comune JVM-ului: Android Keystore (KeyGenParameterSpec),
|
||||
// Tink (sabloanele de chei), OkHttp (ConnectionSpec, TlsVersion, CipherSuite, CertificatePinner) si verificarea lanturilor de
|
||||
// certificate (CertPathValidator "PKIX", TrustManagerFactory, X509TrustManager, checkServerTrusted), raportata ca autentificare.
|
||||
import { argumente, imparteArgumente, valoareArgument, necunoscut, escapeRe } from './context.mjs';
|
||||
import { hashCanonic, grupTls, curbaCanonica } from './catalog.mjs';
|
||||
|
||||
const TLSV = { TLSv1: '1.0', 'TLSv1.1': '1.1', 'TLSv1.2': '1.2', 'TLSv1.3': '1.3', SSLv3: 'ssl3', SSLv2Hello: 'ssl2', SSL: 'negotiated', TLS: 'negotiated', Default: 'negotiated' };
|
||||
@@ -40,7 +44,7 @@ export function activJca(clasa, val, dupa = '', variabila = null) {
|
||||
if (u === 'DSA') return { grup: 'DSA', param: bits, functii: f };
|
||||
if (u === 'DH' || u === 'DIFFIEHELLMAN') return { grup: 'DH', param: bits, functii: f };
|
||||
if (u === 'EC' || u === 'ECDSA' || u === 'ECDH') {
|
||||
const spec = peVar('initialize', 'new\\s+ECGenParameterSpec\\s*\\(\\s*"([^"]+)"');
|
||||
const spec = peVar('initialize', '(?:new\\s+)?ECGenParameterSpec\\s*\\(\\s*"([^"]+)"'); // Kotlin: fara new
|
||||
return { grup: u === 'ECDH' ? 'ECDH' : 'EC', curba: spec ? spec[1] : undefined, functii: f };
|
||||
}
|
||||
if (u === 'ED25519' || u === 'ED448' || u === 'EDDSA') return { grup: 'EDDSA', nume: u === 'ED448' ? 'Ed448' : 'Ed25519', functii: f };
|
||||
@@ -169,14 +173,94 @@ export function variabilaAtribuita(c, pos) {
|
||||
return st < sf ? c.slice(st, sf) : null;
|
||||
}
|
||||
|
||||
export function detecteazaJava(ctx) {
|
||||
// KeyProperties.KEY_ALGORITHM_* (Android Keystore) -> numele JCA pe care il primeste getInstance
|
||||
const KEY_ALGORITHM = { EC: 'EC', RSA: 'RSA', AES: 'AES', '3DES': 'DESede', HMAC_SHA1: 'HmacSHA1', HMAC_SHA224: 'HmacSHA224', HMAC_SHA256: 'HmacSHA256', HMAC_SHA384: 'HmacSHA384', HMAC_SHA512: 'HmacSHA512', XDH: 'XDH' };
|
||||
const NUME_PKIX = 'X.509 chain validation (PKIX)';
|
||||
|
||||
// Lantul unui KeyGenParameterSpec.Builder(...)....build(): marimea cheii, curba, hash-urile, modurile, umpluturile
|
||||
function citesteSpecAndroid(lant) {
|
||||
const t = lant.slice(0, 3000);
|
||||
const r = {};
|
||||
let m;
|
||||
if ((m = /setKeySize\s*\(\s*(\d+)\s*\)/.exec(t))) r.bits = m[1];
|
||||
if ((m = /(?:new\s+)?ECGenParameterSpec\s*\(\s*"([^"]+)"/.exec(t))) { r.curba = m[1]; r.pozCurba = m.index; } // pozitia, ca sa nu se numere si separat
|
||||
if ((m = /BLOCK_MODE_(GCM|CBC|ECB|CTR)\b/.exec(t))) r.mod = m[1].toLowerCase();
|
||||
if ((m = /DIGEST_(SHA1|SHA224|SHA256|SHA384|SHA512|MD5)\b/.exec(t))) r.hash = hashCanonic(m[1]) || m[1];
|
||||
if ((m = /(ENCRYPTION_PADDING_RSA_OAEP|ENCRYPTION_PADDING_RSA_PKCS1|SIGNATURE_PADDING_RSA_PSS|SIGNATURE_PADDING_RSA_PKCS1)\b/.exec(t))) r.padding = /OAEP/.test(m[1]) ? 'oaep' : /PSS/.test(m[1]) ? 'other' : 'pkcs1v15';
|
||||
return r;
|
||||
}
|
||||
|
||||
// Specificatia Android Keystore data generatorului `variabila` prin .initialize(spec) / .init(spec): inline in apel sau printr-o variabila
|
||||
// definita in fisier cu KeyGenParameterSpec.Builder; intoarce { spec, pozitiiBuilder } (pozitiile builderelor consumate)
|
||||
function specAndroidPentru(ctx, dupaStart, dupa, variabila) {
|
||||
if (!variabila) return null;
|
||||
const s = new RegExp(`(?<![\\w.])${escapeRe(variabila)}\\s*\\.\\s*(?:initialize|init)\\s*\\(`).exec(dupa);
|
||||
if (!s) return null;
|
||||
const a = argumente(ctx, dupaStart + s.index + s[0].length);
|
||||
const RE_B = /(?<![\w.])KeyGenParameterSpec\s*\.\s*Builder\s*\(/g;
|
||||
const cu = (baza, text) => { const spec = citesteSpecAndroid(text); const pozitii = [baza]; if (spec.pozCurba !== undefined) pozitii.push(baza + spec.pozCurba); return { spec, pozitii }; };
|
||||
let b = RE_B.exec(a.text);
|
||||
if (b) return cu(a.start + b.index, a.text.slice(b.index));
|
||||
const id = /^\s*([A-Za-z_]\w*)\s*$/.exec(a.text);
|
||||
if (!id) return null;
|
||||
const def = new RegExp(`(?<![\\w.])${escapeRe(id[1])}\\s*(?::\\s*KeyGenParameterSpec\\s*)?=\\s*KeyGenParameterSpec\\s*\\.\\s*Builder\\s*\\(`).exec(ctx.code);
|
||||
if (!def) return null;
|
||||
const inceput = def.index + def[0].lastIndexOf('KeyGenParameterSpec');
|
||||
return cu(inceput, ctx.code.slice(inceput));
|
||||
}
|
||||
|
||||
// Sabloanele de chei Tink (KeyTemplates.get("..."), AeadKeyTemplates.X, PredefinedAeadParameters.X): numele spune algoritmul
|
||||
export function sablonTink(nume) {
|
||||
const t = String(nume).trim().replace(/_RAW$/, '');
|
||||
let m;
|
||||
const pq = pqNume(t.replace(/_/g, '-'));
|
||||
if (pq) return pq;
|
||||
if ((m = /^AES(128|256)_GCM(_SIV)?$/.exec(t))) return { grup: 'CIPHER', nume: 'AES', param: m[1], mod: m[2] ? 'gcm-siv' : 'gcm', functii: ['encrypt', 'decrypt'] };
|
||||
if ((m = /^AES(128|256)_EAX$/.exec(t))) return { grup: 'CIPHER', nume: 'AES', param: m[1], mod: 'eax', functii: ['encrypt', 'decrypt'] };
|
||||
if ((m = /^AES(128|256)_CTR_HMAC_SHA256$/.exec(t))) return { grup: 'CIPHER', nume: 'AES', param: m[1], mod: 'ctr', functii: ['encrypt', 'decrypt'], nota: 'Tink AES-CTR with HMAC-SHA-256 (encrypt-then-MAC).' };
|
||||
if ((m = /^AES(128|256)_GCM_HKDF_(\d+KB|\d+MB)$/.exec(t))) return { grup: 'CIPHER', nume: 'AES', param: m[1], mod: 'gcm', functii: ['encrypt', 'decrypt'], nota: 'Tink streaming AEAD (segments keyed with HKDF).' };
|
||||
if (t === 'AES256_SIV') return { grup: 'CIPHER', nume: 'AES', param: '256', mod: 'siv', functii: ['encrypt', 'decrypt'] };
|
||||
if (t === 'XCHACHA20_POLY1305') return { grup: 'CIPHER', nume: 'XChaCha20-Poly1305', functii: ['encrypt', 'decrypt'] };
|
||||
if (t === 'CHACHA20_POLY1305') return { grup: 'CIPHER', nume: 'ChaCha20-Poly1305', functii: ['encrypt', 'decrypt'] };
|
||||
if (t === 'AES_CMAC') return { grup: 'MAC', nume: 'AES-CMAC', functii: ['tag'] };
|
||||
if ((m = /^HMAC_SHA(256|512)_(\d+)BITTAG$/.exec(t))) return { grup: 'MAC', hash: `SHA${m[1]}`, functii: ['tag'] };
|
||||
if ((m = /^HMAC_SHA(256|512)_PRF$/.exec(t)) || (m = /^HKDF_SHA(256)$/.exec(t))) return { grup: 'KDF', nume: /^HKDF/.test(t) ? 'HKDF' : 'HMAC-PRF', hash: `SHA${m[1]}`, functii: ['keyderive'] };
|
||||
if ((m = /^ECDSA_P(256|384|521)(?:_IEEE_P1363|_RAW)?$/.exec(t))) return { grup: 'ECDSA', curba: `secp${m[1]}r1`, functii: ['sign', 'verify'] };
|
||||
if (t === 'ED25519') return { grup: 'EDDSA', nume: 'Ed25519', functii: ['sign', 'verify'] };
|
||||
if ((m = /^RSA_SSA_(PKCS1|PSS)_(\d{4})_SHA(\d{3})(?:_SHA\d{3}_\d+)?_F4$/.exec(t))) return { grup: 'RSA', param: m[2], primitiv: 'signature', padding: m[1] === 'PSS' ? 'other' : 'pkcs1v15', hash: `SHA${m[3]}`, functii: ['sign', 'verify'] };
|
||||
if ((m = /^ECIES_P(256|384|521)(?:_COMPRESSED)?_HKDF_HMAC_SHA\d+_AES\d+_(?:GCM|CTR_HMAC_SHA\d+)$/.exec(t))) return { grup: 'ECDH', curba: `secp${m[1]}r1`, primitiv: 'pke', functii: ['encrypt', 'decrypt'], nota: `Tink ECIES (${t}).` };
|
||||
if ((m = /^DHKEM_(X25519|P256|P384|P521)_HKDF_SHA\d+_HKDF_SHA\d+_(AES_128_GCM|AES_256_GCM|CHACHA20_POLY1305)$/.exec(t))) {
|
||||
const nota = `Tink HPKE (RFC 9180) with DHKEM ${m[1]}: the key encapsulation is classical.`;
|
||||
return m[1] === 'X25519' ? { grup: 'XDH', nume: 'X25519', functii: ['encapsulate', 'decapsulate'], nota } : { grup: 'ECDH', curba: `secp${m[1].slice(1)}r1`, primitiv: 'pke', functii: ['encapsulate', 'decapsulate'], nota };
|
||||
}
|
||||
return { grup: 'UNKNOWN', nume: `Tink template ${nume}`, motiv: `Tink key template "${nume}" is not in this tool's catalog.` };
|
||||
}
|
||||
|
||||
// Suita de cifruri TLS (OkHttp CipherSuite.TLS_...): schimbul de cheie din nume, sau cifrul pentru suitele TLS 1.3
|
||||
function suitaTls(nume) {
|
||||
let m;
|
||||
if ((m = /^TLS_(ECDHE|ECDH)_/.exec(nume))) return { grup: 'ECDH', nume, functii: ['keygen'], nota: 'TLS cipher suite with (EC)DHE key exchange; the curve is negotiated separately.' };
|
||||
if ((m = /^TLS_(DHE|DH)_/.exec(nume))) return { grup: 'DH', nume, functii: ['keygen'] };
|
||||
if (/^TLS_RSA_/.test(nume)) return { grup: 'RSA', nume, primitiv: 'pke', padding: 'pkcs1v15', functii: ['encrypt'], nota: 'TLS cipher suite with RSA key transport (no forward secrecy).' };
|
||||
if ((m = /^TLS_AES_(128|256)_GCM_SHA\d+$/.exec(nume))) return { grup: 'CIPHER', nume: 'AES', param: m[1], mod: 'gcm', functii: ['encrypt'], nota: 'TLS 1.3 cipher suite: the key exchange group is negotiated separately.' };
|
||||
if (/^TLS_CHACHA20_POLY1305_SHA256$/.test(nume)) return { grup: 'CIPHER', nume: 'ChaCha20-Poly1305', functii: ['encrypt'], nota: 'TLS 1.3 cipher suite: the key exchange group is negotiated separately.' };
|
||||
if ((m = /^TLS_AES_(128|256)_CCM/.exec(nume))) return { grup: 'CIPHER', nume: 'AES', param: m[1], mod: 'ccm', functii: ['encrypt'] };
|
||||
return { grup: 'UNKNOWN', nume, motiv: `TLS cipher suite "${nume}" is not in this tool's catalog.` };
|
||||
}
|
||||
|
||||
export function detecteazaJava(ctx) { detecteazaJvm(ctx, false); }
|
||||
|
||||
export function detecteazaJvm(ctx, kotlin) {
|
||||
const c = ctx.code;
|
||||
const consumate = new Set();
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(KeyPairGenerator|Signature|Cipher|KeyAgreement|MessageDigest|Mac|KeyGenerator|KeyFactory|SecretKeyFactory|KEM|SSLContext|AlgorithmParameterGenerator)\s*\.\s*getInstance\s*\(/g)) {
|
||||
const a = argumente(ctx, m.index + m[0].length);
|
||||
const p = imparteArgumente(ctx, a.start, a.end);
|
||||
const api = `${m[1]}.getInstance`;
|
||||
const v = valoareArgument(ctx, p[0]);
|
||||
let v = valoareArgument(ctx, p[0]);
|
||||
// Android Keystore: KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
|
||||
const kp = v.fel === 'necunoscut' && /^KeyProperties\s*\.\s*KEY_ALGORITHM_(\w+)$/.exec(v.expresie);
|
||||
if (kp && KEY_ALGORITHM[kp[1]]) v = { fel: 'rezolvat', valoare: KEY_ALGORITHM[kp[1]], din: `KeyProperties.KEY_ALGORITHM_${kp[1]}` };
|
||||
if (v.fel === 'necunoscut') { ctx.adauga(m.index, api, 'call', necunoscut(v.expresie, api), { bucata: m[0] + v.expresie }); continue; }
|
||||
if (v.fel !== 'literal' && v.fel !== 'rezolvat') continue;
|
||||
const ex = v.fel === 'rezolvat' ? { rezolvatDin: v.din } : {};
|
||||
@@ -188,13 +272,39 @@ export function detecteazaJava(ctx) {
|
||||
const dupa = c.slice(a.end, a.end + 2000);
|
||||
const variabila = variabilaAtribuita(c, m.index);
|
||||
if (variabila && m[1] === 'KeyPairGenerator' && /^(EC|ECDSA|ECDH)$/i.test(v.valoare)) {
|
||||
const s = new RegExp(`(?<![\\w.])${variabila}\\s*\\.\\s*initialize\\s*\\(\\s*(new\\s+ECGenParameterSpec\\s*\\(\\s*")`).exec(dupa);
|
||||
const s = new RegExp(`(?<![\\w.])${variabila}\\s*\\.\\s*initialize\\s*\\(\\s*((?:new\\s+)?ECGenParameterSpec\\s*\\(\\s*")`).exec(dupa);
|
||||
if (s) consumate.add(a.end + s.index + s[0].indexOf(s[1]));
|
||||
}
|
||||
ctx.adauga(m.index, api, 'call', activJca(m[1], v.valoare, dupa, variabila), { ...ex, bucata: `${m[0]}"${v.valoare}"` });
|
||||
const act = activJca(m[1], v.valoare, dupa, variabila);
|
||||
// Android Keystore: marimea, curba, modul si umplutura vin din KeyGenParameterSpec.Builder, nu din initialize(bits)
|
||||
if (/^(KeyPairGenerator|KeyGenerator)$/.test(m[1]) && act.grup !== 'UNKNOWN') {
|
||||
const sp = specAndroidPentru(ctx, a.end, dupa, variabila);
|
||||
if (sp) {
|
||||
for (const pz of sp.pozitii) consumate.add(pz);
|
||||
if (sp.spec.bits && !act.param) act.param = sp.spec.bits;
|
||||
if (sp.spec.curba && !act.curba && /^(EC|ECDH)$/.test(act.grup)) act.curba = sp.spec.curba;
|
||||
if (sp.spec.mod && act.grup === 'CIPHER') act.mod = sp.spec.mod;
|
||||
if (sp.spec.padding && act.grup === 'RSA') { act.padding = sp.spec.padding; act.primitiv = sp.spec.padding === 'oaep' ? 'pke' : 'signature'; }
|
||||
if (sp.spec.hash && act.grup === 'RSA' && !act.hash) act.hash = sp.spec.hash;
|
||||
}
|
||||
}
|
||||
ctx.adauga(m.index, api, 'call', act, { ...ex, bucata: `${m[0]}"${v.valoare}"` });
|
||||
}
|
||||
// curbe numite in afara unui KeyPairGenerator (ECGenParameterSpec, ECNamedCurveTable)
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:new\s+ECGenParameterSpec|ECNamedCurveTable\s*\.\s*getParameterSpec|SECNamedCurves\s*\.\s*getByName|CustomNamedCurves\s*\.\s*getByName)\s*\(\s*"([^"]+)"/g)) {
|
||||
// Android Keystore: un KeyGenParameterSpec.Builder neconsumat de un getInstance din acelasi fisier (generatorul e in alta parte);
|
||||
// inaintea curbelor numite, fiindca ECGenParameterSpec-ul din lantul lui e al lui, nu o a doua curba
|
||||
for (const m of ctx.potriviri(/(?<![\w.])KeyGenParameterSpec\s*\.\s*Builder\s*\(/g)) {
|
||||
if (consumate.has(m.index)) continue;
|
||||
const sp = citesteSpecAndroid(c.slice(m.index));
|
||||
if (sp.pozCurba !== undefined) consumate.add(m.index + sp.pozCurba);
|
||||
const act = sp.curba ? { grup: 'EC', curba: sp.curba, functii: ['keygen'] }
|
||||
: sp.mod ? { grup: 'CIPHER', nume: sp.bits === '168' ? '3DES' : 'AES', param: sp.bits, mod: sp.mod, functii: ['keygen'] }
|
||||
: sp.padding || (sp.bits && Number(sp.bits) >= 1024) ? { grup: 'RSA', param: sp.bits, padding: sp.padding, primitiv: sp.padding === 'oaep' ? 'pke' : (sp.padding ? 'signature' : undefined), hash: sp.hash, functii: ['keygen'] }
|
||||
: sp.bits && /^(224|256|384|521)$/.test(sp.bits) ? { grup: 'EC', curba: `secp${sp.bits}r1`, functii: ['keygen'] }
|
||||
: { grup: 'UNKNOWN', nume: 'KeyGenParameterSpec', motiv: 'Android Keystore key specification: the algorithm is given to the generator (KeyProperties.KEY_ALGORITHM_*), which is not in this file; the spec alone does not say it.' };
|
||||
ctx.adauga(m.index, 'KeyGenParameterSpec.Builder', 'config', act, { bucata: m[0] });
|
||||
}
|
||||
// curbe numite in afara unui KeyPairGenerator (ECGenParameterSpec, ECNamedCurveTable); Kotlin: fara new
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:(?:new\s+)?ECGenParameterSpec|ECNamedCurveTable\s*\.\s*getParameterSpec|SECNamedCurves\s*\.\s*getByName|CustomNamedCurves\s*\.\s*getByName)\s*\(\s*"([^"]+)"/g)) {
|
||||
if (consumate.has(m.index)) continue;
|
||||
ctx.adauga(m.index, m[0].replace(/\s*\(.*$/, ''), 'call', { grup: 'EC', curba: m[1] }, { bucata: m[0] });
|
||||
}
|
||||
@@ -203,8 +313,8 @@ export function detecteazaJava(ctx) {
|
||||
const act = pqNume(t) || (/^X/.test(t) ? { grup: 'XDH', nume: t } : { grup: 'EDDSA', nume: t === 'ED448' ? 'Ed448' : 'Ed25519' });
|
||||
ctx.adauga(m.index, `NamedParameterSpec.${m[1]}`, 'call', act, { bucata: m[0] });
|
||||
}
|
||||
// protocoale TLS activate explicit
|
||||
for (const m of ctx.potriviri(/(?<![\w.])set(?:Enabled)?Protocols\s*\(\s*new\s+String\s*\[\s*\]\s*\{/g)) {
|
||||
// protocoale TLS activate explicit: Java new String[]{...}, Kotlin arrayOf(...) / listOf(...)
|
||||
for (const m of ctx.potriviri(/(?<![\w.])set(?:Enabled)?Protocols\s*\(\s*(?:new\s+String\s*\[\s*\]\s*\{|arrayOf\s*\(|listOf\s*\()/g)) {
|
||||
const a = argumente(ctx, m.index + m[0].length);
|
||||
const vers = [...a.text.matchAll(/"([^"]+)"/g)];
|
||||
const lista = vers.map((x) => TLSV[x[1]]).filter(Boolean);
|
||||
@@ -215,6 +325,39 @@ export function detecteazaJava(ctx) {
|
||||
ctx.adauga(a.start + x.index, 'setEnabledProtocols', 'config', { grup: 'TLS', param: ver, rol }, { bucata: `"${x[1]}"` });
|
||||
}
|
||||
}
|
||||
// OkHttp (ancorat pe importul okhttp3): ConnectionSpec, versiunile si suitele cerute, pinning
|
||||
if (/^[ \t]*import\s+okhttp3\./m.test(c)) {
|
||||
for (const m of ctx.potriviri(/(?<![\w.])ConnectionSpec\s*\.\s*Builder\s*\(\s*ConnectionSpec\s*\.\s*(MODERN_TLS|COMPATIBLE_TLS|RESTRICTED_TLS|CLEARTEXT)\s*\)/g)) {
|
||||
if (m[1] === 'CLEARTEXT') { ctx.adauga(m.index, 'ConnectionSpec.CLEARTEXT', 'config', { grup: 'UNKNOWN', nume: 'OkHttp CLEARTEXT', motiv: 'OkHttp ConnectionSpec.CLEARTEXT: plain HTTP, no TLS at all on this connection spec.' }, { bucata: m[0] }); continue; }
|
||||
ctx.adauga(m.index, `ConnectionSpec.${m[1]}`, 'config', { grup: 'TLS', param: 'negotiated', nume: `TLS (negotiated, OkHttp ${m[1]})` }, { bucata: m[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(/\.\s*tlsVersions\s*\(/g)) {
|
||||
const a = argumente(ctx, m.index + m[0].length);
|
||||
const vers = [...a.text.matchAll(/TlsVersion\s*\.\s*(TLS_1_0|TLS_1_1|TLS_1_2|TLS_1_3|SSL_3_0)\b/g)];
|
||||
const map = { TLS_1_0: '1.0', TLS_1_1: '1.1', TLS_1_2: '1.2', TLS_1_3: '1.3', SSL_3_0: 'ssl3' };
|
||||
const lista = vers.map((x) => map[x[1]]);
|
||||
for (const x of vers) ctx.adauga(a.start + x.index, 'ConnectionSpec.tlsVersions', 'config', { grup: 'TLS', param: map[x[1]], rol: map[x[1]] === '1.2' && lista.includes('1.3') ? 'min' : 'only' }, { bucata: x[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(/\.\s*cipherSuites\s*\(/g)) {
|
||||
const a = argumente(ctx, m.index + m[0].length);
|
||||
for (const x of a.text.matchAll(/CipherSuite\s*\.\s*(TLS_[A-Z0-9_]+)\b/g)) ctx.adauga(a.start + x.index, 'ConnectionSpec.cipherSuites', 'config', suitaTls(x[1]), { bucata: x[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])CertificatePinner\s*\.\s*Builder\s*\(/g)) ctx.adauga(m.index, 'CertificatePinner.Builder', 'config', { grup: 'PKI-VERIFY', nume: 'certificate pinning (SPKI)', nota: 'OkHttp CertificatePinner: the pinned SPKI hashes name classical (RSA or EC) keys.' }, { bucata: m[0] });
|
||||
}
|
||||
// verificarea lanturilor de certificate (lantul de incredere TLS al clientului): autentificare, nu schimb de cheie
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(CertPathValidator|TrustManagerFactory)\s*\.\s*getInstance\s*\(/g)) ctx.adauga(m.index, `${m[1]}.getInstance`, 'call', { grup: 'PKI-VERIFY', nume: NUME_PKIX, functii: ['verify'] }, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(/(?<![\w.])KeyStore\s*\.\s*getInstance\s*\(\s*"AndroidCAStore"\s*\)/g)) ctx.adauga(m.index, 'KeyStore.getInstance("AndroidCAStore")', 'call', { grup: 'PKI-VERIFY', nume: NUME_PKIX, nota: 'The Android system CA store (the client\'s TLS trust anchors).' }, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(/(?<![\w.])X509TrustManager\b(?!\s*\.)/g)) ctx.adauga(m.index, 'X509TrustManager', 'config', { grup: 'PKI-VERIFY', nume: NUME_PKIX, functii: ['verify'] }, { bucata: c.slice(Math.max(0, m.index - 12), m.index + 16) });
|
||||
for (const m of ctx.potriviri(/\.\s*checkServerTrusted\s*\(/g)) ctx.adauga(m.index, 'checkServerTrusted', 'call', { grup: 'PKI-VERIFY', nume: NUME_PKIX, functii: ['verify'] }, { bucata: m[0].trim() });
|
||||
// Tink (ancorat pe importul com.google.crypto.tink): sablonul de cheie spune algoritmul; inregistrarea primitivelor e dovada slaba
|
||||
const tink = ctx.potriviri(/^[ \t]*import\s+com\.google\.crypto\.tink\.[\w.*]+/gm);
|
||||
if (tink.length) {
|
||||
const TINK_SUPRIMA = ['CIPHER', 'MAC', 'KDF', 'ECDSA', 'EDDSA', 'RSA', 'XDH', 'ECDH', 'MLDSA', 'MLKEM', 'SLHDSA', 'UNKNOWN'];
|
||||
for (const m of ctx.potriviri(/(?<![\w.])KeyTemplates\s*\.\s*get\s*\(\s*"([^"]+)"\s*\)/g)) ctx.adauga(m.index, 'KeyTemplates.get', 'call', sablonTink(m[1]), { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:(?:Aead|Mac|Signature|Hybrid|Daead|StreamingAead|Prf)KeyTemplates|Predefined(?:Aead|Mac|Signature|Hybrid|Daead|StreamingAead|Prf)Parameters)\s*\.\s*([A-Z][A-Z0-9_]+)\b/g)) ctx.adauga(m.index, m[0].replace(/\s+/g, ''), 'call', sablonTink(m[1]), { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(Aead|Mac|Signature|Hybrid|Daead|StreamingAead|Prf|Tink)Config\s*\.\s*register\s*\(/g)) ctx.adauga(m.index, `${m[1]}Config.register`, 'import', { grup: 'LIB-MULTI', nume: `Tink ${m[1]} primitives`, motiv: `Tink ${m[1]}Config.register(): registers the primitive family; the algorithm is chosen by the key template, not visible in this file.` }, { suprimaDe: TINK_SUPRIMA, bucata: m[0] });
|
||||
ctx.adauga(tink[0].index + tink[0][0].indexOf('import'), 'import com.google.crypto.tink', 'import', { grup: 'LIB-MULTI', nume: 'Tink (com.google.crypto.tink)', motiv: 'Imports Tink (AEAD, MAC, signatures, hybrid encryption, HPKE); no key template recognized in this file.' }, { suprimaDe: [...TINK_SUPRIMA, 'LIB-MULTI'], bucata: tink[0][0].trim() });
|
||||
}
|
||||
// proprietati de sistem ale JSSE
|
||||
for (const m of ctx.potriviri(/(?<![\w.])System\s*\.\s*setProperty\s*\(\s*"(jdk\.tls\.(?:client|server)\.protocols|jdk\.tls\.namedGroups|https\.protocols)"\s*,\s*"([^"]*)"/g)) {
|
||||
const off = m[0].lastIndexOf('"' + m[2] + '"') + 1;
|
||||
@@ -228,8 +371,8 @@ export function detecteazaJava(ctx) {
|
||||
else if (TLSV[t]) ctx.adauga(pos, m[1], 'config', { grup: 'TLS', param: TLSV[t], rol: 'only' }, { bucata: `${m[1]}=${t}` });
|
||||
}
|
||||
}
|
||||
// Bouncy Castle: importurile si parametrii post-cuantici
|
||||
for (const m of ctx.potriviri(/^[ \t]*import\s+(?:static\s+)?(org\.bouncycastle\.[\w.]+)\s*;/gm)) {
|
||||
// Bouncy Castle: importurile (Java cu `;`, Kotlin fara) si parametrii post-cuantici
|
||||
for (const m of ctx.potriviri(/^[ \t]*import\s+(?:static\s+)?(org\.bouncycastle\.[\w.]+)\s*(?:;|$)/gm)) {
|
||||
const act = bcActiv(m[1]);
|
||||
if (act) ctx.adauga(m.index + m[0].indexOf('import'), `import ${m[1]}`, 'import', act, { suprimaDe: act.grup === 'EC' ? ['EC', 'ECDSA', 'ECDH', 'SECP256K1'] : 'AUTO', bucata: `import ${m[1]}` });
|
||||
}
|
||||
@@ -237,7 +380,7 @@ export function detecteazaJava(ctx) {
|
||||
const act = bcParam(m[1], m[2]);
|
||||
if (act) ctx.adauga(m.index, `${m[1]}Parameters.${m[2]}`, 'call', act, { bucata: m[0] });
|
||||
}
|
||||
detecteazaLibsignalJava(ctx);
|
||||
detecteazaLibsignalJvm(ctx, kotlin);
|
||||
void curbaCanonica;
|
||||
}
|
||||
|
||||
@@ -253,23 +396,43 @@ export function kemLibsignal(tip) {
|
||||
if ((k = /^ML_?KEM_?(768|1024)$/i.exec(tip || ''))) return { grup: 'MLKEM', param: k[1], functii: ['keygen'] };
|
||||
return { grup: 'UNKNOWN', nume: 'libsignal KEM key pair', motiv: 'libsignal KEMKeyPair: the key type (Kyber-1024 or ML-KEM) is the KEMKeyType argument, not visible on this line.' };
|
||||
}
|
||||
function detecteazaLibsignalJava(ctx) {
|
||||
export const LIBSIGNAL_NOTA_KYBER_PK = 'libsignal KEMPublicKey: a Kyber-1024 public key (a PQXDH prekey), built from bytes or from a native handle.';
|
||||
export const LIBSIGNAL_NOTA_SEALED = 'libsignal sealed sender: the envelope key is derived with X25519 (an ephemeral key against the recipient\'s identity key) and HKDF-SHA-256, then AES-256-CTR with HMAC-SHA-256 (v1) or AES-256-GCM-SIV (v2); the session inside is X3DH/PQXDH.';
|
||||
// 0.4.0 (2026-10-18): Kotlin are aceleasi clase fara `new` (Aes256GcmSiv(key), PreKeyBundle(...)); forma fara `new` nu se admite in Java,
|
||||
// unde ar prinde declaratii. In Kotlin, `class X(` / `fun X(` / `constructor(` sunt declaratii, nu apeluri. Si puntea nativa a bibliotecii
|
||||
// insesi (Native.ECPrivateKey_Generate(), Native.KyberKeyPair_Generate(), Native.HKDF_DeriveSecrets(...)): asa isi fac cheile sursele
|
||||
// Kotlin si Java din org.signal.libsignal (ECKeyPair.kt, KEMKeyPair.kt, HKDF.kt), unde ancora e pachetul.
|
||||
function detecteazaLibsignalJvm(ctx, kotlin) {
|
||||
const ancore = ctx.potriviri(/(?<![\w.])(?:import\s+(?:static\s+)?org\.signal\.libsignal\.(?:protocol|crypto|metadata|zkgroup|svr|keytrans)\b|package\s+org\.signal\.libsignal\b)/g);
|
||||
if (!ancore.length) return;
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:(ECKeyPair|IdentityKeyPair|ECPrivateKey)\s*\.\s*generate|(Curve)\s*\.\s*generateKeyPair)\s*\(/g)) {
|
||||
ctx.adauga(m.index, `${m[1] || m[2]}.${m[1] ? 'generate' : 'generateKeyPair'}`, 'call', { grup: 'XDH', nume: 'X25519', functii: ['keygen'], nota: LIBSIGNAL_NOTA_EC }, { bucata: m[0] });
|
||||
const ctor = kotlin ? '(?<![\\w.])(?<!class\\s)(?<!fun\\s)(?<!constructor\\s)(?<!object\\s)' : '(?<![\\w.])new\\s+';
|
||||
const api = (nume) => (kotlin ? nume : `new ${nume}`);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:(ECKeyPair|IdentityKeyPair|ECPrivateKey)\s*\.\s*generate|(Curve)\s*\.\s*generateKeyPair|Native\s*\.\s*(ECPrivateKey_Generate|IdentityKeyPair_Generate))\s*\(/g)) {
|
||||
const nume = m[3] ? `Native.${m[3]}` : `${m[1] || m[2]}.${m[1] ? 'generate' : 'generateKeyPair'}`;
|
||||
ctx.adauga(m.index, nume, 'call', { grup: 'XDH', nume: 'X25519', functii: ['keygen'], nota: LIBSIGNAL_NOTA_EC }, { bucata: m[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])KEMKeyPair\s*\.\s*generate\s*\(\s*(?:KEMKeyType\s*\.\s*([A-Za-z_0-9]+))?/g)) {
|
||||
ctx.adauga(m.index, 'KEMKeyPair.generate', 'call', kemLibsignal(m[1]), { bucata: m[0].trim() });
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])HKDF\s*\.\s*deriveSecrets\s*\(/g)) {
|
||||
ctx.adauga(m.index, 'HKDF.deriveSecrets', 'call', { grup: 'KDF', nume: 'HKDF', hash: 'SHA256', functii: ['keyderive'], nota: 'libsignal HKDF is HKDF-SHA-256.' }, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Native\s*\.\s*KyberKeyPair_Generate\s*\(/g)) ctx.adauga(m.index, 'Native.KyberKeyPair_Generate', 'call', kemLibsignal('KYBER_1024'), { bucata: m[0] });
|
||||
// puntea cheii Curve25519 (ECPrivateKey.kt / ECPrivateKey.java): acordul X25519, semnatura XEdDSA pe aceeasi cheie, HPKE (RFC 9180, DHKEM X25519)
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Native\s*\.\s*(ECPrivateKey_Agree|ECPrivateKey_Sign|ECPublicKey_Verify|ECPrivateKey_HpkeOpen|ECPublicKey_HpkeSeal)\s*\(/g)) {
|
||||
const act = m[1] === 'ECPrivateKey_Agree' ? { grup: 'XDH', nume: 'X25519', functii: ['other'], nota: 'libsignal Diffie-Hellman agreement over Curve25519.' }
|
||||
: /Hpke/.test(m[1]) ? { grup: 'XDH', nume: 'X25519', primitiv: 'pke', functii: [m[1] === 'ECPublicKey_HpkeSeal' ? 'encrypt' : 'decrypt'], nota: 'libsignal HPKE (RFC 9180) with DHKEM X25519: the key encapsulation is classical.' }
|
||||
: { grup: 'EDDSA', nume: 'XEdDSA (Curve25519)', functii: [m[1] === 'ECPublicKey_Verify' ? 'verify' : 'sign'], nota: 'libsignal XEdDSA: an Ed25519-style signature made with the Curve25519 (X25519) identity key.' };
|
||||
ctx.adauga(m.index, `Native.${m[1]}`, 'call', act, { bucata: m[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])new\s+(Aes256GcmSiv|Aes256GcmEncryption|Aes256GcmDecryption|Aes256Ctr32)\s*\(/g)) {
|
||||
const mod = m[1] === 'Aes256GcmSiv' ? 'gcm-siv' : m[1] === 'Aes256Ctr32' ? 'ctr' : 'gcm';
|
||||
ctx.adauga(m.index, `new ${m[1]}`, 'call', { grup: 'CIPHER', nume: 'AES', param: '256', mod, functii: [m[1] === 'Aes256GcmDecryption' ? 'decrypt' : 'encrypt'] }, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(new RegExp(`${ctor}KEMPublicKey\\s*\\(`, 'g'))) ctx.adauga(m.index, api('KEMPublicKey'), 'call', { grup: 'PREPQ', nume: 'Kyber-1024', primitiv: 'kem', functii: ['other'], nota: LIBSIGNAL_NOTA_KYBER_PK }, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:HKDF\s*\.\s*deriveSecrets|Native\s*\.\s*HKDF_DeriveSecrets)\s*\(/g)) {
|
||||
ctx.adauga(m.index, /Native/.test(m[0]) ? 'Native.HKDF_DeriveSecrets' : 'HKDF.deriveSecrets', 'call', { grup: 'KDF', nume: 'HKDF', hash: 'SHA256', functii: ['keyderive'], nota: 'libsignal HKDF is HKDF-SHA-256.' }, { bucata: m[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])new\s+PreKeyBundle\s*\(/g)) ctx.adauga(m.index, 'new PreKeyBundle', 'call', LIBSIGNAL_BUNDLE, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(new RegExp(`${ctor}(Aes256GcmSiv|Aes256GcmEncryption|Aes256GcmDecryption|Aes256Ctr32)\\s*\\(|(?<![\\w.])Native\\s*\\.\\s*(Aes256GcmSiv|Aes256GcmEncryption|Aes256GcmDecryption|Aes256Ctr32)_New\\s*\\(`, 'g'))) {
|
||||
const tip = m[1] || m[2];
|
||||
const mod = tip === 'Aes256GcmSiv' ? 'gcm-siv' : tip === 'Aes256Ctr32' ? 'ctr' : 'gcm';
|
||||
ctx.adauga(m.index, m[2] ? `Native.${m[2]}_New` : api(tip), 'call', { grup: 'CIPHER', nume: 'AES', param: '256', mod, functii: [tip === 'Aes256GcmDecryption' ? 'decrypt' : 'encrypt'] }, { bucata: m[0] });
|
||||
}
|
||||
for (const m of ctx.potriviri(new RegExp(`${ctor}PreKeyBundle\\s*\\(|(?<![\\w.])Native\\s*\\.\\s*(?:PreKeyBundle_New|SessionBuilder_ProcessPreKeyBundle)\\s*\\(`, 'g'))) ctx.adauga(m.index, /Native/.test(m[0]) ? m[0].replace(/\s+|\($/g, '') : api('PreKeyBundle'), 'call', LIBSIGNAL_BUNDLE, { bucata: m[0] });
|
||||
for (const m of ctx.potriviri(new RegExp(`${ctor}SealedSessionCipher\\s*\\(`, 'g'))) ctx.adauga(m.index, api('SealedSessionCipher'), 'call', { grup: 'XDH', nume: 'X25519', functii: ['keygen'], nota: LIBSIGNAL_NOTA_SEALED }, { bucata: m[0] });
|
||||
// importul: dovada slaba, o singura data pe fisier, suprimata de orice apel recunoscut de mai sus
|
||||
const imp = ancore.find((a) => /^import/.test(a[0]));
|
||||
if (imp) ctx.adauga(imp.index, 'import org.signal.libsignal', 'import', { grup: 'LIB-MULTI', nume: 'libsignal (org.signal.libsignal)', motiv: 'Imports the Signal protocol library (Curve25519 identity and prekeys, Kyber prekeys (PQXDH), Double Ratchet, SPQR, sealed sender); no specific call recognized in this file.' }, { suprimaDe: ['XDH', 'PREPQ', 'MLKEM', 'KDF', 'CIPHER', 'LIB-MULTI'], bucata: imp[0].trim() });
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Detectorul Kotlin (0.4.0, 2026-10-18; scris dupa rularea pe libsignal: 111 fisiere Kotlin, 24.117 randuri, neanalizate prin
|
||||
// constructie). E un adaptor subtire peste detectorul Java: JCA/JSSE, Android Keystore, Tink, OkHttp, verificarea PKIX si API-ul
|
||||
// libsignal sunt aceleasi clase si aceleasi metode; ce difera e sintaxa (fara `new`, fara `;`, `val`/`var`, `arrayOf(...)`,
|
||||
// `ECGenParameterSpec("...")` fara `new`, `Aes256GcmSiv(key)` fara `new`), si lexerul (comentarii imbricate, sabloane `${ }`,
|
||||
// siruri `"""`, literale char), care sta in lexer.mjs. Rezolvarea variabilelor (`val X = "..."`) sta in context.mjs.
|
||||
// Ce NU se recunoaste: extensiile Kotlin peste JCA (`"text".toByteArray().sha256()` dintr-o biblioteca proprie), DSL-urile care
|
||||
// construiesc numele algoritmului din bucati, si `libs.versions.toml` altfel decat ca manifest.
|
||||
import { detecteazaJvm } from './detect-java.mjs';
|
||||
|
||||
export function detecteazaKotlin(ctx) {
|
||||
detecteazaJvm(ctx, true);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Detectorul Swift (0.4.0, 2026-10-18; scris dupa rularea pe libsignal: 210 fisiere Swift, 44.923 randuri, neanalizate prin
|
||||
// constructie). In Swift un modul se vede in fisier numai dupa `import Modul`, deci importurile spun ce poate insemna un nume:
|
||||
// - CryptoKit / Crypto (swift-crypto, acelasi API): SHA256.hash, Insecure.MD5/SHA1, HMAC<SHA256>, AES.GCM.seal/open, ChaChaPoly,
|
||||
// Curve25519.KeyAgreement / .Signing, P256/P384/P521.Signing / .KeyAgreement, HKDF<SHA256>.deriveKey, SymmetricKey(size:),
|
||||
// _RSA (din _CryptoExtras);
|
||||
// - CommonCrypto: CC_SHA256 & co, CCCrypt / CCCryptorCreate cu kCCAlgorithm* si kCCOption*, CCHmac cu kCCHmacAlg*, CCKeyDerivationPBKDF;
|
||||
// - Security: SecKeyCreateRandomKey (tipul si marimea din dictionarul de atribute, inline sau dintr-o variabila a fisierului),
|
||||
// SecKeyCreateSignature / SecKeyVerifySignature / SecKeyCreateEncryptedData / SecKeyCreateDecryptedData cu algoritmul .rsa*/.ecdsa*/.ecies*,
|
||||
// SecTrustEvaluate* si SecPolicyCreateSSL (verificare de certificate: autentificare, nu schimb de cheie);
|
||||
// - TLS-ul clientului: tlsMinimumSupportedProtocolVersion / tlsMaximumSupportedProtocolVersion (URLSessionConfiguration),
|
||||
// sec_protocol_options_set_min/max_tls_protocol_version, NWProtocolTLS.Options();
|
||||
// - CryptoSwift: AES(key:blockMode:), SHA2(variant:), .md5()/.sha256(), HMAC(key:variant:), PBKDF2, ChaCha20, Poly1305, RSA(keySize:), Blowfish;
|
||||
// - Sodium / Clibsodium: sodium.box / .sign / .keyExchange / .secretBox / .aead.xchacha20poly1305ietf / .pwHash / .genericHash si functiile C crypto_*;
|
||||
// - LibSignalClient (si SignalFfi, modulul FFI pe care il importa chiar sursele bibliotecii): IdentityKeyPair.generate(), PrivateKey.generate(),
|
||||
// KEMKeyPair.generate() (Kyber-1024: API-ul Swift nu are parametru de tip, puntea genereaza kem::KeyType::Kyber1024), KEMPublicKey(...),
|
||||
// Aes256GcmSiv(key:), Aes256GcmEncryptedData, Aes256GcmEncryption/Decryption, Aes256Ctr32, hkdf(...), PreKeyBundle(...), processPreKeyBundle(...).
|
||||
// Importul unei biblioteci terte cu multe primitive (LibSignalClient, CryptoSwift, Sodium) fara niciun apel recunoscut e dovada slaba
|
||||
// (unknown, o data pe fisier); cadrele de sistem (CryptoKit, CommonCrypto, Security) nu se raporteaza la import: Security se importa
|
||||
// pentru keychain si SecRandomCopyBytes in aproape orice aplicatie.
|
||||
// Ce NU se recunoaste: un modul adus printr-un bridging header Objective-C (fara `import` in fisierul Swift), tipurile proprii care
|
||||
// invelesc un cadru, metodele pe valori fara constructorul lor in acelasi fisier, `#if DEBUG` (scopul se deriva din cale, nu din modul).
|
||||
import { argumente, escapeRe } from './context.mjs';
|
||||
import { hashCanonic } from './catalog.mjs';
|
||||
|
||||
const NUME_PKIX = 'X.509 chain validation (PKIX)';
|
||||
const NOTA_EC_LIBSIGNAL = 'libsignal Curve25519 key pair: used for Diffie-Hellman (X3DH/PQXDH, Double Ratchet) and for XEdDSA signatures over the same key.';
|
||||
export const NOTA_KEM_SWIFT = 'libsignal Swift KEMKeyPair.generate() takes no key type: the bridge generates kem::KeyType::Kyber1024 (rust/bridge/shared/src/protocol.rs, KYBER_KEY_TYPE), the PQXDH prekey; CRYSTALS-Kyber is the pre-standard form of ML-KEM.';
|
||||
const BUNDLE = { grup: 'LIB-MULTI', nume: 'libsignal session setup (X3DH/PQXDH)', motiv: 'libsignal prekey bundle: Curve25519 identity and signed prekey; a Kyber prekey in the bundle makes the session PQXDH (hybrid). Which prekeys the bundle carries is decided at run time.' };
|
||||
const TLSV = { TLSv10: '1.0', TLSv11: '1.1', TLSv12: '1.2', TLSv13: '1.3', tlsProtocol1: '1.0', tlsProtocol11: '1.1', tlsProtocol12: '1.2', tlsProtocol13: '1.3', sslProtocol3: 'ssl3' };
|
||||
const CURBA_P = { P256: 'secp256r1', P384: 'secp384r1', P521: 'secp521r1' };
|
||||
|
||||
export function importuriSwift(ctx) {
|
||||
const r = new Map(); // modul -> pozitia primului import
|
||||
for (const m of ctx.potriviri(/^[ \t]*(?:@\w+(?:\([^)]*\))?[ \t]+)*import[ \t]+(?:(?:class|struct|enum|protocol|typealias|func|var|let)[ \t]+)?([A-Za-z_]\w*)/gm)) {
|
||||
if (!r.has(m[1])) r.set(m[1], m.index + m[0].indexOf('import'));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// algoritmul SecKeyAlgorithm (.rsaSignatureMessagePKCS1v15SHA256, .ecdsaSignatureMessageX962SHA256, .rsaEncryptionOAEPSHA256, ...)
|
||||
export function algoritmSecKey(nume, functie) {
|
||||
let m;
|
||||
const hash = (s) => { const h = /SHA(1|224|256|384|512)$/.exec(s); return h ? hashCanonic('SHA' + h[1]) : undefined; };
|
||||
if ((m = /^rsaSignature(?:Message|Digest)(PKCS1v15|PSS)(?:SHA\d+|Raw)?$/.exec(nume))) return { grup: 'RSA', primitiv: 'signature', padding: m[1] === 'PSS' ? 'other' : 'pkcs1v15', hash: hash(nume), functii: [functie] };
|
||||
if ((m = /^rsaSignatureRaw$/.exec(nume))) return { grup: 'RSA', primitiv: 'signature', padding: 'raw', functii: [functie] };
|
||||
if ((m = /^rsaEncryption(OAEP|PKCS1|Raw)/.exec(nume))) return { grup: 'RSA', primitiv: 'pke', padding: m[1] === 'OAEP' ? 'oaep' : m[1] === 'PKCS1' ? 'pkcs1v15' : 'raw', hash: hash(nume.replace(/AESGCM$/, '')), functii: [functie] };
|
||||
if ((m = /^ecdsaSignature(?:Message|Digest|Rfc4754)(?:X962|RFC4754)?(?:SHA\d+)?$/.exec(nume))) return { grup: 'ECDSA', hash: hash(nume), functii: [functie] };
|
||||
if (/^eciesEncryption/.test(nume)) return { grup: 'ECDH', nume: `ECIES (${nume})`, primitiv: 'pke', functii: [functie] };
|
||||
if (/^ecdhKeyExchange/.test(nume)) return { grup: 'ECDH', functii: ['keygen'] };
|
||||
return { grup: 'UNKNOWN', nume: `SecKeyAlgorithm.${nume}`, motiv: `SecKeyAlgorithm .${nume} is not in this tool's catalog.` };
|
||||
}
|
||||
|
||||
// tipul si marimea cheii dintr-un dictionar de atribute SecKey (text): kSecAttrKeyTypeRSA / kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits
|
||||
function cheieDinAtribute(text) {
|
||||
const tip = /kSecAttrKeyType(RSA|ECSECPrimeRandom|ECDSA|EC)\b/.exec(text);
|
||||
const bits = /kSecAttrKeySizeInBits(?:\s+as\s+String)?\s*:\s*(\d+)/.exec(text);
|
||||
if (!tip) return null;
|
||||
if (tip[1] === 'RSA') return { grup: 'RSA', param: bits ? bits[1] : undefined, functii: ['keygen'] };
|
||||
const curba = bits ? ({ 256: 'secp256r1', 384: 'secp384r1', 521: 'secp521r1', 224: 'secp224r1', 192: 'secp192r1' })[bits[1]] : undefined;
|
||||
return { grup: 'EC', curba, functii: ['keygen'] };
|
||||
}
|
||||
|
||||
export function detecteazaSwift(ctx) {
|
||||
const c = ctx.code;
|
||||
const imp = importuriSwift(ctx);
|
||||
const are = (...module) => module.some((m) => imp.has(m));
|
||||
const folosite = new Set(); // bibliotecile terte cu cel putin un apel recunoscut (nu primesc dovada slaba de import)
|
||||
const adauga = (lib, pos, api, fel, activ, bucata) => { if (lib) folosite.add(lib); ctx.adauga(pos, api, fel, activ, { bucata }); };
|
||||
const randul = (pos) => { const a = c.lastIndexOf('\n', pos) + 1; const b = c.indexOf('\n', pos); return c.slice(a, b < 0 ? c.length : b); };
|
||||
const argsDupa = (m) => argumente(ctx, m.index + m[0].length);
|
||||
|
||||
// --- CryptoKit / swift-crypto ---------------------------------------------------------------------------------------------------
|
||||
if (are('CryptoKit', 'Crypto', '_CryptoExtras')) {
|
||||
const bitsPeRand = (pos) => { const b = /SymmetricKey\s*\(\s*size\s*:\s*\.bits(128|192|256)\s*\)/.exec(randul(pos)); return b ? b[1] : undefined; };
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(SHA256|SHA384|SHA512)\s*(?:\.\s*hash\s*\(|\(\s*\))/g)) adauga(null, m.index, `${m[1]}${/hash/.test(m[0]) ? '.hash' : '()'}`, 'call', { grup: 'HASH', hash: m[1], functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Insecure\s*\.\s*(MD5|SHA1)\s*(?:\.\s*hash\s*\(|\(\s*\))/g)) adauga(null, m.index, `Insecure.${m[1]}`, 'call', { grup: 'HASH', hash: m[1], functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])HMAC\s*<\s*(?:Insecure\s*\.\s*)?(MD5|SHA1|SHA256|SHA384|SHA512)\s*>/g)) adauga(null, m.index, `HMAC<${m[1]}>`, 'call', { grup: 'MAC', hash: m[1], functii: ['tag'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])HKDF\s*<\s*(?:Insecure\s*\.\s*)?(MD5|SHA1|SHA256|SHA384|SHA512)\s*>\s*\.\s*(deriveKey|extract|expand)/g)) adauga(null, m.index, `HKDF<${m[1]}>.${m[2]}`, 'call', { grup: 'KDF', nume: 'HKDF', hash: m[1], functii: ['keyderive'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])AES\s*\.\s*GCM\s*\.\s*(seal|open|SealedBox|Nonce)\b/g)) adauga(null, m.index, `AES.GCM.${m[1]}`, 'call', { grup: 'CIPHER', nume: 'AES', param: bitsPeRand(m.index), mod: 'gcm', functii: [m[1] === 'open' ? 'decrypt' : 'encrypt'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])AES\s*\.\s*KeyWrap\s*\.\s*(wrap|unwrap)\b/g)) adauga(null, m.index, `AES.KeyWrap.${m[1]}`, 'call', { grup: 'CIPHER', nume: 'AES', param: bitsPeRand(m.index), mod: 'kw', functii: ['encrypt'], nota: 'AES key wrap (RFC 3394).' }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])ChaChaPoly\s*\.\s*(seal|open|SealedBox|Nonce)\b/g)) adauga(null, m.index, `ChaChaPoly.${m[1]}`, 'call', { grup: 'CIPHER', nume: 'ChaCha20-Poly1305', functii: [m[1] === 'open' ? 'decrypt' : 'encrypt'] }, m[0]);
|
||||
// constructorii (PrivateKey(), PublicKey(rawRepresentation:)), nu tipul scris intr-o semnatura (`peer: Curve25519.KeyAgreement.PublicKey`)
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Curve25519\s*\.\s*(KeyAgreement|Signing)\s*\.\s*(PrivateKey|PublicKey)\s*\(/g)) {
|
||||
adauga(null, m.index, `Curve25519.${m[1]}.${m[2]}`, 'call', m[1] === 'KeyAgreement' ? { grup: 'XDH', nume: 'X25519', functii: [m[2] === 'PrivateKey' ? 'keygen' : 'other'] } : { grup: 'EDDSA', nume: 'Ed25519', functii: [m[2] === 'PrivateKey' ? 'keygen' : 'verify'] }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(P256|P384|P521)\s*\.\s*(KeyAgreement|Signing)\s*\.\s*(PrivateKey|PublicKey|ECDSASignature)\s*\(/g)) {
|
||||
const curba = CURBA_P[m[1]];
|
||||
adauga(null, m.index, `${m[1]}.${m[2]}.${m[3]}`, 'call', m[2] === 'KeyAgreement' ? { grup: 'ECDH', curba, functii: [m[3] === 'PrivateKey' ? 'keygen' : 'other'] } : { grup: 'ECDSA', curba, functii: [m[3] === 'PrivateKey' ? 'keygen' : 'verify'] }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])_RSA\s*\.\s*(Signing|Encryption)\s*\.\s*(PrivateKey|PublicKey)\s*(\(\s*keySize\s*:\s*\.bits(\d+)|\()/g)) {
|
||||
adauga(null, m.index, `_RSA.${m[1]}.${m[2]}`, 'call', { grup: 'RSA', param: m[4], primitiv: m[1] === 'Signing' ? 'signature' : 'pke', functii: [m[2] === 'PrivateKey' ? 'keygen' : 'other'] }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])SymmetricKey\s*\(\s*size\s*:\s*\.bits(128|192|256)\s*\)/g)) {
|
||||
if (/AES\s*\.\s*(GCM|KeyWrap)|ChaChaPoly|HMAC\s*<|HKDF\s*</.test(randul(m.index))) continue; // marimea e deja in cifrul de pe acelasi rand
|
||||
adauga(null, m.index, 'SymmetricKey(size:)', 'call', { grup: 'UNKNOWN', nume: `SymmetricKey (${m[1]}-bit)`, motiv: `CryptoKit SymmetricKey of ${m[1]} bits: the algorithm that uses it (AES-GCM, ChaChaPoly, HMAC, HKDF) is chosen where the key is used, not here.` }, m[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// --- CommonCrypto ------------------------------------------------------------------------------------------------------------------
|
||||
if (are('CommonCrypto')) {
|
||||
for (const m of ctx.potriviri(/(?<![\w.])CC_(MD2|MD4|MD5|SHA1|SHA224|SHA256|SHA384|SHA512)(?:_Init|_Update|_Final)?\s*\(/g)) adauga(null, m.index, m[0].replace(/\s*\($/, ''), 'call', { grup: 'HASH', hash: m[1], functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(CCCrypt|CCCryptorCreate(?:WithMode)?)\s*\(/g)) {
|
||||
const t = argsDupa(m).text;
|
||||
const alg = /kCCAlgorithm(AES128|AES|DES|3DES|CAST|RC4|RC2|Blowfish)\b/.exec(t);
|
||||
if (!alg) { adauga(null, m.index, m[1], 'call', { grup: 'UNKNOWN', nume: m[1], motiv: `${m[1]}: the algorithm constant (kCCAlgorithm*) is not among the arguments of this call.` }, m[0]); continue; }
|
||||
const bits = /kCCKeySizeAES(128|192|256)\b/.exec(t);
|
||||
const mod = /kCCOptionECBMode\b/.test(t) ? 'ecb' : /kCCModeCTR\b/.test(t) ? 'ctr' : /kCCModeGCM\b/.test(t) ? 'gcm' : /kCCModeCFB\b/.test(t) ? 'cfb' : /kCCModeOFB\b/.test(t) ? 'ofb' : 'cbc';
|
||||
const nume = { AES128: 'AES', AES: 'AES', DES: 'DES', '3DES': '3DES', CAST: 'CAST5', RC4: 'RC4', RC2: 'RC2', Blowfish: 'Blowfish' }[alg[1]];
|
||||
adauga(null, m.index, `${m[1]}(kCCAlgorithm${alg[1]})`, 'call', { grup: 'CIPHER', nume, param: nume === 'AES' ? (bits ? bits[1] : undefined) : undefined, mod: /^(RC4)$/.test(nume) ? undefined : mod, functii: [/kCCDecrypt\b/.test(t) ? 'decrypt' : 'encrypt'], nota: nume === 'AES' && mod === 'cbc' && !/kCCMode/.test(t) ? 'CommonCrypto block ciphers default to CBC unless kCCOptionECBMode is set.' : undefined }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])CCHmac(?:Init)?\s*\(/g)) {
|
||||
const h = /kCCHmacAlg(MD5|SHA1|SHA224|SHA256|SHA384|SHA512)\b/.exec(argsDupa(m).text);
|
||||
adauga(null, m.index, 'CCHmac', 'call', h ? { grup: 'MAC', hash: h[1], functii: ['tag'] } : { grup: 'MAC', motiv: 'CCHmac: the hash constant (kCCHmacAlg*) is not among the arguments of this call.' }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])CCKeyDerivationPBKDF\s*\(/g)) {
|
||||
const h = /kCCPRFHmacAlg(SHA1|SHA224|SHA256|SHA384|SHA512)\b/.exec(argsDupa(m).text);
|
||||
adauga(null, m.index, 'CCKeyDerivationPBKDF', 'call', { grup: 'KDF', nume: h ? `PBKDF2-HMAC-${h[1]}` : 'PBKDF2', hash: h ? h[1] : undefined, functii: ['keyderive'] }, m[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Security.framework --------------------------------------------------------------------------------------------------------------
|
||||
if (are('Security')) {
|
||||
for (const m of ctx.potriviri(/(?<![\w.])SecKeyCreateRandomKey\s*\(/g)) {
|
||||
const a = argsDupa(m);
|
||||
let act = cheieDinAtribute(a.text);
|
||||
if (!act) {
|
||||
const id = /^\s*([A-Za-z_]\w*)\b/.exec(a.text);
|
||||
const def = id && new RegExp(`(?<![\\w.])(?:let|var)\\s+${escapeRe(id[1])}\\b[^=\\n]*=\\s*\\[`).exec(c);
|
||||
if (def) act = cheieDinAtribute(c.slice(def.index, argumente(ctx, def.index + def[0].length).end + 1));
|
||||
}
|
||||
adauga(null, m.index, 'SecKeyCreateRandomKey', 'call', act || { grup: 'UNKNOWN', nume: 'SecKeyCreateRandomKey', motiv: 'SecKeyCreateRandomKey: the key type (kSecAttrKeyType) is not in the attributes of this call nor in a dictionary defined in this file.' }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])SecKey(CreateSignature|VerifySignature|CreateEncryptedData|CreateDecryptedData)\s*\(/g)) {
|
||||
const a = argsDupa(m);
|
||||
const fn = { CreateSignature: 'sign', VerifySignature: 'verify', CreateEncryptedData: 'encrypt', CreateDecryptedData: 'decrypt' }[m[1]];
|
||||
let alg = /(?:SecKeyAlgorithm\s*)?\.\s*((?:rsa|ecdsa|ecies|ecdh)\w+)/.exec(a.text);
|
||||
if (!alg) {
|
||||
const parti = a.text.split(',');
|
||||
const id = parti[1] && /^\s*([A-Za-z_]\w*)\s*$/.exec(parti[1]);
|
||||
if (id) alg = new RegExp(`(?<![\\w.])(?:let|var)\\s+${escapeRe(id[1])}\\s*(?::\\s*SecKeyAlgorithm\\s*)?=\\s*(?:SecKeyAlgorithm\\s*)?\\.\\s*((?:rsa|ecdsa|ecies|ecdh)\\w+)`).exec(c);
|
||||
}
|
||||
adauga(null, m.index, `SecKey${m[1]}`, 'call', alg ? algoritmSecKey(alg[1], fn) : { grup: 'UNKNOWN', nume: `SecKey${m[1]}`, motiv: `SecKey${m[1]}: the SecKeyAlgorithm is not a literal in this call nor a variable set once in this file.` }, m[0] + (alg ? `.${alg[1]}` : ''));
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(SecTrustEvaluate(?:WithError|AsyncWithError|Async)?|SecPolicyCreateSSL)\s*\(/g)) adauga(null, m.index, m[1], 'call', { grup: 'PKI-VERIFY', nume: NUME_PKIX, functii: ['verify'] }, m[0]);
|
||||
}
|
||||
|
||||
// --- TLS-ul clientului (URLSession, Network) ---------------------------------------------------------------------------------------
|
||||
for (const m of ctx.potriviri(/\.\s*tls(Minimum|Maximum)SupportedProtocolVersion\s*=\s*\.(TLSv10|TLSv11|TLSv12|TLSv13)\b/g)) adauga(null, m.index, `tls${m[1]}SupportedProtocolVersion`, 'config', { grup: 'TLS', param: TLSV[m[2]], rol: m[1] === 'Minimum' ? 'min' : 'max' }, m[0].trim());
|
||||
for (const m of ctx.potriviri(/\.\s*TLS(Minimum|Maximum)SupportedProtocol\s*=\s*\.(tlsProtocol1|tlsProtocol11|tlsProtocol12|tlsProtocol13|sslProtocol3)\b/g)) adauga(null, m.index, `TLS${m[1]}SupportedProtocol`, 'config', { grup: 'TLS', param: TLSV[m[2]], rol: m[1] === 'Minimum' ? 'min' : 'max' }, m[0].trim());
|
||||
for (const m of ctx.potriviri(/(?<![\w.])sec_protocol_options_set_(min|max)_tls_protocol_version\s*\(\s*[^,]+,\s*\.(TLSv10|TLSv11|TLSv12|TLSv13)\b/g)) adauga(null, m.index, `sec_protocol_options_set_${m[1]}_tls_protocol_version`, 'config', { grup: 'TLS', param: TLSV[m[2]], rol: m[1] }, m[0]);
|
||||
if (are('Network')) for (const m of ctx.potriviri(/(?<![\w.])NWProtocolTLS\s*\.\s*Options\s*\(/g)) adauga(null, m.index, 'NWProtocolTLS.Options', 'config', { grup: 'TLS', param: 'negotiated' }, m[0]);
|
||||
|
||||
// --- CryptoSwift -----------------------------------------------------------------------------------------------------------------------
|
||||
if (are('CryptoSwift')) {
|
||||
const L = 'CryptoSwift';
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(AES|Blowfish)\s*\(\s*key\s*:/g)) {
|
||||
const mod = /blockMode\s*:\s*(GCM|CBC|ECB|CTR|CCM|OFB|CFB|PCBC)\b/.exec(argsDupa(m).text);
|
||||
adauga(L, m.index, `${m[1]}(key:blockMode:)`, 'call', { grup: 'CIPHER', nume: m[1], mod: mod ? mod[1].toLowerCase() : undefined, functii: ['encrypt', 'decrypt'] }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])SHA2\s*\(\s*variant\s*:\s*\.(sha224|sha256|sha384|sha512)\b/g)) adauga(L, m.index, 'SHA2(variant:)', 'call', { grup: 'HASH', hash: m[1].toUpperCase(), functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])SHA3\s*\(\s*variant\s*:\s*\.(sha224|sha256|sha384|sha512|keccak224|keccak256|keccak384|keccak512)\b/g)) adauga(L, m.index, 'SHA3(variant:)', 'call', { grup: 'HASH', hash: /^keccak/.test(m[1]) ? 'KECCAK256' : 'SHA3-' + m[1].slice(3), functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:MD5|SHA1)\s*\(\s*\)/g)) adauga(L, m.index, m[0].replace(/\s+/g, ''), 'call', { grup: 'HASH', hash: m[0].startsWith('MD5') ? 'MD5' : 'SHA1', functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Digest\s*\.\s*(md5|sha1|sha224|sha256|sha384|sha512)\s*\(/g)) adauga(L, m.index, `Digest.${m[1]}`, 'call', { grup: 'HASH', hash: m[1].toUpperCase(), functii: ['digest'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/\.\s*(md5|sha1|sha224|sha256|sha384|sha512)\s*\(\s*\)/g)) adauga(L, m.index, `.${m[1]}()`, 'call', { grup: 'HASH', hash: m[1].toUpperCase(), functii: ['digest'] }, m[0].trim());
|
||||
for (const m of ctx.potriviri(/(?<![\w.])HMAC\s*\(\s*key\s*:/g)) {
|
||||
const v = /variant\s*:\s*\.(md5|sha1|sha224|sha256|sha384|sha512)\b/.exec(argsDupa(m).text);
|
||||
adauga(L, m.index, 'HMAC(key:variant:)', 'call', v ? { grup: 'MAC', hash: v[1].toUpperCase(), functii: ['tag'] } : { grup: 'MAC', hash: 'MD5', functii: ['tag'], nota: 'CryptoSwift HMAC without variant: defaults to MD5.' }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?:PKCS5\s*\.\s*)?PBKDF2\s*\(/g)) {
|
||||
const v = /variant\s*:\s*\.(md5|sha1|sha224|sha256|sha384|sha512)\b/.exec(argsDupa(m).text);
|
||||
adauga(L, m.index, 'PBKDF2', 'call', { grup: 'KDF', nume: v ? `PBKDF2-HMAC-${v[1].toUpperCase()}` : 'PBKDF2', hash: v ? v[1].toUpperCase() : undefined, functii: ['keyderive'] }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Scrypt\s*\(/g)) adauga(L, m.index, 'Scrypt', 'call', { grup: 'KDF', nume: 'scrypt', functii: ['keyderive'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])ChaCha20\s*\(\s*key\s*:/g)) adauga(L, m.index, 'ChaCha20(key:iv:)', 'call', { grup: 'CIPHER', nume: 'ChaCha20', functii: ['encrypt', 'decrypt'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Poly1305\s*\(\s*key\s*:/g)) adauga(L, m.index, 'Poly1305(key:)', 'call', { grup: 'MAC', nume: 'Poly1305', functii: ['tag'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])Rabbit\s*\(\s*key\s*:/g)) adauga(L, m.index, 'Rabbit(key:)', 'call', { grup: 'CIPHER', nume: 'Rabbit', functii: ['encrypt', 'decrypt'] }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])RSA\s*\(\s*(?:keySize\s*:\s*(\d+)|[nedp]\s*:|rawRepresentation\s*:|publicDER|privateDER)/g)) adauga(L, m.index, 'RSA(...)', 'call', { grup: 'RSA', param: m[1], functii: [m[1] ? 'keygen' : 'other'] }, m[0]);
|
||||
}
|
||||
|
||||
// --- Sodium (swift-sodium) si Clibsodium ------------------------------------------------------------------------------------------------
|
||||
if (are('Sodium', 'Clibsodium')) {
|
||||
const L = imp.has('Sodium') ? 'Sodium' : 'Clibsodium';
|
||||
const X = (nota) => ({ grup: 'XDH', nume: 'X25519', functii: ['keygen'], nota });
|
||||
const FORME = [
|
||||
[/\.\s*box\s*\.\s*(keyPair|seal|open|beforenm)\s*\(/g, 'sodium.box', () => X('libsodium crypto_box: X25519 key agreement with XSalsa20-Poly1305.')],
|
||||
[/\.\s*sealedBox\s*\.\s*(seal|open)\s*\(/g, 'sodium.sealedBox', () => X('libsodium sealed box: an ephemeral X25519 key against the recipient key, XSalsa20-Poly1305.')],
|
||||
[/\.\s*keyExchange\s*\.\s*(keyPair|sessionKeyPair)\s*\(/g, 'sodium.keyExchange', () => X('libsodium crypto_kx: X25519 with BLAKE2b.')],
|
||||
[/\.\s*sign\s*\.\s*(keyPair|signature|sign|verify|open)\s*\(/g, 'sodium.sign', (m) => ({ grup: 'EDDSA', nume: 'Ed25519', functii: [m[1] === 'keyPair' ? 'keygen' : /verify|open/.test(m[1]) ? 'verify' : 'sign'] })],
|
||||
[/\.\s*secretBox\s*\.\s*(seal|open)\s*\(/g, 'sodium.secretBox', (m) => ({ grup: 'CIPHER', nume: 'XSalsa20-Poly1305', functii: [m[1] === 'open' ? 'decrypt' : 'encrypt'] })],
|
||||
[/\.\s*aead\s*\.\s*xchacha20poly1305ietf\s*\.\s*(encrypt|decrypt)\s*\(/g, 'sodium.aead.xchacha20poly1305ietf', (m) => ({ grup: 'CIPHER', nume: 'XChaCha20-Poly1305', functii: [m[1]] })],
|
||||
[/\.\s*pwHash\s*\.\s*(hash|str|strVerify)\s*\(/g, 'sodium.pwHash', () => ({ grup: 'KDF', nume: 'Argon2id', functii: ['keyderive'] })],
|
||||
[/\.\s*genericHash\s*\.\s*(hash|initStream)\s*\(/g, 'sodium.genericHash', () => ({ grup: 'HASH', hash: 'BLAKE2B', functii: ['digest'] })],
|
||||
[/(?<![\w.])crypto_(?:box|scalarmult|kx)(?:_\w+)?\s*\(/g, 'crypto_box', () => X('libsodium crypto_box / crypto_kx / crypto_scalarmult: X25519.')],
|
||||
[/(?<![\w.])crypto_sign(?:_\w+)?\s*\(/g, 'crypto_sign', (m) => ({ grup: 'EDDSA', nume: 'Ed25519', functii: [/keypair/.test(m[0]) ? 'keygen' : /verify|open/.test(m[0]) ? 'verify' : 'sign'] })],
|
||||
[/(?<![\w.])crypto_aead_(xchacha20poly1305|chacha20poly1305|aes256gcm|aegis256|aegis128l)(?:_ietf)?_(encrypt|decrypt)(?:_detached)?\s*\(/g, 'crypto_aead', (m) => ({ grup: 'CIPHER', nume: { xchacha20poly1305: 'XChaCha20-Poly1305', chacha20poly1305: 'ChaCha20-Poly1305', aes256gcm: 'AES', aegis256: 'AEGIS-256', aegis128l: 'AEGIS-128L' }[m[1]], param: m[1] === 'aes256gcm' ? '256' : undefined, mod: m[1] === 'aes256gcm' ? 'gcm' : undefined, functii: [m[2]] })],
|
||||
[/(?<![\w.])crypto_secretbox(?:_\w+)?\s*\(/g, 'crypto_secretbox', () => ({ grup: 'CIPHER', nume: 'XSalsa20-Poly1305', functii: ['encrypt'] })],
|
||||
[/(?<![\w.])crypto_pwhash(?:_\w+)?\s*\(/g, 'crypto_pwhash', () => ({ grup: 'KDF', nume: 'Argon2id', functii: ['keyderive'] })],
|
||||
[/(?<![\w.])crypto_generichash(?:_\w+)?\s*\(/g, 'crypto_generichash', () => ({ grup: 'HASH', hash: 'BLAKE2B', functii: ['digest'] })],
|
||||
[/(?<![\w.])crypto_hash_(sha256|sha512)(?:_\w+)?\s*\(/g, 'crypto_hash', (m) => ({ grup: 'HASH', hash: m[1].toUpperCase(), functii: ['digest'] })],
|
||||
[/(?<![\w.])crypto_auth(?:_\w+)?\s*\(/g, 'crypto_auth', () => ({ grup: 'MAC', hash: 'SHA512/256', functii: ['tag'] })],
|
||||
];
|
||||
for (const [re, api, act] of FORME) for (const m of ctx.potriviri(re)) adauga(L, m.index, api, 'call', act(m), m[0].trim());
|
||||
}
|
||||
|
||||
// --- libsignal (LibSignalClient; in sursele bibliotecii, SignalFfi) ----------------------------------------------------------------
|
||||
// Swift nu declara modulul in fisier: un fisier din tinta SwiftPM `LibSignalClient` (dosarul Sources/LibSignalClient/) vede numele
|
||||
// bibliotecii fara niciun import (masurat pe libsignal: DataStoreInMemory.swift, `IdentityKeyPair.generate()`, importa doar
|
||||
// Foundation). A treia ancora e deci dosarul cu numele modulului, scrisa pe cale.
|
||||
const inModulLibsignal = /(^|\/)LibSignalClient(Tests)?\//.test(String(ctx.rel || '').replace(/\\/g, '/'));
|
||||
const libsignal = are('LibSignalClient', 'SignalFfi') || inModulLibsignal;
|
||||
if (libsignal) {
|
||||
const L = 'LibSignalClient';
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(IdentityKeyPair|PrivateKey)\s*\.\s*generate\s*\(\s*\)/g)) adauga(L, m.index, `${m[1]}.generate`, 'call', { grup: 'XDH', nume: 'X25519', functii: ['keygen'], nota: NOTA_EC_LIBSIGNAL }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])KEMKeyPair\s*\.\s*generate\s*\(\s*\)/g)) adauga(L, m.index, 'KEMKeyPair.generate', 'call', { grup: 'PREPQ', nume: 'Kyber-1024', primitiv: 'kem', functii: ['keygen'], nota: NOTA_KEM_SWIFT }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?<!class\s)(?<!func\s)KEMPublicKey\s*\(/g)) adauga(L, m.index, 'KEMPublicKey(...)', 'call', { grup: 'PREPQ', nume: 'Kyber-1024', primitiv: 'kem', functii: ['other'], nota: 'libsignal KEMPublicKey: a Kyber-1024 public key (a PQXDH prekey), built from bytes or from a native handle.' }, m[0]);
|
||||
// constructorii (Aes256GcmSiv(key:), Aes256Ctr32(key:nonce:)) si formele statice (Aes256Ctr32.process(_:key:nonce:), CryptoTests.swift:169;
|
||||
// Aes256GcmEncryptedData.encrypt(_:key:)); numele tipului intr-o declaratie (class/struct) sau intr-o constanta (Aes256Ctr32.nonceLength) nu e un apel
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?<!class\s)(?<!struct\s)(Aes256GcmSiv|Aes256GcmEncryption|Aes256GcmDecryption|Aes256Ctr32|Aes256GcmEncryptedData)\s*(?:\.\s*(encrypt|decrypt|process)\s*)?\(/g)) {
|
||||
const tip = m[1];
|
||||
const mod = tip === 'Aes256GcmSiv' ? 'gcm-siv' : tip === 'Aes256Ctr32' ? 'ctr' : 'gcm';
|
||||
const fn = m[2] === 'decrypt' || tip === 'Aes256GcmDecryption' || (tip === 'Aes256GcmEncryptedData' && !m[2]) ? 'decrypt' : 'encrypt';
|
||||
adauga(L, m.index, m[0].replace(/\s+/g, '').replace(/\($/, ''), 'call', { grup: 'CIPHER', nume: 'AES', param: '256', mod, functii: [fn] }, m[0]);
|
||||
}
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?<!func\s)hkdf\s*\(/g)) adauga(L, m.index, 'hkdf', 'call', { grup: 'KDF', nume: 'HKDF', hash: 'SHA256', functii: ['keyderive'], nota: 'libsignal HKDF is HKDF-SHA-256.' }, m[0]);
|
||||
for (const m of ctx.potriviri(/(?<![\w.])(?<!class\s)PreKeyBundle\s*\(|(?<![\w.])(?<!func\s)processPreKeyBundle\s*\(/g)) adauga(L, m.index, m[0].replace(/\s*\($/, ''), 'call', BUNDLE, m[0]);
|
||||
}
|
||||
|
||||
// --- importurile bibliotecilor terte fara niciun apel recunoscut: dovada slaba, o data pe fisier ----------------------------------------
|
||||
const TERTE = {
|
||||
LibSignalClient: 'libsignal for Swift (Curve25519 identity and prekeys, Kyber prekeys (PQXDH), Double Ratchet, SPQR, sealed sender)',
|
||||
CryptoSwift: 'CryptoSwift (AES, ChaCha20, Blowfish, RSA, SHA-2/3, MD5, SHA-1, HMAC, PBKDF2)',
|
||||
Sodium: 'swift-sodium (libsodium: X25519, Ed25519, XSalsa20/XChaCha20-Poly1305, Argon2, BLAKE2b)',
|
||||
Clibsodium: 'libsodium (X25519, Ed25519, XSalsa20/XChaCha20-Poly1305, Argon2, BLAKE2b)',
|
||||
};
|
||||
for (const [modul, descriere] of Object.entries(TERTE)) {
|
||||
if (!imp.has(modul) || folosite.has(modul) || (modul === 'Clibsodium' && folosite.has('Sodium'))) continue;
|
||||
ctx.adauga(imp.get(modul), `import ${modul}`, 'import', { grup: 'LIB-MULTI', nume: modul === 'LibSignalClient' ? 'libsignal (LibSignalClient)' : modul, motiv: `Imports ${descriere}; no specific call recognized in this file.` }, { suprimaDe: ['XDH', 'EDDSA', 'PREPQ', 'MLKEM', 'KDF', 'CIPHER', 'HASH', 'MAC', 'RSA', 'LIB-MULTI'], bucata: `import ${modul}` });
|
||||
}
|
||||
}
|
||||
@@ -16,10 +16,199 @@ export function curata(text, limbaj) {
|
||||
case 'go': return curataC(text, { raw: true });
|
||||
case 'python': return curataPython(text);
|
||||
case 'rust': return curataRust(text);
|
||||
case 'swift': return curataSwift(text);
|
||||
case 'kotlin': return curataKotlin(text);
|
||||
default: return { code: text, siruri: [] };
|
||||
}
|
||||
}
|
||||
|
||||
// Sfarsitul unui comentariu bloc IMBRICAT (/* a /* b */ c */) care incepe la i; n daca nu se inchide. Comun pentru Rust, Swift si
|
||||
// Kotlin: toate trei imbrica; un lexer C ar fi inchis comentariul la primul */ si ar fi lasat restul drept cod.
|
||||
function sfarsitComentariuImbricat(text, i, n) {
|
||||
let j = i + 2;
|
||||
let ad = 1;
|
||||
while (j < n && ad > 0) {
|
||||
if (text[j] === '/' && text[j + 1] === '*') { ad++; j += 2; continue; }
|
||||
if (text[j] === '*' && text[j + 1] === '/') { ad--; j += 2; continue; }
|
||||
j++;
|
||||
}
|
||||
return j;
|
||||
}
|
||||
|
||||
// Swift (0.4.0, 2026-10-18): comentariile bloc se imbrica; sirurile sunt "..." (un singur rand), """...""" (multi-rand), si formele
|
||||
// brute #"..."# / #"""..."""# cu oricate diezuri; INTERPOLAREA \( expr ) (in sirurile brute \#( expr )) poate contine la randul ei
|
||||
// siruri si paranteze, deci sfarsitul sirului se cauta cu o stiva de cadre, nu cu "pana la urmatorul ghilimea". Nu exista literale
|
||||
// char. Scanarea e ITERATIVA (stiva explicita): un fisier facut anume din `"\(` repetat ar fi 85.000 de niveluri de recursie.
|
||||
// Continutul sirului (interpolare inclusa) ramane un singur interval: un nume de API scris in interpolare nu e o folosire masurata.
|
||||
function sfarsitSirSwift(text, start, n) {
|
||||
// cadre: { fel: 'sir', diezi, multi } sau { fel: 'interp', ad } (ad = paranteze deschise in interpolare)
|
||||
const stiva = [];
|
||||
const deschide = (j) => {
|
||||
let d = 0;
|
||||
while (text[j] === '#') { d++; j++; }
|
||||
if (text[j] !== '"') return -1;
|
||||
const multi = text.startsWith('"""', j);
|
||||
stiva.push({ fel: 'sir', diezi: d, multi });
|
||||
return j + (multi ? 3 : 1);
|
||||
};
|
||||
let j = deschide(start);
|
||||
if (j < 0) return -1;
|
||||
while (j < n && stiva.length) {
|
||||
const cadru = stiva[stiva.length - 1];
|
||||
const c = text[j];
|
||||
if (cadru.fel === 'sir') {
|
||||
if (c === '\\') {
|
||||
// escape-ul unui sir brut e \ urmat de exact `diezi` diezi; un \ singur in sirul brut e un caracter obisnuit
|
||||
let k = j + 1;
|
||||
let d = 0;
|
||||
while (d < cadru.diezi && text[k] === '#') { d++; k++; }
|
||||
if (d < cadru.diezi) { j++; continue; }
|
||||
if (text[k] === '(') { stiva.push({ fel: 'interp', ad: 1 }); j = k + 1; continue; }
|
||||
j = k + 1; continue;
|
||||
}
|
||||
if (c === '"') {
|
||||
const inchidere = (cadru.multi ? '"""' : '"') + '#'.repeat(cadru.diezi);
|
||||
if (text.startsWith(inchidere, j)) { stiva.pop(); j += inchidere.length; continue; }
|
||||
j++; continue;
|
||||
}
|
||||
if (c === '\n' && !cadru.multi) { stiva.pop(); j++; continue; } // sir neterminat pe rand: se inchide la capatul randului
|
||||
j++; continue;
|
||||
}
|
||||
// in interpolare: paranteze echilibrate, siruri imbricate
|
||||
if (c === '(') { cadru.ad++; j++; continue; }
|
||||
if (c === ')') { if (--cadru.ad === 0) stiva.pop(); j++; continue; }
|
||||
if (c === '"' || (c === '#' && /^#+"/.test(text.slice(j, j + 8)))) {
|
||||
const k = deschide(j);
|
||||
if (k >= 0) { j = k; continue; }
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return Math.min(j, n);
|
||||
}
|
||||
|
||||
function curataSwift(text) {
|
||||
const n = text.length;
|
||||
const out = text.split('');
|
||||
const goleste = golitor(out);
|
||||
const siruri = [];
|
||||
let i = 0;
|
||||
while (i < n) {
|
||||
const c = text[i];
|
||||
const d = text[i + 1];
|
||||
if (c === '/' && d === c) { // (scris altfel decat in lexerul C si in cel Rust: controlul negativ isi ancoreaza cioturile pe acelea)
|
||||
let j = i;
|
||||
while (j < n && text[j] !== '\n') j++;
|
||||
goleste(i, j); i = j; continue;
|
||||
}
|
||||
if (c === '/' && d === '*') {
|
||||
const jSw = sfarsitComentariuImbricat(text, i, n);
|
||||
goleste(i, jSw); i = jSw; continue;
|
||||
}
|
||||
if (c === '"' || (c === '#' && (d === '#' || d === '"'))) {
|
||||
const sf = sfarsitSirSwift(text, i, n);
|
||||
if (sf > i) { siruri.push([i, sf]); i = sf; continue; }
|
||||
}
|
||||
if (/[A-Za-z_]/.test(c)) {
|
||||
let j = i + 1;
|
||||
while (j < n && /\w/.test(text[j])) j++;
|
||||
i = j; continue;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return { code: out.join(''), siruri };
|
||||
}
|
||||
|
||||
// Kotlin (0.4.0, 2026-10-18): comentariile bloc se imbrica; sirurile sunt "..." (un singur rand, cu escape-uri) si """...""" (brute,
|
||||
// fara escape-uri); amandoua au sabloane $nume si ${ expr }, iar expr poate contine siruri si acolade, deci sfarsitul se cauta cu o
|
||||
// stiva de cadre, iterativ. 'c' e un literal char ('a', '\n', 'A', '\''), nu deschide un sir. Continutul sirului ramane un singur
|
||||
// interval: un nume de API scris intr-un sablon nu e o folosire masurata.
|
||||
function sfarsitSirKotlin(text, start, n) {
|
||||
const stiva = []; // { fel: 'sir', brut } | { fel: 'sablon', ad }
|
||||
const deschide = (j) => {
|
||||
if (text[j] !== '"') return -1;
|
||||
const brut = text.startsWith('"""', j);
|
||||
stiva.push({ fel: 'sir', brut });
|
||||
return j + (brut ? 3 : 1);
|
||||
};
|
||||
let j = deschide(start);
|
||||
if (j < 0) return -1;
|
||||
while (j < n && stiva.length) {
|
||||
const cadru = stiva[stiva.length - 1];
|
||||
const c = text[j];
|
||||
if (cadru.fel === 'sir') {
|
||||
if (c === '\\' && !cadru.brut) { j += 2; continue; }
|
||||
if (c === '$' && text[j + 1] === '{') { stiva.push({ fel: 'sablon', ad: 1 }); j += 2; continue; }
|
||||
if (c === '"') {
|
||||
if (cadru.brut) {
|
||||
if (text.startsWith('"""', j)) { j += 3; while (text[j] === '"') j++; stiva.pop(); continue; } // """"" inchide si pastreaza ghilimelele in plus
|
||||
j++; continue;
|
||||
}
|
||||
stiva.pop(); j++; continue;
|
||||
}
|
||||
if (c === '\n' && !cadru.brut) { stiva.pop(); j++; continue; }
|
||||
j++; continue;
|
||||
}
|
||||
if (c === '{') { cadru.ad++; j++; continue; }
|
||||
if (c === '}') { if (--cadru.ad === 0) stiva.pop(); j++; continue; }
|
||||
if (c === '"') { const k = deschide(j); if (k >= 0) { j = k; continue; } }
|
||||
if (c === "'") { const k = sfarsitCharKotlin(text, j, n); if (k > 0) { j = k; continue; } }
|
||||
j++;
|
||||
}
|
||||
return Math.min(j, n);
|
||||
}
|
||||
|
||||
// literal char Kotlin la i: 'x', '\n', '\'', 'A', un caracter astral; -1 daca la i nu incepe un literal char
|
||||
function sfarsitCharKotlin(text, i, n) {
|
||||
const d = text[i + 1];
|
||||
if (d === undefined || d === '\n' || d === "'") return -1;
|
||||
if (d === '\\') {
|
||||
let j = i + 2;
|
||||
while (j < n && text[j] !== "'" && text[j] !== '\n' && j - i < 8) j++;
|
||||
return text[j] === "'" ? j + 1 : -1;
|
||||
}
|
||||
if (text[i + 2] === "'") return i + 3;
|
||||
const cod = d.charCodeAt(0);
|
||||
if (cod >= 0xd800 && cod <= 0xdbff && text[i + 3] === "'") return i + 4;
|
||||
return -1;
|
||||
}
|
||||
|
||||
function curataKotlin(text) {
|
||||
const n = text.length;
|
||||
const out = text.split('');
|
||||
const goleste = golitor(out);
|
||||
const siruri = [];
|
||||
let i = 0;
|
||||
while (i < n) {
|
||||
const c = text[i];
|
||||
const d = text[i + 1];
|
||||
if (c === d && d === '/') { // (scris altfel decat in lexerele C, Rust si Swift: fiecare ciot al controlului negativ are ancora lui)
|
||||
let j = i;
|
||||
while (j < n && text[j] !== '\n') j++;
|
||||
goleste(i, j); i = j; continue;
|
||||
}
|
||||
if (c === '/' && d === '*') {
|
||||
const jKt = sfarsitComentariuImbricat(text, i, n);
|
||||
goleste(i, jKt); i = jKt; continue;
|
||||
}
|
||||
if (c === '"') {
|
||||
const sf = sfarsitSirKotlin(text, i, n);
|
||||
if (sf > i) { siruri.push([i, sf]); i = sf; continue; }
|
||||
}
|
||||
if (c === "'") {
|
||||
const sf = sfarsitCharKotlin(text, i, n);
|
||||
if (sf > 0) { siruri.push([i, sf]); i = sf; continue; }
|
||||
i++; continue;
|
||||
}
|
||||
if (/[A-Za-z_]/.test(c)) {
|
||||
let j = i + 1;
|
||||
while (j < n && /\w/.test(text[j])) j++;
|
||||
i = j; continue;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return { code: out.join(''), siruri };
|
||||
}
|
||||
|
||||
function golitor(out) {
|
||||
return (a, b) => {
|
||||
for (let k = a; k < b; k++) if (out[k] !== '\n' && out[k] !== '\r') out[k] = ' ';
|
||||
@@ -218,13 +407,7 @@ function curataRust(text) {
|
||||
goleste(i, j); i = j; continue;
|
||||
}
|
||||
if (c === '/' && d === '*') {
|
||||
let j = i + 2;
|
||||
let ad = 1;
|
||||
while (j < n && ad > 0) {
|
||||
if (text[j] === '/' && text[j + 1] === '*') { ad++; j += 2; continue; }
|
||||
if (text[j] === '*' && text[j + 1] === '/') { ad--; j += 2; continue; }
|
||||
j++;
|
||||
}
|
||||
const j = sfarsitComentariuImbricat(text, i, n); // (0.4.0: aceeasi functie pentru Rust, Swift si Kotlin)
|
||||
goleste(i, j); i = j; continue;
|
||||
}
|
||||
const dupaCuvant = i > 0 && /\w/.test(text[i - 1]);
|
||||
|
||||
@@ -32,7 +32,30 @@ const MAVEN_GROUP = {
|
||||
'org.bouncycastle': 'Bouncy Castle: classical and post-quantum algorithms',
|
||||
'io.jsonwebtoken': 'JJWT: JWS HS*/RS*/ES*/PS*/EdDSA', 'com.nimbusds': 'Nimbus JOSE+JWT', 'com.auth0': 'java-jwt (if artifact is java-jwt)',
|
||||
'org.web3j': 'secp256k1 ECDSA accounts (web3j)', 'com.google.crypto.tink': 'Tink: AEAD, signatures, hybrid encryption', 'org.conscrypt': 'Conscrypt TLS provider',
|
||||
// 0.4.0 (2026-10-18, libsignal pentru Android/JVM si bibliotecile obisnuite ale unei aplicatii Android)
|
||||
'org.signal': 'libsignal: Curve25519 identity and prekeys (X3DH/PQXDH), Kyber prekeys, Double Ratchet, SPQR, sealed sender',
|
||||
'org.whispersystems': 'legacy Signal protocol libraries (Curve25519, Double Ratchet)',
|
||||
'org.mindrot': 'bcrypt password hashing (jbcrypt)', 'de.mkammerer': 'Argon2 password hashing (argon2-jvm)', 'com.lambdaworks': 'scrypt',
|
||||
'org.bitcoinj': 'secp256k1 ECDSA (bitcoinj)',
|
||||
};
|
||||
// Swift Package Manager (Package.swift) si CocoaPods (Podfile, *.podspec), 0.4.0: pachetele criptografice cunoscute, dupa calea depozitului
|
||||
// sau numele pachetului / pod-ului. Versiunea e CERINTA declarata (from:, exact:, '~> 1.8'), nu cea rezolvata din Package.resolved / Podfile.lock.
|
||||
const SWIFT_PKG = [
|
||||
[/(^|\/)apple\/swift-crypto$|^swift-crypto$|^Crypto$/i, 'swift-crypto: the CryptoKit API on every platform (AES-GCM, ChaChaPoly, SHA-2, HMAC, HKDF, P-256/384/521, Curve25519; RSA in _CryptoExtras)'],
|
||||
[/(^|\/)krzyzanowskim\/CryptoSwift$|^CryptoSwift$/i, 'CryptoSwift: AES, ChaCha20, Blowfish, RSA, SHA-2/3, MD5, SHA-1, HMAC, PBKDF2 (pure Swift)'],
|
||||
[/(^|\/)jedisct1\/swift-sodium$|^swift-sodium$|^Sodium$/i, 'swift-sodium (libsodium): X25519, Ed25519, XSalsa20/XChaCha20-Poly1305, Argon2, BLAKE2b'],
|
||||
[/(^|\/)signalapp\/libsignal(-client)?$|^LibSignalClient$/i, 'libsignal: Curve25519 identity and prekeys (X3DH/PQXDH), Kyber prekeys, Double Ratchet, SPQR, sealed sender'],
|
||||
[/(^|\/)apple\/swift-certificates$|^swift-certificates$|^X509$/i, 'X.509 certificates (swift-certificates)'],
|
||||
[/(^|\/)apple\/swift-nio-ssl$|^swift-nio-ssl$/i, 'TLS for SwiftNIO (BoringSSL)'],
|
||||
[/(^|\/)(GigaBitcoin\/secp256k1\.swift|21-DOT-DEV\/swift-secp256k1)$|^secp256k1(\.swift)?$/i, 'secp256k1 ECDSA/Schnorr'],
|
||||
[/(^|\/)(skywinder|web3swift-team)\/web3swift$|^web3swift$/i, 'secp256k1 ECDSA accounts and signatures (web3swift)'],
|
||||
[/(^|\/)airsidemobile\/JOSESwift$|^JOSESwift$/i, 'JWS/JWE (classical algorithms)'],
|
||||
[/(^|\/)TakeScoop\/SwiftyRSA$|^SwiftyRSA$/i, 'RSA'],
|
||||
[/(^|\/)datatheorem\/TrustKit$|^TrustKit$/i, 'certificate pinning (SPKI)'],
|
||||
[/(^|\/)krzyzanowskim\/OpenSSL$|^OpenSSL(-Universal)?$/i, 'OpenSSL'],
|
||||
[/(^|\/)tmthecoder\/Argon2Swift$|^Argon2Swift$/i, 'Argon2 password hashing'],
|
||||
];
|
||||
const swiftPachet = (cale, nume) => SWIFT_PKG.find(([re]) => (cale && re.test(cale)) || (nume && re.test(nume)));
|
||||
const GO = [
|
||||
[/^golang\.org\/x\/crypto$/, 'extended crypto: ssh, chacha20poly1305, curve25519, bcrypt, argon2'],
|
||||
[/^github\.com\/cloudflare\/circl$/, 'CIRCL: ML-KEM, ML-DSA, SLH-DSA, hybrid KEMs, classical curves'],
|
||||
@@ -61,18 +84,24 @@ const CARGO = [
|
||||
[/^(sodiumoxide|libsodium-sys|dryoc)$/, 'libsodium (NaCl): X25519, Ed25519, XSalsa20/XChaCha20-Poly1305, Argon2'],
|
||||
];
|
||||
|
||||
export const NUME_MANIFEST = /^(package\.json|requirements[\w.-]*\.txt|pyproject\.toml|pom\.xml|build\.gradle(\.kts)?|go\.mod|Cargo\.toml)$/;
|
||||
export const NUME_MANIFEST = /^(package\.json|requirements[\w.-]*\.txt|pyproject\.toml|pom\.xml|build\.gradle(\.kts)?|libs\.versions\.toml|go\.mod|Cargo\.toml|Package\.swift|Podfile|[\w.+-]+\.podspec)$/;
|
||||
|
||||
function lib(ecosistem, nume, versiune, ofera, pos, inceputuri, fisier) {
|
||||
const { line } = randul(inceputuri, pos);
|
||||
const purl = ecosistem === 'npm' ? `pkg:npm/${nume.startsWith('@') ? '%40' + nume.slice(1) : nume}${versiune && /^[\w.-]+$/.test(versiune) ? '@' + versiune : ''}`
|
||||
: ecosistem === 'pypi' ? `pkg:pypi/${nume}${versiune && /^[\w.-]+$/.test(versiune) ? '@' + versiune : ''}`
|
||||
: ecosistem === 'maven' ? `pkg:maven/${nume.replace(':', '/')}${versiune && /^[\w.-]+$/.test(versiune) ? '@' + versiune : ''}`
|
||||
: ecosistem === 'cargo' ? `pkg:cargo/${nume}${versiune && /^[\w.-]+$/.test(versiune) ? '@' + versiune : ''}`
|
||||
: `pkg:golang/${nume}${versiune ? '@' + versiune : ''}`;
|
||||
const v = versiune && /^[\w.-]+$/.test(versiune) ? '@' + versiune : '';
|
||||
const purl = ecosistem === 'npm' ? `pkg:npm/${nume.startsWith('@') ? '%40' + nume.slice(1) : nume}${v}`
|
||||
: ecosistem === 'pypi' ? `pkg:pypi/${nume}${v}`
|
||||
: ecosistem === 'maven' ? `pkg:maven/${nume.replace(':', '/')}${v}`
|
||||
: ecosistem === 'cargo' ? `pkg:cargo/${nume}${v}`
|
||||
: ecosistem === 'swift' ? `pkg:swift/${nume}${v}`
|
||||
: ecosistem === 'cocoapods' ? `pkg:cocoapods/${nume}${v}`
|
||||
: `pkg:golang/${nume}${versiune ? '@' + versiune : ''}`;
|
||||
return { file: fisier, line, ecosystem: ecosistem, name: nume, version: versiune || undefined, provides: ofera, purl };
|
||||
}
|
||||
|
||||
// versiunea dintr-o cerinta CocoaPods ('~> 1.8', '>= 2.0', '1.8.0')
|
||||
const versiunePod = (s) => (s ? s.replace(/^[~>=<\s]+/, '').trim() || undefined : undefined);
|
||||
|
||||
export function citesteManifest(text, numeFisier, rel) {
|
||||
const inceputuri = inceputuriDeRand(text);
|
||||
const r = [];
|
||||
@@ -128,11 +157,31 @@ export function citesteManifest(text, numeFisier, rel) {
|
||||
if (!ofera) continue;
|
||||
r.push(lib('maven', `${g[1]}:${a[1]}`, v && !/\$\{/.test(v[1]) ? v[1] : undefined, ofera, m.index + m[0].indexOf(a[0]), inceputuri, rel));
|
||||
}
|
||||
} else if (/^build\.gradle/.test(numeFisier)) {
|
||||
} else if (/^build\.gradle/.test(numeFisier) || numeFisier === 'libs.versions.toml') {
|
||||
// Groovy si Kotlin DSL ("group:artifact:version"), si catalogul de versiuni Gradle (module = "group:artifact", versiunea in alt camp)
|
||||
for (const m of text.matchAll(/["']([\w.-]+):([\w.-]+)(?::([\w.-]+))?["']/g)) {
|
||||
const ofera = MAVEN_GROUP[m[1]];
|
||||
if (ofera) r.push(lib('maven', `${m[1]}:${m[2]}`, m[3], ofera, m.index + 1, inceputuri, rel));
|
||||
}
|
||||
} else if (numeFisier === 'Package.swift') {
|
||||
// .package(url: "https://github.com/apple/swift-crypto.git", from: "3.0.0"), .package(url: ..., exact: / .upToNextMajor(from: / "1.0.0"..<),
|
||||
// .package(name: "LibSignalClient", path: "../..")
|
||||
for (const m of text.matchAll(/\.package\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)/g)) {
|
||||
const a = m[1];
|
||||
const url = /\burl\s*:\s*"([^"]+)"/.exec(a);
|
||||
const nume = /\bname\s*:\s*"([^"]+)"/.exec(a);
|
||||
const cale = url ? url[1].replace(/^[a-z]+:\/\//i, '').replace(/^git@([^:]+):/, '$1/').replace(/\.git$/, '').replace(/\/+$/, '') : null;
|
||||
const intrare = swiftPachet(cale, nume ? nume[1] : (cale ? cale.split('/').pop() : null));
|
||||
if (!intrare) continue;
|
||||
const v = /\b(?:from|exact)\s*:\s*"([^"]+)"/.exec(a) || /\.upToNext(?:Major|Minor)\s*\(\s*from\s*:\s*"([^"]+)"/.exec(a) || /"([^"]+)"\s*\.\.[.<]/.exec(a);
|
||||
r.push(lib('swift', cale || nume[1], v ? v[1] : undefined, intrare[1], m.index + m[0].indexOf(url ? url[0] : nume[0]), inceputuri, rel));
|
||||
}
|
||||
} else if (numeFisier === 'Podfile' || /\.podspec$/.test(numeFisier)) {
|
||||
// pod 'CryptoSwift', '~> 1.8' / s.dependency 'CryptoSwift', '~> 1.8'
|
||||
for (const m of text.matchAll(/(?:^|\s)(?:pod|\w+\.dependency)\s+['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?/g)) {
|
||||
const intrare = swiftPachet(null, m[1].split('/')[0]);
|
||||
if (intrare) r.push(lib('cocoapods', m[1].split('/')[0], versiunePod(m[2]), intrare[1], m.index + m[0].indexOf(m[1]), inceputuri, rel));
|
||||
}
|
||||
} else if (numeFisier === 'go.mod') {
|
||||
let pos = 0;
|
||||
let inRequire = false;
|
||||
|
||||
@@ -8,10 +8,12 @@ import { detecteazaPy } from './detect-py.mjs';
|
||||
import { detecteazaJava } from './detect-java.mjs';
|
||||
import { detecteazaGo } from './detect-go.mjs';
|
||||
import { detecteazaRust } from './detect-rust.mjs';
|
||||
import { detecteazaSwift } from './detect-swift.mjs';
|
||||
import { detecteazaKotlin } from './detect-kotlin.mjs';
|
||||
import { detecteazaPem } from './pem.mjs';
|
||||
import { citesteManifest, NUME_MANIFEST } from './manifeste.mjs';
|
||||
|
||||
export const VERSIUNE = '0.3.0';
|
||||
export const VERSIUNE = '0.4.0';
|
||||
export const DOSARE_EXCLUSE_IMPLICIT = ['.git', '.hg', '.svn', 'node_modules', '__pycache__', '.venv', 'venv', '.tox', '.gradle', '.idea', '.mypy_cache', '.pytest_cache', '.claude'];
|
||||
|
||||
const LIMBAJ = {
|
||||
@@ -21,8 +23,11 @@ const LIMBAJ = {
|
||||
'.java': 'java',
|
||||
'.go': 'go',
|
||||
'.rs': 'rust',
|
||||
// 0.4.0 (2026-10-18): Swift si Kotlin, dupa rularea pe libsignal (20,5% din randuri neanalizate); .kts e si manifest (build.gradle.kts)
|
||||
'.swift': 'swift',
|
||||
'.kt': 'kotlin', '.kts': 'kotlin',
|
||||
};
|
||||
const DETECTOR = { javascript: detecteazaJs, python: detecteazaPy, java: detecteazaJava, go: detecteazaGo, rust: detecteazaRust };
|
||||
const DETECTOR = { javascript: detecteazaJs, python: detecteazaPy, java: detecteazaJava, go: detecteazaGo, rust: detecteazaRust, swift: detecteazaSwift, kotlin: detecteazaKotlin };
|
||||
const EXEMPLE = 5;
|
||||
|
||||
export function limbajul(cale) {
|
||||
|
||||
Reference in new issue
Block a user