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
@@ -6,6 +6,7 @@
|
||||
// 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
|
||||
// P4 (0.4.0) comentariul bloc Swift neinchis reluat de la urmatorul caracter (fiecare `/*` rescaneaza pana la capat) -> swift-coment 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';
|
||||
@@ -62,6 +63,7 @@ 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']],
|
||||
['P4', 'lib/lexer.mjs', 'goleste(i, jSw); i = jSw; continue;', 'goleste(i, jSw); i = jSw < n ? jSw : i + 2; continue;', ['swift-coment.swift']],
|
||||
];
|
||||
for (const [id, fisier, ancora, cu, tinte] of P) {
|
||||
total++;
|
||||
|
||||
@@ -67,11 +67,92 @@ const MUTATII = [
|
||||
{
|
||||
nume: 'Cargo.toml scos din manifeste',
|
||||
fisier: 'lib/manifeste.mjs',
|
||||
ancora: '|go\\.mod|Cargo\\.toml)$/;',
|
||||
cu: '|go\\.mod)$/;',
|
||||
ancora: '|Cargo\\.toml|Package\\.swift|Podfile|',
|
||||
cu: '|Package\\.swift|Podfile|',
|
||||
tinta: 'pozitiv: manifestele dau biblioteci declarate, nu gasiri',
|
||||
martor: B,
|
||||
},
|
||||
// 0.4.0 (2026-10-18): Swift si Kotlin
|
||||
{
|
||||
nume: 'Package.swift, Podfile si podspec scoase din manifeste',
|
||||
fisier: 'lib/manifeste.mjs',
|
||||
ancora: '|Package\\.swift|Podfile|[\\w.+-]+\\.podspec)$/;',
|
||||
cu: ')$/;',
|
||||
tinta: 'manifeste: Package.swift, Podfile, podspec si build.gradle.kts dau versiunea ceruta si purl pkg:swift / pkg:cocoapods / pkg:maven',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'comentariile bloc Swift nu se mai imbrica (lexerul)',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: 'const jSw = sfarsitComentariuImbricat(text, i, n);',
|
||||
cu: "const jSw = (() => { const k = text.indexOf('*/', i + 2); return k < 0 ? n : k + 2; })();",
|
||||
tinta: 'negativ: comentariile imbricate, sirurile multi-rand, brute si interpolate Swift nu produc gasiri',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'API-ul libsignal Swift recunoscut fara ancora de import (orice IdentityKeyPair.generate devine libsignal)',
|
||||
fisier: 'lib/detect-swift.mjs',
|
||||
ancora: "const libsignal = are('LibSignalClient', 'SignalFfi') || inModulLibsignal;",
|
||||
cu: 'const libsignal = true;',
|
||||
tinta: 'negativ: numele API-ului libsignal si CryptoKit fara importurile lor nu produc gasiri (Swift), iar SecRandomCopyBytes nu e criptografie',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'importul CryptoKit ignorat (SHA256.hash recunoscut in orice fisier Swift)',
|
||||
fisier: 'lib/detect-swift.mjs',
|
||||
ancora: "if (are('CryptoKit', 'Crypto', '_CryptoExtras')) {",
|
||||
cu: 'if (true) {',
|
||||
tinta: 'negativ: numele API-ului libsignal si CryptoKit fara importurile lor nu produc gasiri (Swift), iar SecRandomCopyBytes nu e criptografie',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'KEMKeyPair.generate() din Swift citit ca cheie clasica (X25519), nu Kyber-1024',
|
||||
fisier: 'lib/detect-swift.mjs',
|
||||
ancora: "{ grup: 'PREPQ', nume: 'Kyber-1024', primitiv: 'kem', functii: ['keygen'], nota: NOTA_KEM_SWIFT }",
|
||||
cu: "{ grup: 'XDH', nume: 'X25519', functii: ['keygen'], nota: NOTA_KEM_SWIFT }",
|
||||
tinta: 'pozitiv: swift/libsignal.swift',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'constructorul Kotlin fara `new` ignorat (Aes256GcmSiv(key), PreKeyBundle(...), SealedSessionCipher(...) cer forma Java)',
|
||||
fisier: 'lib/detect-java.mjs',
|
||||
ancora: 'const ctor = kotlin ? ',
|
||||
cu: 'const ctor = false ? ',
|
||||
tinta: 'pozitiv: kotlin/Libsignal.kt',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'comentariile bloc Kotlin nu se mai imbrica (lexerul)',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: 'const jKt = sfarsitComentariuImbricat(text, i, n);',
|
||||
cu: "const jKt = (() => { const k = text.indexOf('*/', i + 2); return k < 0 ? n : k + 2; })();",
|
||||
tinta: 'negativ: comentariile imbricate, sirurile brute, sabloanele si literalele char Kotlin nu produc gasiri',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'acolada care inchide sablonul ${ } Kotlin ignorata (sirul inghite tot ce urmeaza)',
|
||||
fisier: 'lib/lexer.mjs',
|
||||
ancora: "if (c === '}') { if (--cadru.ad === 0) stiva.pop(); j++; continue; }",
|
||||
cu: "if (c === '}') { j++; continue; }",
|
||||
tinta: 'pozitiv: kotlin/Android.kt',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'KeyProperties.KEY_ALGORITHM_* netradus (Android Keystore iese unknown)',
|
||||
fisier: 'lib/detect-java.mjs',
|
||||
ancora: "const kp = v.fel === 'necunoscut' && /^KeyProperties",
|
||||
cu: "const kp = false && /^KeyProperties",
|
||||
tinta: 'kotlin: variabila rezolvata (val X = "...") poarta resolvedFrom, iar KeyProperties.KEY_ALGORITHM_* se traduce in numele JCA',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'verificarea lanturilor de certificate fara regula de clasificare (PKI-VERIFY cade pe "unknown")',
|
||||
fisier: 'lib/catalog.mjs',
|
||||
ancora: "if (g === 'PKI-VERIFY') {",
|
||||
cu: 'if (false) {',
|
||||
tinta: 'jvm si swift: verificarea lanturilor de certificate iese autentificare (signature, quantum-vulnerable), nu schimb de cheie',
|
||||
martor: B,
|
||||
},
|
||||
{
|
||||
nume: 'secp256k1 clasificat quantum-safe',
|
||||
fisier: 'lib/catalog.mjs',
|
||||
|
||||
@@ -45,21 +45,27 @@ try {
|
||||
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);
|
||||
// 0.3.0 (2026-10-18): Rust si Cargo.toml nu existau in 0.1.0, deci gasirile lor nu intra in echivalenta; se numara si se spun
|
||||
const rustN = b.findings.filter((g) => g.language === 'rust').length;
|
||||
const cargoN = b.libraries.filter((x) => x.ecosystem === 'cargo').length;
|
||||
b.findings = b.findings.filter((g) => g.language !== 'rust');
|
||||
b.libraries = b.libraries.filter((x) => x.ecosystem !== 'cargo');
|
||||
if (rustN || cargoN) console.log(` (in afara echivalentei: ${rustN} gasiri Rust, ${cargoN} biblioteci Cargo; 0.1.0 nu le stia)`);
|
||||
// 0.3.0 (2026-10-18): Rust si Cargo.toml nu existau in 0.1.0, deci gasirile lor nu intra in echivalenta; se numara si se spun.
|
||||
// 0.4.0 (2026-10-18): la fel Swift si Kotlin, manifestele Swift Package Manager / CocoaPods / libs.versions.toml, si grupurile Maven
|
||||
// adaugate atunci (org.signal, org.whispersystems, org.mindrot, de.mkammerer, com.lambdaworks, org.bitcoinj).
|
||||
const LIMBAJE_NOI = new Set(['rust', 'swift', 'kotlin']);
|
||||
const libNoua = (x) => x.ecosystem === 'cargo' || x.ecosystem === 'swift' || x.ecosystem === 'cocoapods' || /(^|\/)libs\.versions\.toml$/.test(x.file) || /^(org\.signal|org\.whispersystems|org\.mindrot|de\.mkammerer|com\.lambdaworks|org\.bitcoinj):/.test(x.name);
|
||||
const peLimbaj = {};
|
||||
for (const g of b.findings) if (LIMBAJE_NOI.has(g.language)) peLimbaj[g.language] = (peLimbaj[g.language] || 0) + 1;
|
||||
const libN = b.libraries.filter(libNoua).length;
|
||||
b.findings = b.findings.filter((g) => !LIMBAJE_NOI.has(g.language));
|
||||
b.libraries = b.libraries.filter((x) => !libNoua(x));
|
||||
if (Object.keys(peLimbaj).length || libN) console.log(` (in afara echivalentei: gasiri ${JSON.stringify(peLimbaj)}, ${libN} biblioteci Cargo/Swift/CocoaPods/grupuri Maven noi; 0.1.0 nu le stia)`);
|
||||
const ka = a.findings.map(norm), kb = b.findings.map(norm);
|
||||
const sa = new Set(ka), sb = new Set(kb);
|
||||
// 0.3.0 (2026-10-18, libsignal): detectoarele noi pe limbaje pe care 0.1.0 le STIA (API-ul libsignal in Java si Node) sunt adaugiri,
|
||||
// nu rescrieri: o gasire numai in versiunea noua, cu un API din lista de mai jos, se numara si se spune, nu e diferenta. O gasire
|
||||
// numai in 0.1.0 ramane intotdeauna diferenta: echivalenta pazeste ca rescrierea nu a PIERDUT nimic.
|
||||
const ADAUGIRI = /"api":"(?:(?:ECKeyPair|IdentityKeyPair|ECPrivateKey|PrivateKey|KEMKeyPair)\.generate|Curve\.generateKeyPair|HKDF\.deriveSecrets|new (?:Aes256GcmSiv|Aes256GcmEncryption|Aes256GcmDecryption|Aes256Ctr32|PreKeyBundle)|import org\.signal\.libsignal|hkdf|Aes256GcmSiv\.new|PreKeyBundle\.new|processPreKeyBundle|import @signalapp\/libsignal-client(?:\/[^"]*)?)"/;
|
||||
// 0.4.0: si regulile JVM adaugate pentru Kotlin, care se aplica si in Java (Android Keystore, Tink, OkHttp, PKIX, puntea libsignal).
|
||||
const ADAUGIRI = /"api":"(?:(?:ECKeyPair|IdentityKeyPair|ECPrivateKey|PrivateKey|KEMKeyPair)\.generate|Curve\.generateKeyPair|HKDF\.deriveSecrets|new (?:Aes256GcmSiv|Aes256GcmEncryption|Aes256GcmDecryption|Aes256Ctr32|PreKeyBundle|KEMPublicKey|SealedSessionCipher)|import org\.signal\.libsignal|hkdf|Aes256GcmSiv\.new|PreKeyBundle\.new|processPreKeyBundle|import @signalapp\/libsignal-client(?:\/[^"]*)?|Native\.\w+|KeyGenParameterSpec\.Builder|KeyTemplates\.get|\w+KeyTemplates\.\w+|Predefined\w+Parameters\.\w+|\w+Config\.register|import com\.google\.crypto\.tink|ConnectionSpec\.\w+|CertificatePinner\.Builder|(?:CertPathValidator|TrustManagerFactory)\.getInstance|KeyStore\.getInstance\("AndroidCAStore"\)|X509TrustManager|checkServerTrusted)"/;
|
||||
const doarV = ka.filter((x) => !sb.has(x)), doarN0 = kb.filter((x) => !sa.has(x));
|
||||
const adaugate = doarN0.filter((x) => ADAUGIRI.test(x)), doarN = doarN0.filter((x) => !ADAUGIRI.test(x));
|
||||
if (adaugate.length) console.log(` (in afara echivalentei: ${adaugate.length} gasiri ale detectoarelor adaugate dupa 0.1.0, API-ul libsignal Java/Node)`);
|
||||
if (adaugate.length) console.log(` (in afara echivalentei: ${adaugate.length} gasiri ale detectoarelor adaugate dupa 0.1.0, API-ul libsignal Java/Node si regulile JVM din 0.4.0)`);
|
||||
const ok = !doarV.length && !doarN.length && ka.length + adaugate.length === kb.length && JSON.stringify(a.libraries) === JSON.stringify(b.libraries);
|
||||
comparate += ka.length;
|
||||
if (!ok) dif++;
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Fixtura: JCA/JSSE din Kotlin (fara `new`, cu `val`), verificatorul PKIX al lui rustls-platform-verifier asa cum sta in clona libsignal
|
||||
// (java/android/src/main/java/org/rustls/platformverifier/CertificateVerifier.kt, randurile in dreptul formelor), Android Keystore
|
||||
// (developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.Builder), Tink (developers.google.com/tink, sabloanele
|
||||
// de chei) si OkHttp (square.github.io/okhttp/features/https: ConnectionSpec, TlsVersion, CipherSuite, CertificatePinner). Nu se compileaza.
|
||||
package fixturi
|
||||
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.KeyStore
|
||||
import java.security.MessageDigest
|
||||
import java.security.cert.CertPathValidator
|
||||
import java.security.cert.CertificateFactory
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.Mac
|
||||
import javax.net.ssl.SSLContext
|
||||
import javax.net.ssl.TrustManagerFactory
|
||||
import javax.net.ssl.X509TrustManager
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import com.google.crypto.tink.KeyTemplates
|
||||
import com.google.crypto.tink.KeysetHandle
|
||||
import com.google.crypto.tink.aead.AeadConfig
|
||||
import okhttp3.CertificatePinner
|
||||
import okhttp3.CipherSuite
|
||||
import okhttp3.ConnectionSpec
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.TlsVersion
|
||||
import org.bouncycastle.crypto.engines.RC4Engine // EXPECT: RC4 | weak-now
|
||||
|
||||
class Android {
|
||||
private val DIGEST = "SHA-256"
|
||||
|
||||
fun jca(algDinParametru: String, keystore: KeyStore) {
|
||||
val alias = "root_${keystore.size()}" // CertificateVerifier.kt:149: un sablon ${ } inaintea apelurilor (lexerul trebuie sa il inchida)
|
||||
val kpg = KeyPairGenerator.getInstance("RSA") // EXPECT: RSA-3072 | quantum-vulnerable
|
||||
kpg.initialize(3072)
|
||||
val ec = KeyPairGenerator.getInstance("EC") // EXPECT: EC-secp256r1 | quantum-vulnerable
|
||||
ec.initialize(ECGenParameterSpec("secp256r1"))
|
||||
val c1 = Cipher.getInstance("AES/GCM/NoPadding") // EXPECT: AES-GCM | quantum-safe
|
||||
val mac = Mac.getInstance("HmacSHA256") // EXPECT: HMAC-SHA-256 | quantum-safe
|
||||
val md = MessageDigest.getInstance(DIGEST) // EXPECT: SHA-256 | quantum-safe
|
||||
val md2 = MessageDigest.getInstance(algDinParametru) // EXPECT: MessageDigest.getInstance | unknown
|
||||
val tls = SSLContext.getInstance("TLSv1.2") // EXPECT: TLSv1.2 | quantum-vulnerable
|
||||
println(listOf(alias, c1, mac, md, md2, tls))
|
||||
}
|
||||
|
||||
// rustls-platform-verifier, CertificateVerifier.kt: lantul de incredere TLS al clientului (verificare de certificate, nu schimb de cheie)
|
||||
fun pkix(keystore: KeyStore?, principal: ByteArray) {
|
||||
val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) // :101; EXPECT: X.509 chain validation (PKIX) | quantum-vulnerable
|
||||
factory.init(keystore)
|
||||
for (manager in factory.trustManagers) {
|
||||
if (manager is X509TrustManager) { // :113; EXPECT: X.509 chain validation (PKIX) | quantum-vulnerable
|
||||
manager.checkServerTrusted(arrayOf(), "RSA") // :291; EXPECT: X.509 chain validation (PKIX) | quantum-vulnerable
|
||||
}
|
||||
}
|
||||
val certFactory: CertificateFactory = CertificateFactory.getInstance("X.509") // :198: parsare de certificate, nu verificare: nimic
|
||||
val systemKeystore = KeyStore.getInstance("AndroidCAStore") // :209; EXPECT: X.509 chain validation (PKIX) | quantum-vulnerable
|
||||
val validator = CertPathValidator.getInstance("PKIX") // :367; EXPECT: X.509 chain validation (PKIX) | quantum-vulnerable
|
||||
val digest = MessageDigest.getInstance("MD5").digest(principal) // :435: aliasul de sistem al unei radacini, nu securitate; unealta nu judeca intentia; EXPECT: MD5 | weak-now
|
||||
println(listOf(certFactory, systemKeystore, validator, digest))
|
||||
}
|
||||
|
||||
fun keystore() {
|
||||
val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore") // curba din Builder-ul de mai jos; EXPECT: EC-secp256r1 | quantum-vulnerable
|
||||
kpg.initialize(
|
||||
KeyGenParameterSpec.Builder("alias", KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY)
|
||||
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
|
||||
.setDigests(KeyProperties.DIGEST_SHA256)
|
||||
.build()
|
||||
)
|
||||
val rsa = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore") // marimea din variabila spec; EXPECT: RSA-2048 | quantum-vulnerable
|
||||
val spec = KeyGenParameterSpec.Builder("rsa", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
|
||||
.setKeySize(2048)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
|
||||
.build()
|
||||
rsa.initialize(spec)
|
||||
val kg = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") // EXPECT: AES-256-GCM | quantum-safe
|
||||
kg.init(KeyGenParameterSpec.Builder("aes", KeyProperties.PURPOSE_ENCRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setKeySize(256).build())
|
||||
val singur = KeyGenParameterSpec.Builder("hmac", KeyProperties.PURPOSE_SIGN).setKeySize(521).build() // fara generator in fisier: din marime; EXPECT: EC-secp521r1 | quantum-vulnerable
|
||||
println(singur)
|
||||
}
|
||||
|
||||
fun tink() {
|
||||
AeadConfig.register() // dovada slaba, suprimata de sabloanele de mai jos: nimic
|
||||
val aead = KeysetHandle.generateNew(KeyTemplates.get("AES256_GCM")) // EXPECT: AES-256-GCM | quantum-safe
|
||||
val sig = KeysetHandle.generateNew(KeyTemplates.get("ECDSA_P256")) // EXPECT: ECDSA-secp256r1 | quantum-vulnerable
|
||||
val hybrid = KeysetHandle.generateNew(KeyTemplates.get("DHKEM_X25519_HKDF_SHA256_HKDF_SHA256_AES_256_GCM")) // HPKE; EXPECT: X25519 | quantum-vulnerable
|
||||
val mac = KeysetHandle.generateNew(KeyTemplates.get("HMAC_SHA256_256BITTAG")) // EXPECT: HMAC-SHA-256 | quantum-safe
|
||||
val rsa = KeysetHandle.generateNew(KeyTemplates.get("RSA_SSA_PSS_3072_SHA256_F4")) // EXPECT: RSA-3072 | quantum-vulnerable
|
||||
println(listOf(aead, sig, hybrid, mac, rsa))
|
||||
}
|
||||
|
||||
fun okhttp(): OkHttpClient {
|
||||
val spec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) // EXPECT: TLS (negotiated, OkHttp MODERN_TLS) | unknown
|
||||
.tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_3) // EXPECT: TLSv1.2 | quantum-vulnerable ; TLSv1.3 | unknown
|
||||
.cipherSuites(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_AES_256_GCM_SHA384) // EXPECT: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 | quantum-vulnerable ; AES-256-GCM | quantum-safe
|
||||
.build()
|
||||
val pinner = CertificatePinner.Builder().add("example.com", "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=").build() // EXPECT: certificate pinning (SPKI) | quantum-vulnerable
|
||||
return OkHttpClient.Builder().connectionSpecs(listOf(spec)).certificatePinner(pinner).build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Fixtura: API-ul libsignal din Kotlin (org.signal.libsignal), 2026-10-18. Formele vin din clona signalapp/libsignal 1738ead8
|
||||
// (fisier:rand in dreptul lor); unde Kotlin-ul clonei are numai DEFINITIA, forma de apel e semnatura ei plus apelul Java corespunzator
|
||||
// din aceeasi clona (scris in dreptul randului). Fisierul nu se compileaza; e doar text pentru scaner. Ancora e importul
|
||||
// org.signal.libsignal.* (sau pachetul); fara ea, aceleasi nume nu inseamna libsignal (vezi negative/FaraLibsignal.kt).
|
||||
package fixturi
|
||||
|
||||
import org.signal.libsignal.protocol.IdentityKeyPair
|
||||
import org.signal.libsignal.protocol.ecc.ECKeyPair
|
||||
import org.signal.libsignal.protocol.ecc.ECPrivateKey
|
||||
import org.signal.libsignal.protocol.kem.KEMKeyPair
|
||||
import org.signal.libsignal.protocol.kem.KEMKeyType
|
||||
import org.signal.libsignal.protocol.kem.KEMPublicKey
|
||||
import org.signal.libsignal.protocol.kdf.HKDF
|
||||
import org.signal.libsignal.protocol.state.PreKeyBundle
|
||||
import org.signal.libsignal.metadata.SealedSessionCipher
|
||||
import org.signal.libsignal.crypto.Aes256GcmSiv
|
||||
import org.signal.libsignal.internal.Native
|
||||
|
||||
class Libsignal {
|
||||
fun exemple(key: ByteArray, ikm: ByteArray, info: ByteArray, bytes: ByteArray, tip: KEMKeyType, store: Any, aci: Any, e164: String) {
|
||||
var privateKey = ECPrivateKey.generate() // java/shared/.../protocol/ecc/ECKeyPair.kt:15; EXPECT: X25519 | quantum-vulnerable
|
||||
val pair = ECKeyPair(privateKey.getPublicKey(), privateKey) // ECKeyPair.kt:16: constructor din parti, NU o generare: nimic
|
||||
val pair2 = ECKeyPair.generate() // semnatura ECKeyPair.kt:14 + apelul Java `ECKeyPair.generate()` (x66 in clona); EXPECT: X25519 | quantum-vulnerable
|
||||
val id = IdentityKeyPair.generate() // apelul Java `IdentityKeyPair.generate()` (x9 in clona); EXPECT: X25519 | quantum-vulnerable
|
||||
val kem = KEMKeyPair.generate(KEMKeyType.KYBER_1024) // semnatura KEMKeyPair.kt:18 + apelul Java (x5); EXPECT: Kyber-1024 | quantum-safe
|
||||
val kem2 = KEMKeyPair.generate(tip) // tipul nu e pe rand: nu se ghiceste; EXPECT: libsignal KEM key pair | unknown
|
||||
val kemDinPunte = KEMKeyPair(Native.KyberKeyPair_Generate()) // KEMKeyPair.kt:20; EXPECT: Kyber-1024 | quantum-safe
|
||||
val remote = KEMPublicKey(bytes) // java/client/src/test/.../net/AuthKeysServiceTest.kt:66; EXPECT: Kyber-1024 | quantum-safe
|
||||
val okm = HKDF.deriveSecrets(ikm, info, 32) // semnatura HKDF.kt:10 + apelul Java (x7); EXPECT: HKDF | quantum-safe
|
||||
val okm2 = Native.HKDF_DeriveSecrets(32, ikm, info, null) // HKDF.kt:15; EXPECT: HKDF | quantum-safe
|
||||
val siv = Aes256GcmSiv(key) // Java `new Aes256GcmSiv(key)` (x3), in Kotlin fara new; EXPECT: AES-256-GCM-SIV | quantum-safe
|
||||
val bundle = PreKeyBundle(1, 1, 2, pair.publicKey, 3, pair.publicKey, ByteArray(64), id.publicKey, 4, kem.publicKey, ByteArray(64)) // constructorul PreKeyBundle.kt:26; EXPECT: libsignal session setup (X3DH/PQXDH) | unknown
|
||||
val sealed = SealedSessionCipher(store, aci, e164, 1) // Java `new SealedSessionCipher(store, aci, e164, deviceId)`; plicul e X25519 + HKDF; EXPECT: X25519 | quantum-vulnerable
|
||||
val deserializat = ECPrivateKey(bytes) // UnauthBackupsServiceTest.kt:61: deserializare, nu generare: nimic
|
||||
val semnatura = Native.ECPrivateKey_Sign(1L, info) // ECPrivateKey.kt:30 (calculateSignature): XEdDSA pe cheia Curve25519; EXPECT: XEdDSA (Curve25519) | quantum-vulnerable
|
||||
val acord = Native.ECPrivateKey_Agree(1L, 2L) // ECPrivateKey.kt:35 (calculateAgreement); EXPECT: X25519 | quantum-vulnerable
|
||||
val deschis = Native.ECPrivateKey_HpkeOpen(1L, bytes, info, info) // ECPrivateKey.kt:55 (open, HPKE RFC 9180 cu DHKEM X25519); EXPECT: X25519 | quantum-vulnerable
|
||||
println(listOf(pair, pair2, kem2, kemDinPunte, remote, okm, okm2, siv, bundle, sealed, deserializat, semnatura, acord, deschis))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'Exemplu'
|
||||
s.version = '1.0.0'
|
||||
s.dependency 'Sodium', '~> 0.9'
|
||||
s.dependency 'SwiftyJSON'
|
||||
end
|
||||
@@ -0,0 +1,18 @@
|
||||
// swift-tools-version:5.9
|
||||
// Fixtura: manifest Swift Package Manager. Formele sunt cele din clona libsignal (Package.swift si swift/Benchmarks/Package.swift:
|
||||
// .package(url:from:), .package(name:path:)) si din documentatia SwiftPM (.upToNextMajor(from:), exact:).
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Exemplu",
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-crypto.git", from: "3.0.0"),
|
||||
.package(url: "https://github.com/krzyzanowskim/CryptoSwift.git", .upToNextMajor(from: "1.8.0")),
|
||||
.package(url: "https://github.com/jedisct1/swift-sodium.git", exact: "0.9.1"),
|
||||
.package(name: "LibSignalClient", path: "../libsignal"),
|
||||
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.2.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(name: "Exemplu", dependencies: ["CryptoSwift"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,9 @@
|
||||
platform :ios, '15'
|
||||
use_frameworks!
|
||||
|
||||
target 'Exemplu' do
|
||||
pod 'CryptoSwift', '~> 1.8'
|
||||
pod 'LibSignalClient', path: '../libsignal'
|
||||
pod 'Alamofire', '~> 5.8'
|
||||
pod 'TrustKit'
|
||||
end
|
||||
@@ -0,0 +1,8 @@
|
||||
plugins { id("com.android.application") }
|
||||
dependencies {
|
||||
implementation("org.signal:libsignal-android:0.105.1")
|
||||
implementation("com.google.crypto.tink:tink-android:1.15.0")
|
||||
implementation("org.bouncycastle:bcprov-jdk18on:1.78.1")
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Fixtura negativa Kotlin: comentarii IMBRICATE, siruri obisnuite cu escape-uri, siruri brute """...""", sabloane ${ } cu apeluri si
|
||||
// siruri inauntru, literale char (inclusiv '"' si '\''): niciunul nu e o folosire si niciunul nu are voie sa deschida un sir peste
|
||||
// codul de dupa el. Numele JCA nu au nevoie de ancora, deci daca lexerul greseste, gasirea apare.
|
||||
package fixturi
|
||||
|
||||
/* import javax.crypto.Cipher
|
||||
/* val c = Cipher.getInstance("AES/ECB/PKCS5Padding") */
|
||||
val md = MessageDigest.getInstance("MD5")
|
||||
*/
|
||||
|
||||
/** KeyPairGenerator.getInstance("RSA") intr-un comentariu KDoc nu e o folosire. */
|
||||
class Comentarii {
|
||||
fun nimic(x: Int): String {
|
||||
val ghilimea = '"'
|
||||
val apostrof = '\''
|
||||
val unicode = 'A'
|
||||
val brut = """MessageDigest.getInstance("MD5") si Cipher.getInstance("DES") "ghilimele" """
|
||||
val sablon = "k=${listOf("MessageDigest.getInstance(\"SHA-1\")", "${x}").size} $x MessageDigest.getInstance(\"MD5\")"
|
||||
val text = "KeyPairGenerator.getInstance(\"RSA\") \\ CertPathValidator.getInstance(\"PKIX\")"
|
||||
val tm = "javax.net.ssl.X509TrustManager si TrustManagerFactory.getInstance(\"PKIX\")"
|
||||
return brut + sablon + text + tm + ghilimea + apostrof + unicode
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Fixtura negativa Kotlin: aceleasi nume scurte ca in API-ul libsignal (ECKeyPair.generate(), HKDF.deriveSecrets, Aes256GcmSiv(key)),
|
||||
// dar FARA importul org.signal.libsignal: nu sunt libsignal, deci nu produc nicio gasire. Nu se compileaza; e text pentru scaner.
|
||||
package fixturi
|
||||
|
||||
import com.exemplu.chei.ECKeyPair
|
||||
import com.exemplu.kdf.HKDF
|
||||
import com.exemplu.cifru.Aes256GcmSiv
|
||||
|
||||
class FaraLibsignal {
|
||||
fun exemple(key: ByteArray, ikm: ByteArray): Any {
|
||||
val ec = ECKeyPair.generate()
|
||||
val okm = HKDF.deriveSecrets(ikm, "info".toByteArray(), 32)
|
||||
println(listOf(ec, okm))
|
||||
return Aes256GcmSiv(key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Fixtura negativa Kotlin: SecureRandom singur (aleator, nu criptografie; forma din libsignal
|
||||
// java/shared/java/org/signal/libsignal/zkgroup/donation/DonationPermit.kt:122) si un tip X509Certificate purtat ca parametru,
|
||||
// fara nicio verificare de lant. Nicio gasire.
|
||||
package fixturi
|
||||
|
||||
import java.security.SecureRandom
|
||||
import java.security.cert.X509Certificate
|
||||
|
||||
class ZgomotSecureRandom {
|
||||
fun aleator(rng: SecureRandom = SecureRandom()): ByteArray {
|
||||
val b = ByteArray(32)
|
||||
rng.nextBytes(b)
|
||||
return b
|
||||
}
|
||||
|
||||
fun subiect(cert: X509Certificate): String = cert.subjectX500Principal.name
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Fixtura negativa Swift: comentarii IMBRICATE, siruri "..." cu interpolare \( ) (care contine la randul ei siruri), siruri multi-rand
|
||||
// """...""" si brute #"..."# / #"""..."""# care contin nume de API: niciunul nu e o folosire si niciunul nu are voie sa deschida un
|
||||
// sir peste codul de dupa el. Importul CryptoKit e aici dinadins: cu el, numele AR insemna ceva daca ar fi in cod.
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
/* let d = SHA256.hash(data: x)
|
||||
/* let k = Curve25519.KeyAgreement.PrivateKey() */
|
||||
let m = Insecure.MD5.hash(data: x)
|
||||
*/
|
||||
|
||||
/// `P256.Signing.PrivateKey()` intr-un comentariu de documentatie nu e o folosire.
|
||||
func nimic(_ x: Data) -> String {
|
||||
let interpolat = "digest \(x.count) SHA256.hash(data: x) \("Insecure.SHA1.hash(data: x)") \(x.isEmpty ? "a" : "b")"
|
||||
let multiRand = """
|
||||
AES.GCM.seal(data, using: key) "ghilimele simple inauntru"
|
||||
Curve25519.KeyAgreement.PrivateKey()
|
||||
"""
|
||||
let brut = #"HMAC<SHA256>.authenticationCode(for: "x", using: key) \#(x.count) \(nu e interpolare in sir brut)"#
|
||||
let brutMulti = #"""
|
||||
ChaChaPoly.seal(data, using: key) "quoted" """ inca nu s-a inchis
|
||||
"""#
|
||||
let gol = ""
|
||||
return interpolat + multiRand + brut + brutMulti + gol
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// Fixtura negativa Swift: Security importat pentru SecRandomCopyBytes (aleator, nu criptografie; forma din libsignal
|
||||
// swift/Sources/LibSignalClient/Utils.swift:258-267), si numele API-urilor libsignal si CryptoKit FARA importurile lor: un fisier
|
||||
// care nu importa modulul nu poate chema acel API, deci nu e o folosire. Nicio gasire.
|
||||
import Foundation
|
||||
#if canImport(Security)
|
||||
import Security
|
||||
#endif
|
||||
|
||||
func fillRandom(_ buffer: inout [UInt8]) throws {
|
||||
let result = SecRandomCopyBytes(kSecRandomDefault, buffer.count, &buffer)
|
||||
guard result == errSecSuccess else {
|
||||
throw NSError(domain: "SecRandomCopyBytes failed (error code \(result))", code: Int(result))
|
||||
}
|
||||
}
|
||||
|
||||
func faraImport() {
|
||||
let id = IdentityKeyPair.generate()
|
||||
let d = SHA256.hash(data: Data())
|
||||
let k = KEMKeyPair.generate()
|
||||
let s = try? Aes256GcmSiv(key: [UInt8]())
|
||||
_ = (id, d, k, s)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Fixtura: CryptoSwift (formele din README-ul github.com/krzyzanowskim/CryptoSwift: AES(key:blockMode:padding:), SHA2(variant:),
|
||||
// bytes.md5(), HMAC(key:variant:), PKCS5.PBKDF2(...), ChaCha20(key:iv:), Poly1305(key:),
|
||||
// RSA(keySize:), Blowfish(key:blockMode:padding:)) si swift-sodium (README-ul github.com/jedisct1/swift-sodium: sodium.box.keyPair(),
|
||||
// sodium.sign.keyPair(), sodium.secretBox.seal(message:secretKey:), sodium.aead.xchacha20poly1305ietf.encrypt(message:secretKey:),
|
||||
// sodium.pwHash.hash(...)) plus o functie C a libsodium (crypto_box_keypair, Clibsodium). Nu se compileaza; e text pentru scaner.
|
||||
// (Parametrul parolei se numeste `parola`: poarta de secrete a casei citeste eticheta engleza a parolei urmata de un tip drept o parola
|
||||
// atribuita in clar; eticheta ramane numai in apelul API-ului, unde valoarea e identificatorul `parola`.)
|
||||
import Foundation
|
||||
import CryptoSwift
|
||||
import Sodium
|
||||
import Clibsodium
|
||||
|
||||
func exemple(key: [UInt8], iv: [UInt8], input: [UInt8], parola: [UInt8], salt: [UInt8]) throws {
|
||||
let aes = try AES(key: key, blockMode: GCM(iv: iv, mode: .combined), padding: .noPadding) // EXPECT: AES-GCM | quantum-safe
|
||||
let cbc = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7) // EXPECT: AES-CBC | quantum-safe
|
||||
let ecb = try AES(key: key, blockMode: ECB()) // EXPECT: AES-ECB | weak-now
|
||||
let digest = SHA2(variant: .sha256).calculate(for: input) // EXPECT: SHA-256 | quantum-safe
|
||||
let md = input.md5() // EXPECT: MD5 | weak-now
|
||||
let mac = try HMAC(key: key, variant: .sha256).authenticate(input) // EXPECT: HMAC-SHA-256 | quantum-safe
|
||||
let dk = try PKCS5.PBKDF2(password: parola, salt: salt, iterations: 4096, keyLength: 32, variant: .sha256).calculate() // EXPECT: PBKDF2-HMAC-SHA256 | quantum-safe
|
||||
let chacha = try ChaCha20(key: key, iv: iv) // EXPECT: ChaCha20 | quantum-safe
|
||||
let poly = try Poly1305(key: key) // EXPECT: Poly1305 | quantum-safe
|
||||
let rsa = try RSA(keySize: 2048) // EXPECT: RSA-2048 | quantum-vulnerable
|
||||
let blowfish = try Blowfish(key: key, blockMode: CBC(iv: iv), padding: .pkcs7) // EXPECT: Blowfish | weak-now
|
||||
let sodium = Sodium()
|
||||
let box = sodium.box.keyPair() // EXPECT: X25519 | quantum-vulnerable
|
||||
let signer = sodium.sign.keyPair() // EXPECT: Ed25519 | quantum-vulnerable
|
||||
let sealed = sodium.secretBox.seal(message: input, secretKey: key) // EXPECT: XSalsa20-Poly1305 | quantum-safe
|
||||
let aead = sodium.aead.xchacha20poly1305ietf.encrypt(message: input, secretKey: key) // EXPECT: XChaCha20-Poly1305 | quantum-safe
|
||||
let pw = sodium.pwHash.hash(outputLength: 32, passwd: parola, salt: salt, opsLimit: 1, memLimit: 1) // EXPECT: Argon2id | quantum-safe
|
||||
var pk = [UInt8](repeating: 0, count: 32)
|
||||
var sk = [UInt8](repeating: 0, count: 32)
|
||||
let rc = crypto_box_keypair(&pk, &sk) // EXPECT: X25519 | quantum-vulnerable
|
||||
_ = (aes, cbc, ecb, digest, md, mac, dk, chacha, poly, rsa, blowfish, box, signer, sealed, aead, pw, rc)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Fixtura: CryptoKit (si swift-crypto, `import Crypto`, acelasi API). Formele sunt cele din documentatia Apple
|
||||
// (developer.apple.com/documentation/cryptokit: SHA256.hash(data:), Insecure.MD5, HMAC<SHA256>.authenticationCode(for:using:),
|
||||
// AES.GCM.seal(_:using:), ChaChaPoly.seal, Curve25519.KeyAgreement.PrivateKey(), P256.Signing.PrivateKey(),
|
||||
// HKDF<SHA256>.deriveKey(inputKeyMaterial:salt:info:outputByteCount:), SymmetricKey(size: .bits256)). Nu se compileaza; e text pentru scaner.
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
func exemple(data: Data, key: SymmetricKey, peer: Curve25519.KeyAgreement.PublicKey) throws {
|
||||
let digest = SHA256.hash(data: data) // EXPECT: SHA-256 | quantum-safe
|
||||
let d384 = SHA384.hash(data: data) // EXPECT: SHA-384 | quantum-safe
|
||||
var hasher = SHA512() // EXPECT: SHA-512 | quantum-safe
|
||||
let md5 = Insecure.MD5.hash(data: data) // EXPECT: MD5 | weak-now
|
||||
let sha1 = Insecure.SHA1.hash(data: data) // EXPECT: SHA-1 | weak-now
|
||||
let tag = HMAC<SHA256>.authenticationCode(for: data, using: key) // EXPECT: HMAC-SHA-256 | quantum-safe
|
||||
let sealed = try AES.GCM.seal(data, using: SymmetricKey(size: .bits256)) // marimea cheii de pe acelasi rand; EXPECT: AES-256-GCM | quantum-safe
|
||||
let opened = try AES.GCM.open(sealed, using: key) // EXPECT: AES-GCM | quantum-safe
|
||||
let cc = try ChaChaPoly.seal(data, using: key) // EXPECT: ChaCha20-Poly1305 | quantum-safe
|
||||
let x = Curve25519.KeyAgreement.PrivateKey() // EXPECT: X25519 | quantum-vulnerable
|
||||
let shared = try x.sharedSecretFromKeyAgreement(with: peer)
|
||||
let ed = Curve25519.Signing.PrivateKey() // EXPECT: Ed25519 | quantum-vulnerable
|
||||
let p256 = P256.Signing.PrivateKey() // EXPECT: ECDSA-secp256r1 | quantum-vulnerable
|
||||
let p384 = P384.KeyAgreement.PrivateKey() // EXPECT: ECDH-secp384r1 | quantum-vulnerable
|
||||
let p521 = P521.Signing.PrivateKey() // EXPECT: ECDSA-secp521r1 | quantum-vulnerable
|
||||
let derived = HKDF<SHA256>.deriveKey(inputKeyMaterial: key, salt: data, info: data, outputByteCount: 32) // EXPECT: HKDF | quantum-safe
|
||||
let k = SymmetricKey(size: .bits128) // singura pe rand: algoritmul se alege unde e folosita; EXPECT: SymmetricKey (128-bit) | unknown
|
||||
hasher.update(data: data)
|
||||
_ = (digest, d384, md5, sha1, tag, opened, cc, shared, ed, p256, p384, p521, derived, k)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Fixtura: un fisier care importa LibSignalClient fara niciun apel recunoscut: importul e dovada slaba (unknown), o singura data.
|
||||
// Cu un apel recunoscut in acelasi fisier, importul nu se mai raporteaza (vezi swift/libsignal.swift, care nu are marcaj pe import).
|
||||
import Foundation
|
||||
import LibSignalClient // EXPECT: libsignal (LibSignalClient) | unknown
|
||||
|
||||
func store() -> InMemorySignalProtocolStore {
|
||||
return InMemorySignalProtocolStore()
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Fixtura: API-ul Swift al libsignal (LibSignalClient), 2026-10-18. FIECARE forma e luata din clona signalapp/libsignal 1738ead8
|
||||
// (fisier:rand scris in dreptul ei; fisierul nu se compileaza, e doar text pentru scaner). Ancora e `import LibSignalClient`
|
||||
// (sau `@testable import LibSignalClient`; in sursele bibliotecii insesi, `import SignalFfi`). Fara ancora, aceleasi nume nu
|
||||
// inseamna nimic (vezi negative/zgomot-securitate.swift).
|
||||
import Foundation
|
||||
import LibSignalClient
|
||||
|
||||
func exemple(key: [UInt8], nonce: [UInt8], ad: [UInt8], ptext: [UInt8], accountEntropy: String, bytes: [UInt8]) throws {
|
||||
let bob_pre_key = PrivateKey.generate() // swift/Tests/LibSignalClientTests/SessionTests.swift:145; EXPECT: X25519 | quantum-vulnerable
|
||||
let bob_identity = IdentityKeyPair.generate() // swift/Sources/LibSignalClient/DataStoreInMemory.swift:33; EXPECT: X25519 | quantum-vulnerable
|
||||
let bob_kyber_pre_key = KEMKeyPair.generate() // SessionTests.swift:147; puntea genereaza kem::KeyType::Kyber1024; EXPECT: Kyber-1024 | quantum-safe
|
||||
let kyberPreKey = KEMKeyPair.generate().publicKey // PublicAPITests.swift:506; EXPECT: Kyber-1024 | quantum-safe
|
||||
let remoteKem = try KEMPublicKey(bytes) // ChatServices/UnauthKeysServiceTests.swift:67; EXPECT: Kyber-1024 | quantum-safe
|
||||
let gcm_siv = try Aes256GcmSiv(key: key) // CryptoTests.swift:62; EXPECT: AES-256-GCM-SIV | quantum-safe
|
||||
let encryptedParts = try Aes256GcmEncryptedData.encrypt(Data(ptext), key: key) // CryptoTests.swift:79; EXPECT: AES-256-GCM | quantum-safe
|
||||
let splitParts = try Aes256GcmEncryptedData(concatenated: encryptedParts.concatenate()) // CryptoTests.swift:86; EXPECT: AES-256-GCM | quantum-safe
|
||||
let gcmEnc = try Aes256GcmEncryption(key: key, nonce: nonce, associatedData: ad) // CryptoTests.swift:131; EXPECT: AES-256-GCM | quantum-safe
|
||||
let gcmDec = try Aes256GcmDecryption(key: key, nonce: nonce, associatedData: ad) // CryptoTests.swift:138; EXPECT: AES-256-GCM | quantum-safe
|
||||
var message = Data(ptext)
|
||||
try Aes256Ctr32(key: key, nonce: nonce).process(&message) // swift/Sources/LibSignalClient/Aes256Ctr.swift:87; EXPECT: AES-256-CTR | quantum-safe
|
||||
try Aes256Ctr32.process(&message, key: key, nonce: nonce) // CryptoTests.swift:169 (forma statica); EXPECT: AES-256-CTR | quantum-safe
|
||||
var nonceCtr = Array(repeating: UInt8(0), count: Aes256Ctr32.nonceLength) // CryptoTests.swift:163: o constanta a tipului, nu un apel: nimic
|
||||
let backupKey = try hkdf( // MessageBackupTests.swift:225; EXPECT: HKDF | quantum-safe
|
||||
outputLength: 32,
|
||||
inputKeyMaterial: Array(accountEntropy.utf8),
|
||||
salt: [],
|
||||
info: Array("20240801_SIGNAL_BACKUP_KEY".utf8)
|
||||
)
|
||||
let bob_bundle = try PreKeyBundle( // SessionTests.swift:165; EXPECT: libsignal session setup (X3DH/PQXDH) | unknown
|
||||
registrationId: 1,
|
||||
deviceId: 9,
|
||||
prekeyId: 4570,
|
||||
prekey: bob_pre_key.publicKey,
|
||||
signedPrekeyId: 3006,
|
||||
signedPrekey: bob_pre_key.publicKey,
|
||||
signedPrekeySignature: Data(),
|
||||
identity: bob_identity.identityKey,
|
||||
kyberPrekeyId: 8888,
|
||||
kyberPrekey: bob_kyber_pre_key.publicKey,
|
||||
kyberPrekeySignature: Data()
|
||||
)
|
||||
try processPreKeyBundle( // SessionTests.swift:180; EXPECT: libsignal session setup (X3DH/PQXDH) | unknown
|
||||
bob_bundle,
|
||||
for: bob_address,
|
||||
ourAddress: alice_address,
|
||||
sessionStore: alice_store,
|
||||
identityStore: alice_store,
|
||||
now: Date(),
|
||||
context: NullContext()
|
||||
)
|
||||
_ = (kyberPreKey, remoteKem, gcm_siv, splitParts, gcmEnc, gcmDec, backupKey)
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Fixtura: CommonCrypto, Security.framework si TLS-ul clientului (URLSession, Network). Formele sunt cele din documentatia Apple:
|
||||
// CC_SHA256 / CCCrypt / CCHmac / CCKeyDerivationPBKDF (CommonCrypto.h), SecKeyCreateRandomKey cu kSecAttrKeyType si kSecAttrKeySizeInBits
|
||||
// (developer.apple.com/documentation/security/generating-new-cryptographic-keys), SecKeyCreateSignature / SecKeyVerifySignature /
|
||||
// SecKeyCreateEncryptedData cu SecKeyAlgorithm, SecTrustEvaluateWithError, URLSessionConfiguration.tlsMinimumSupportedProtocolVersion,
|
||||
// NWProtocolTLS.Options + sec_protocol_options_set_min_tls_protocol_version. Nu se compileaza; e text pentru scaner.
|
||||
import Foundation
|
||||
import CommonCrypto
|
||||
import Security
|
||||
import Network
|
||||
|
||||
func exemple(data: Data, keyData: Data, password: String, salt: Data, trust: SecTrust, privateKey: SecKey, publicKey: SecKey) throws {
|
||||
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
|
||||
data.withUnsafeBytes { _ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash) } // EXPECT: SHA-256 | quantum-safe
|
||||
_ = CC_MD5(nil, 0, &hash) // EXPECT: MD5 | weak-now
|
||||
_ = CC_SHA1(nil, 0, &hash) // EXPECT: SHA-1 | weak-now
|
||||
let status = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), CCOptions(kCCOptionPKCS7Padding), keyBytes, kCCKeySizeAES256, iv, dataBytes, data.count, outBytes, outLength, &moved) // EXPECT: AES-256-CBC | quantum-safe
|
||||
let s3des = CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithm3DES), CCOptions(kCCOptionECBMode), keyBytes, kCCKeySize3DES, nil, dataBytes, data.count, outBytes, outLength, &moved) // EXPECT: 3DES-ECB | weak-now
|
||||
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyBytes, keyData.count, dataBytes, data.count, &hash) // EXPECT: HMAC-SHA-256 | quantum-safe
|
||||
let r = CCKeyDerivationPBKDF(CCPBKDFAlgorithm(kCCPBKDF2), password, password.utf8.count, saltBytes, salt.count, CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1), 10000, derived, 32) // EXPECT: PBKDF2-HMAC-SHA1 | weak-now
|
||||
|
||||
let attributes: [String: Any] = [
|
||||
kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
|
||||
kSecAttrKeySizeInBits as String: 256,
|
||||
]
|
||||
var error: Unmanaged<CFError>?
|
||||
let ecKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) // dictionarul e variabila de mai sus; EXPECT: EC-secp256r1 | quantum-vulnerable
|
||||
let rsaKey = SecKeyCreateRandomKey([kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: 2048] as CFDictionary, &error) // EXPECT: RSA-2048 | quantum-vulnerable
|
||||
let sig = SecKeyCreateSignature(privateKey, .ecdsaSignatureMessageX962SHA256, data as CFData, &error) // EXPECT: ECDSA | quantum-vulnerable
|
||||
let sig2 = SecKeyCreateSignature(privateKey, .rsaSignatureMessagePSSSHA256, data as CFData, &error) // EXPECT: RSA | quantum-vulnerable
|
||||
let ok = SecKeyVerifySignature(publicKey, .rsaSignatureMessagePKCS1v15SHA1, data as CFData, sig!, &error) // EXPECT: RSA | weak-now
|
||||
let ct = SecKeyCreateEncryptedData(publicKey, .rsaEncryptionOAEPSHA256, data as CFData, &error) // EXPECT: RSA | quantum-vulnerable
|
||||
let trusted = SecTrustEvaluateWithError(trust, &error) // lantul de incredere TLS: autentificare, nu schimb de cheie; EXPECT: X.509 chain validation (PKIX) | quantum-vulnerable
|
||||
|
||||
let config = URLSessionConfiguration.default
|
||||
config.tlsMinimumSupportedProtocolVersion = .TLSv12 // EXPECT: TLSv1.2 | quantum-vulnerable
|
||||
config.tlsMaximumSupportedProtocolVersion = .TLSv13 // EXPECT: TLSv1.3 | unknown
|
||||
let tls = NWProtocolTLS.Options() // EXPECT: TLS (negotiated) | unknown
|
||||
sec_protocol_options_set_min_tls_protocol_version(tls.securityProtocolOptions, .TLSv13) // EXPECT: TLSv1.3 | unknown
|
||||
_ = (status, s3des, r, ecKey, rsaKey, sig2, ok, ct, trusted, config)
|
||||
}
|
||||
@@ -16,7 +16,7 @@ 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)
|
||||
// unitatea se repeta pana la marime; forma lista e [unitate, kb1, kb2, prefix?] (prefixul se pune o singura data, inaintea repetarii)
|
||||
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],
|
||||
@@ -27,11 +27,21 @@ export const CAZURI = {
|
||||
'js-func.js': 'crypto.createHash(q)\nfunction (',
|
||||
'java-linie.java': 'Cipher.getInstance(x)+',
|
||||
'java-kpg.java': 'k = KeyPairGenerator.getInstance("EC")+',
|
||||
// 0.4.0 (2026-10-18), Swift si Kotlin: zeci de mii de comentarii imbricate deschise si neinchise; o interpolare / un sablon care se
|
||||
// deschide la nesfarsit (fiecare `"\(` deschide un sir si o interpolare: 85.000 de niveluri la 256 KB, deci scanarea trebuie sa fie
|
||||
// iterativa); un singur sir de un megaoctet neinchis (" si """)
|
||||
'swift-coment.swift': '/* ',
|
||||
'swift-interp.swift': '"\\(',
|
||||
'swift-sir-lung.swift': ['a', 256, 1024, '"'],
|
||||
'kt-sablon.kt': '"${',
|
||||
'kt-brut-lung.kt': ['a', 256, 1024, '"""'],
|
||||
};
|
||||
|
||||
const marimi = (nume) => (Array.isArray(CAZURI[nume]) ? CAZURI[nume].slice(1) : [64, 256]);
|
||||
const marimi = (nume) => (Array.isArray(CAZURI[nume]) ? CAZURI[nume].slice(1, 3) : [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 prefixul = (nume) => (Array.isArray(CAZURI[nume]) ? CAZURI[nume][3] || '' : '');
|
||||
// prefixul intra in marime: la 1024 KB fisierul nu are voie sa treaca de maxFileBytes (1048576), altfel e sarit ca prea mare si proba e STRICATA
|
||||
const genereaza = (unit, kb, prefix = '') => prefix + unit.repeat(Math.max(1, Math.floor((kb * 1024 - prefix.length) / unit.length)));
|
||||
|
||||
const arg = (f) => { const i = process.argv.indexOf(f); return i >= 0 ? process.argv[i + 1] : null; };
|
||||
|
||||
@@ -41,7 +51,7 @@ if (arg('--caz')) {
|
||||
const inv = await import(pathToFileURL(CALE_MODUL).href);
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-timp-'));
|
||||
try {
|
||||
writeFileSync(join(d, nume), genereaza(unitate(nume), kb));
|
||||
writeFileSync(join(d, nume), genereaza(unitate(nume), kb, prefixul(nume)));
|
||||
const t0 = process.hrtime.bigint();
|
||||
const rez = inv.scan(d);
|
||||
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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 { readFileSync, readdirSync, statSync, existsSync, mkdtempSync, mkdirSync, 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';
|
||||
@@ -18,8 +18,12 @@ const lx = await import(pathToFileURL(join(dirname(CALE_MODUL), 'lib', 'lexer.mj
|
||||
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 = 158;
|
||||
const FISIERE_CU_MARCAJE = ['js/node-crypto.mjs', 'js/webcrypto.js', 'js/biblioteci.ts', 'js/tls.cjs', 'js/libsignal-client.ts', 'js/libsignal-client-import.ts', 'python/crypto_py.py', 'java/Crypto.java', 'java/Libsignal.java', 'java/LibsignalImport.java', 'go/crypto.go', 'rust/cripto.rs', 'rust/ambiguu.rs', 'rust/glob.rs', 'rust/libsignal.rs', 'negative/variabile.js'];
|
||||
// (0.4.0, 2026-10-18: 158 + 111 din fixturile Swift si Kotlin, numarate de compara-fixturi inainte de a fi scrise aici)
|
||||
const MARCAJE_ASTEPTATE = 269;
|
||||
const FISIERE_CU_MARCAJE = ['js/node-crypto.mjs', 'js/webcrypto.js', 'js/biblioteci.ts', 'js/tls.cjs', 'js/libsignal-client.ts', 'js/libsignal-client-import.ts', 'python/crypto_py.py', 'java/Crypto.java', 'java/Libsignal.java', 'java/LibsignalImport.java', 'go/crypto.go', 'rust/cripto.rs', 'rust/ambiguu.rs', 'rust/glob.rs', 'rust/libsignal.rs', 'negative/variabile.js',
|
||||
'swift/libsignal.swift', 'swift/libsignal-import.swift', 'swift/cryptokit.swift', 'swift/securitate.swift', 'swift/biblioteci.swift', 'kotlin/Libsignal.kt', 'kotlin/Android.kt'];
|
||||
// fixturile negative: fiecare fisier de aici e un fisier de cod citit si analizat, cu zero gasiri (in afara de variabile.js, care are marcaje)
|
||||
const FISIERE_NEGATIVE = 15;
|
||||
|
||||
const probe = [];
|
||||
const proba = (nume, fn) => probe.push({ nume, fn });
|
||||
@@ -91,11 +95,28 @@ proba('pozitiv: manifestele dau biblioteci declarate, nu gasiri', () => {
|
||||
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', 'Cargo.toml:7 sha2', 'Cargo.toml:8 ed25519-dalek', 'Cargo.toml:9 rustls',
|
||||
'Cargo.toml:11 aes-gcm', 'Cargo.toml:12 pqcrypto-mlkem', 'Cargo.toml:15 ml-dsa', 'Cargo.toml:21 argon2'].sort();
|
||||
'Cargo.toml:11 aes-gcm', 'Cargo.toml:12 pqcrypto-mlkem', 'Cargo.toml:15 ml-dsa', 'Cargo.toml:21 argon2',
|
||||
// 0.4.0: Swift Package Manager, CocoaPods (Podfile si podspec), Gradle Kotlin DSL
|
||||
'Package.swift:9 github.com/apple/swift-crypto', 'Package.swift:10 github.com/krzyzanowskim/CryptoSwift', 'Package.swift:11 github.com/jedisct1/swift-sodium',
|
||||
'Package.swift:12 LibSignalClient', 'Podfile:5 CryptoSwift', 'Podfile:6 LibSignalClient', 'Podfile:8 TrustKit', 'Exemplu.podspec:4 Sodium',
|
||||
'build.gradle.kts:3 org.signal:libsignal-android', 'build.gradle.kts:4 com.google.crypto.tink:tink-android', 'build.gradle.kts:5 org.bouncycastle:bcprov-jdk18on'].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 === 15 && c.every((x) => x.properties.some((p) => p.name.endsWith('declared-only') && p.value === 'true')), 'componentele library nu poarta declared-only');
|
||||
// 26 de biblioteci declarate, 25 de componente: bcprov-jdk18on 1.78.1 e declarat si in pom.xml si in build.gradle.kts (acelasi purl)
|
||||
asigura(c.length === 25 && c.every((x) => x.properties.some((p) => p.name.endsWith('declared-only') && p.value === 'true')), `componentele library: ${c.length}, sau nu poarta declared-only`);
|
||||
});
|
||||
|
||||
proba('manifeste: Package.swift, Podfile, podspec si build.gradle.kts dau versiunea ceruta si purl pkg:swift / pkg:cocoapods / pkg:maven', () => {
|
||||
const libs = scan(join(FIX, 'manifeste')).libraries;
|
||||
const l = (f, n) => libs.find((b) => b.file === f && b.name === n);
|
||||
asigura(l('Package.swift', 'github.com/apple/swift-crypto').purl === 'pkg:swift/github.com/apple/[email protected]', `from: ${JSON.stringify(l('Package.swift', 'github.com/apple/swift-crypto'))}`);
|
||||
asigura(l('Package.swift', 'github.com/krzyzanowskim/CryptoSwift').version === '1.8.0' && l('Package.swift', 'github.com/jedisct1/swift-sodium').version === '0.9.1', 'upToNextMajor / exact');
|
||||
asigura(l('Package.swift', 'LibSignalClient').version === undefined && l('Package.swift', 'LibSignalClient').purl === 'pkg:swift/LibSignalClient', 'pachetul local, fara versiune');
|
||||
asigura(!libs.some((b) => /argument-parser|Alamofire|SwiftyJSON|okhttp|junit/.test(b.name)), 'pachetele fara criptografie nu sunt biblioteci declarate');
|
||||
asigura(l('Podfile', 'CryptoSwift').purl === 'pkg:cocoapods/[email protected]' && l('Podfile', 'TrustKit').version === undefined, `Podfile: ${JSON.stringify([l('Podfile', 'CryptoSwift'), l('Podfile', 'TrustKit')])}`);
|
||||
asigura(l('Exemplu.podspec', 'Sodium').purl === 'pkg:cocoapods/[email protected]', `podspec: ${JSON.stringify(l('Exemplu.podspec', 'Sodium'))}`);
|
||||
asigura(l('build.gradle.kts', 'org.signal:libsignal-android').purl === 'pkg:maven/org.signal/[email protected]', `gradle kts: ${JSON.stringify(l('build.gradle.kts', 'org.signal:libsignal-android'))}`);
|
||||
});
|
||||
|
||||
proba('pozitiv: material PEM (certificat si cheie publica)', () => {
|
||||
@@ -254,11 +275,115 @@ proba('rust: Cargo.toml: forma tabel, workspace = true fara versiune, redenumire
|
||||
|
||||
proba('negativ: fisier fara criptografie da zero gasiri, si a fost citit', () => {
|
||||
const rez = scan(join(FIX, 'negative'));
|
||||
asigura(rez.stats.filesSeen === 10 && rez.stats.codeFilesTotal === 10, `vazute ${rez.stats.filesSeen}, analizate ${rez.stats.codeFilesTotal}`);
|
||||
asigura(rez.stats.filesSeen === FISIERE_NEGATIVE && rez.stats.codeFilesTotal === FISIERE_NEGATIVE, `vazute ${rez.stats.filesSeen}, analizate ${rez.stats.codeFilesTotal} (asteptate ${FISIERE_NEGATIVE})`);
|
||||
const g = gasiriDin(rez, 'fara-cripto.js');
|
||||
asigura(g.length === 0, `fara-cripto.js a produs ${g.length}`);
|
||||
});
|
||||
|
||||
// --- Swift si Kotlin (0.4.0, 2026-10-18, dupa rularea pe libsignal) ---
|
||||
proba('negativ: comentariile imbricate, sirurile multi-rand, brute si interpolate Swift nu produc gasiri', () => {
|
||||
const rez = scan(FIX);
|
||||
asigura(gasiriDin(rez, 'swift/cryptokit.swift').some((x) => x.name === 'MD5'), 'controlul pozitiv: Insecure.MD5 din fixtura CryptoKit lipseste');
|
||||
const g = gasiriDin(rez, 'negative/comentarii.swift');
|
||||
asigura(g.length === 0, `au produs: ${g.map((x) => `${x.line} ${x.name}`).join(', ')}`);
|
||||
});
|
||||
|
||||
proba('negativ: numele API-ului libsignal si CryptoKit fara importurile lor nu produc gasiri (Swift), iar SecRandomCopyBytes nu e criptografie', () => {
|
||||
const rez = scan(FIX);
|
||||
asigura(gasiriDin(rez, 'swift/libsignal.swift').some((x) => x.name === 'Kyber-1024') && gasiriDin(rez, 'swift/cryptokit.swift').some((x) => x.name === 'SHA-256'), 'controlul pozitiv: Kyber-1024 / SHA-256 din fixturile Swift lipsesc');
|
||||
const g = gasiriDin(rez, 'negative/zgomot-securitate.swift');
|
||||
asigura(g.length === 0, `au produs: ${g.map((x) => `${x.line} ${x.name}`).join(', ')}`);
|
||||
// ancorele din sursele bibliotecii: `import SignalFfi` (fara import LibSignalClient) si dosarul tintei SwiftPM (Sources/LibSignalClient/,
|
||||
// DataStoreInMemory.swift importa doar Foundation) fac numele libsignal, fara dovada slaba de import; acelasi fisier in alt dosar: nimic
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-swift-ffi-'));
|
||||
try {
|
||||
// (variabilele se numesc `cheie` / `identitate`, nu privateKey: poarta de secrete a casei citeste `privateKey = ...` din acest text drept o cheie atribuita)
|
||||
writeFileSync(join(d, 'IdentityKey.swift'), 'import Foundation\nimport SignalFfi\n\nextension IdentityKeyPair {\n public static func generate() -> IdentityKeyPair {\n let cheie = PrivateKey.generate()\n return IdentityKeyPair(publicKey: cheie.publicKey, privateKey: cheie)\n }\n}\n');
|
||||
const store = 'import Foundation\n\npublic class InMemorySignalProtocolStore {\n private var identitate: IdentityKeyPair\n public init() {\n self.identitate = IdentityKeyPair.generate()\n }\n}\n';
|
||||
mkdirSync(join(d, 'Sources', 'LibSignalClient'), { recursive: true });
|
||||
writeFileSync(join(d, 'Sources', 'LibSignalClient', 'DataStoreInMemory.swift'), store);
|
||||
writeFileSync(join(d, 'DataStoreInMemory.swift'), store);
|
||||
const r = inv.scan(d);
|
||||
const f = r.findings.map((x) => `${x.file}:${x.line} ${x.name}`).sort();
|
||||
asigura(JSON.stringify(f) === JSON.stringify(['IdentityKey.swift:6 X25519', 'Sources/LibSignalClient/DataStoreInMemory.swift:6 X25519']), `ancorele SignalFfi / dosarul modulului: ${JSON.stringify(f)}`);
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
proba('negativ: comentariile imbricate, sirurile brute, sabloanele si literalele char Kotlin nu produc gasiri', () => {
|
||||
const rez = scan(FIX);
|
||||
asigura(gasiriDin(rez, 'kotlin/Android.kt').some((x) => x.name === 'MD5'), 'controlul pozitiv: MD5 din fixtura Kotlin lipseste');
|
||||
const g = gasiriDin(rez, 'negative/Comentarii.kt');
|
||||
asigura(g.length === 0, `au produs: ${g.map((x) => `${x.line} ${x.name}`).join(', ')}`);
|
||||
});
|
||||
|
||||
proba('negativ: numele API-ului libsignal fara importul lui nu produc gasiri (Kotlin), iar SecureRandom singur nu e criptografie', () => {
|
||||
const rez = scan(FIX);
|
||||
asigura(gasiriDin(rez, 'kotlin/Libsignal.kt').some((x) => x.name === 'Kyber-1024' && x.api === 'KEMKeyPair.generate'), 'controlul pozitiv: Kyber-1024 din fixtura Kotlin libsignal lipseste');
|
||||
const g = [...gasiriDin(rez, 'negative/FaraLibsignal.kt'), ...gasiriDin(rez, 'negative/ZgomotSecureRandom.kt')];
|
||||
asigura(g.length === 0, `au produs: ${g.map((x) => `${x.file}:${x.line} ${x.name}`).join(', ')}`);
|
||||
// ancora de pachet, ca in Java: un fisier din chiar arborele libsignal (package org.signal.libsignal...), fara import
|
||||
const d = mkdtempSync(join(tmpdir(), 'ci-kotlin-libsignal-'));
|
||||
try {
|
||||
writeFileSync(join(d, 'ECKeyPair.kt'), 'package org.signal.libsignal.protocol.ecc\n\npublic data class ECKeyPair(val publicKey: ECPublicKey, val privateKey: ECPrivateKey) {\n public companion object {\n public fun generate(): ECKeyPair {\n var privateKey = ECPrivateKey.generate()\n return ECKeyPair(privateKey.getPublicKey(), privateKey)\n }\n }\n}\n');
|
||||
const r = inv.scan(d);
|
||||
asigura(r.findings.length === 1 && r.findings[0].name === 'X25519' && r.findings[0].line === 6, `ancora de pachet Kotlin: ${JSON.stringify(r.findings.map((x) => [x.line, x.name, x.api]))}`);
|
||||
} finally { rmSync(d, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
proba('swift: lexerul: comentariile bloc se imbrica, interpolarea tine siruri imbricate, sirurile brute se inchid la diezi, multi-rand la """', () => {
|
||||
const t1 = '/* a /* b */ SHA256.hash(data: x) */ Insecure.MD5.hash(data: x)';
|
||||
const c1 = lx.curata(t1, 'swift');
|
||||
asigura(!c1.code.includes('SHA256') && c1.code.includes('Insecure.MD5') && c1.code.length === t1.length, `t1: ${JSON.stringify(c1.code)}`);
|
||||
const t2 = 'let s = "a \\(f("b \\(g("c"))")) d"; SHA256.hash(data: x)';
|
||||
const c2 = lx.curata(t2, 'swift');
|
||||
asigura(c2.siruri.length === 1 && c2.siruri[0][1] === t2.indexOf('; SHA256') && !lx.inSir(c2.siruri, t2.indexOf('SHA256')), `t2: ${JSON.stringify(c2.siruri)}`);
|
||||
const t3 = 'let r = #"a "b" \\(nu) \\#(da) "# ; let m = ##"x"# "## ; Insecure.SHA1.hash(data: x)';
|
||||
const c3 = lx.curata(t3, 'swift');
|
||||
asigura(c3.siruri.length === 2 && c3.siruri[0][1] === t3.indexOf(' ; let m') && c3.siruri[1][1] === t3.indexOf(' ; Insecure') && !lx.inSir(c3.siruri, t3.indexOf('Insecure')), `t3: ${JSON.stringify(c3.siruri)}`);
|
||||
const t4 = 'let m = """\n a "b" \\("c")\n """\nlet n = #"""\n d """ e\n """#\nSHA512()';
|
||||
const c4 = lx.curata(t4, 'swift');
|
||||
asigura(c4.siruri.length === 2 && !lx.inSir(c4.siruri, t4.indexOf('SHA512')) && lx.inSir(c4.siruri, t4.indexOf('d """ e')), `t4: ${JSON.stringify(c4.siruri)}`);
|
||||
// sir neterminat pe un rand: se inchide la capatul randului, nu inghite randul urmator
|
||||
const t5 = 'let x = "neterminat\nSHA256.hash(data: y)';
|
||||
const c5 = lx.curata(t5, 'swift');
|
||||
asigura(!lx.inSir(c5.siruri, t5.indexOf('SHA256')), `t5: ${JSON.stringify(c5.siruri)}`);
|
||||
});
|
||||
|
||||
proba('kotlin: lexerul: sabloanele ${ } tin siruri imbricate, sirurile brute nu au escape-uri, literalele char nu deschid siruri', () => {
|
||||
const t1 = 'val s = "k=${f("a", "${g("b")}")} ${x}"; MessageDigest.getInstance("MD5")';
|
||||
const c1 = lx.curata(t1, 'kotlin');
|
||||
asigura(c1.siruri.length === 2 && c1.siruri[0][1] === t1.indexOf('; MessageDigest') && !lx.inSir(c1.siruri, t1.indexOf('MessageDigest')), `t1: ${JSON.stringify(c1.siruri)}`);
|
||||
const t2 = 'val r = """a \\ "b" ${"c"} """" ; Cipher.getInstance("DES")';
|
||||
const c2 = lx.curata(t2, 'kotlin');
|
||||
asigura(c2.siruri.length === 2 && c2.siruri[0][1] === t2.indexOf(' ; Cipher') && !lx.inSir(c2.siruri, t2.indexOf('Cipher')), `t2: ${JSON.stringify(c2.siruri)}`);
|
||||
const t3 = "val a = '\"'; val b = '\\''; val c = '\\u0041'; val d = 'x'; Mac.getInstance(\"HmacSHA1\")";
|
||||
const c3 = lx.curata(t3, 'kotlin');
|
||||
asigura(c3.siruri.length === 5 && !lx.inSir(c3.siruri, t3.indexOf('Mac.')), `t3: ${JSON.stringify(c3.siruri)}`);
|
||||
const t4 = '/* a /* b */ KeyGenerator.getInstance("AES") */ KeyAgreement.getInstance("X25519")';
|
||||
const c4 = lx.curata(t4, 'kotlin');
|
||||
asigura(!c4.code.includes('KeyGenerator') && c4.code.includes('KeyAgreement') && c4.code.length === t4.length, `t4: ${JSON.stringify(c4.code)}`);
|
||||
});
|
||||
|
||||
proba('kotlin: variabila rezolvata (val X = "...") poarta resolvedFrom, iar KeyProperties.KEY_ALGORITHM_* se traduce in numele JCA', () => {
|
||||
const g = gasiriDin(scan(FIX), 'kotlin/Android.kt');
|
||||
const md = g.find((x) => x.name === 'SHA-256' && x.api === 'MessageDigest.getInstance');
|
||||
asigura(md && /DIGEST \(line \d+\)/.test(md.resolvedFrom || ''), `resolvedFrom: ${md && md.resolvedFrom}`);
|
||||
const ec = g.find((x) => /KEY_ALGORITHM_EC\b/.test(x.resolvedFrom || ''));
|
||||
// curba vine din Builder-ul inline din initialize(...), si ECGenParameterSpec-ul de acolo NU se numara si separat (o singura gasire pe cele 7 randuri)
|
||||
asigura(ec && ec.name === 'EC-secp256r1' && g.filter((x) => x.line >= ec.line && x.line <= ec.line + 6).length === 1, `Android Keystore EC: ${JSON.stringify(g.filter((x) => ec && x.line >= ec.line && x.line <= ec.line + 6).map((x) => [x.line, x.name, x.resolvedFrom]))}`);
|
||||
const rsa = g.find((x) => /KEY_ALGORITHM_RSA\b/.test(x.resolvedFrom || ''));
|
||||
asigura(rsa && rsa.name === 'RSA-2048' && rsa.padding === 'oaep' && rsa.primitive === 'pke', `Android Keystore RSA prin variabila spec: ${JSON.stringify(rsa && [rsa.name, rsa.padding, rsa.primitive])}`);
|
||||
});
|
||||
|
||||
proba('jvm si swift: verificarea lanturilor de certificate iese autentificare (signature, quantum-vulnerable), nu schimb de cheie', () => {
|
||||
const rez = scan(FIX);
|
||||
const pk = [...gasiriDin(rez, 'kotlin/Android.kt'), ...gasiriDin(rez, 'swift/securitate.swift')].filter((x) => x.group === 'PKI-VERIFY');
|
||||
asigura(pk.length === 7, `gasiri PKI-VERIFY: ${pk.length} (asteptate 7: 6 in Kotlin, 1 in Swift)`);
|
||||
for (const x of pk) asigura(x.primitive === 'signature' && x.quantumVulnerable === true && x.classification === 'quantum-vulnerable' && /authentication exposure/.test(x.reason) && /not a harvest-now-decrypt-later/.test(x.reason), `${x.file}:${x.line} ${x.name}: ${x.primitive} ${x.classification}`);
|
||||
const a = inv.classify({ grup: 'PKI-VERIFY' });
|
||||
asigura(a.primitiv === 'signature' && /Nothing to change in this code alone/.test(a.recommendation), 'recomandarea PKI-VERIFY nu spune ca schimbarea e la CA');
|
||||
});
|
||||
|
||||
// 2026-10-18 (libsignal): API-ul libsignal se recunoaste numai cu ancora lui (importul org.signal.libsignal / @signalapp/libsignal-client)
|
||||
proba('negativ: numele API-ului libsignal fara importul lui nu produc gasiri (Java si TypeScript), iar cu import se recunosc', () => {
|
||||
const rez = scan(FIX);
|
||||
|
||||
Reference in new issue
Block a user