Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/qytiming/main.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import CAuditDIT43import Foundation44import QyvoraMLKEM45import QyvoraMath46import QyvoraSecp256k147import QyvoraSymmetric4849#if QY_TIMING_INTERNALS50@testable import QyvoraEd2551951#else52import QyvoraEd2551953#endif5455// qytiming — dudect-style statistical timing test (Reparaz, Balasch, Verbauwhede, 2017).56//57// For each operation that must not leak a secret through its duration, two classes of inputs are58// timed in random interleaved order and compared with Welch's t-test, on the raw measurements and on59// measurements cropped at several percentiles (to remove the long tail caused by interrupts).60// |t| above 4.5 is the usual threshold for "the two timing distributions differ".61//62// What this is: statistical evidence on one machine, one compiler, one build. What it is not: a proof63// of constant-time behaviour. Swift gives no constant-time guarantee, the optimiser may change between64// versions, and no power or electromagnetic measurement is made. Two controls prove the harness can65// see a leak (an early-exit comparison) and does not invent one (same class against itself).66//67// qytiming [--scale X] [--only name[,name]] [--seed N] [--dit] [--no-barrier] [--pool N] [--json file] [--internals]68//69// `--internals` (only in a build made with QY_TIMING_INTERNALS=1 and -Xswiftc -enable-testing) restricts the run to70// the targets that call internal functions of the Ed25519 module with chosen scalars and field elements, plus the two71// basic controls. Every other measurement is made on the production build (no testability).7273struct Options {74 var scale = 1.075 var only: Set<String>?76 var seed: UInt64?77 var json: String?78 /// Sets the processor's data-independent-timing flag (PSTATE.DIT) for the measurements.79 var dit = false80 /// The processor is serialised (dsb sy; isb) between the preparation of the inputs and the timed region, and again81 /// before the final clock reading. `--no-barrier` removes this and reproduces the harness as it was before the82 /// analysis of QYV-AUD-005 (measurement artefact on mlkem-decaps-message-*).83 var barrier = true84 /// Number of buffers per class (and of distinct values in a class of many values).85 var pool = 51286 /// Only the targets on internal functions (and the two basic controls): see the header.87 var internals = false88}8990nonisolated(unsafe) var options = Options()91do {92 var args = CommandLine.arguments.dropFirst().makeIterator()93 while let a = args.next() {94 switch a {95 case "--scale": options.scale = Double(args.next() ?? "") ?? 1.096 case "--only": options.only = Set((args.next() ?? "").split(separator: ",").map(String.init))97 case "--seed": options.seed = UInt64(args.next() ?? "")98 case "--json": options.json = args.next()99 case "--dit": options.dit = true100 case "--no-barrier": options.barrier = false101 case "--pool": options.pool = max(2, Int(args.next() ?? "") ?? 512)102 case "--internals": options.internals = true103 default:104 FileHandle.standardError.write(Data("unknown argument \(a)\n".utf8))105 exit(2)106 }107 }108}109110#if QY_TIMING_INTERNALS111let internalsBuild = true112#else113let internalsBuild = false114if options.internals {115 FileHandle.standardError.write(Data("--internals needs a build with QY_TIMING_INTERNALS=1 and -Xswiftc -enable-testing\n".utf8))116 exit(2)117}118#endif119120if options.dit { qy_audit_dit_enable() }121let ditState = qy_audit_dit_enabled() == 1122FileHandle.standardError.write(Data("DIT supported: \(qy_audit_dit_supported() == 1), enabled for this run: \(ditState)\n".utf8))123124let seed = options.seed ?? AuditSeed.make("qytiming")125nonisolated(unsafe) var rng = AuditRNG(seed: seed)126127/// Keeps a value alive so that the optimiser cannot remove the measured computation.128nonisolated(unsafe) var sink: UInt64 = 0129@inline(never) func consume(_ b: Bytes) {130 var x: UInt64 = 0131 for v in b.prefix(8) { x = x << 8 | UInt64(v) }132 sink ^= x133}134@inline(never) func consume(_ b: Bool) { sink ^= b ? 1 : 2 }135@inline(never) func consume(_ v: UInt64) { sink ^= v }136137struct Result {138 let name: String, description: String, classA: String, classB: String, expectation: String139 let samplesA: Int, samplesB: Int, repetitions: Int140 let meanA: Double, meanB: Double141 let tRaw: Double, tMax: Double, cropOfMax: Int142 /// Medians of the two classes (per operation): the size of an effect that only the cropped statistics show.143 var medianA = 0.0, medianB = 0.0144}145146func welch(_ a: [Double], _ b: [Double]) -> Double {147 guard a.count > 1, b.count > 1 else { return 0 }148 let ma = a.reduce(0, +) / Double(a.count), mb = b.reduce(0, +) / Double(b.count)149 let va = a.reduce(0) { $0 + ($1 - ma) * ($1 - ma) } / Double(a.count - 1)150 let vb = b.reduce(0) { $0 + ($1 - mb) * ($1 - mb) } / Double(b.count - 1)151 let d = (va / Double(a.count) + vb / Double(b.count)).squareRoot()152 return d == 0 ? 0 : (ma - mb) / d153}154155/// Times `body()` for `samples` measurements per class in random interleaved order; `prepare(class, index)` (class 0156/// = A, 1 = B) runs before each measurement, outside the timed region, and writes the inputs of the class into fixed157/// working buffers. `repetitions` > 1 repeats the operation inside one measurement (operations shorter than the clock158/// resolution).159///160/// The loop treats the class as an index, never as a condition, and stores the measurements in one array that is161/// split afterwards: with a preparation that ignores the class, two classes show no difference at a million162/// measurements per class (diag-aes-null). What a target's `prepare` does with the class is the target's business:163/// see `ClassStore`.164func measure(165 _ name: String, description: String, classA: String, classB: String, expectation: String = "no difference",166 samples: Int, repetitions: Int = 1, prepare: (_ class: Int, _ index: Int) -> Void, body: () -> Void167) -> Result {168 let n = max(2000, Int(Double(samples) * options.scale))169 var order = [Int](repeating: 0, count: n) + [Int](repeating: 1, count: n)170 order.shuffle(using: &rng)171 // warm-up172 for i in 0..<min(2000, n) {173 prepare(i & 1, i)174 body()175 }176 let barrier = options.barrier177 var elapsed = [Double](repeating: 0, count: 2 * n)178 var next = [0, 0]179 for k in 0..<(2 * n) {180 let c = order[k]181 prepare(c, next[c]) // contents of the class copied into the working buffers, not timed182 next[c] &+= 1183 // The clock reading is not a serialising instruction: without the barrier the processor is still completing the184 // copy made by `prepare` (out-of-order execution, pending writes) when the timed region starts, and how long that185 // takes depends on where the class keeps its inputs, not on what the measured operation does (QYV-AUD-005).186 if barrier { qy_audit_serialize() }187 let start = clock_gettime_nsec_np(CLOCK_UPTIME_RAW)188 for _ in 0..<repetitions { body() }189 if barrier { qy_audit_serialize() }190 elapsed[k] = Double(clock_gettime_nsec_np(CLOCK_UPTIME_RAW) - start)191 }192 var a = [Double](), b = [Double]()193 a.reserveCapacity(n)194 b.reserveCapacity(n)195 for k in 0..<(2 * n) {196 if order[k] == 1 { b.append(elapsed[k]) } else { a.append(elapsed[k]) }197 }198 let tRaw = welch(a, b)199 var tMax = tRaw, crop = 100200 let pooled = (a + b).sorted()201 for percentile in [99, 95, 90, 75, 50] {202 let threshold = pooled[min(pooled.count - 1, pooled.count * percentile / 100)]203 let t = welch(a.filter { $0 <= threshold }, b.filter { $0 <= threshold })204 if abs(t) > abs(tMax) {205 tMax = t206 crop = percentile207 }208 }209 var r = Result(210 name: name, description: description, classA: classA, classB: classB, expectation: expectation,211 samplesA: a.count, samplesB: b.count, repetitions: repetitions,212 meanA: a.reduce(0, +) / Double(a.count) / Double(repetitions), meanB: b.reduce(0, +) / Double(b.count) / Double(repetitions),213 tRaw: tRaw, tMax: tMax, cropOfMax: crop)214 r.medianA = a.sorted()[a.count / 2] / Double(repetitions)215 r.medianB = b.sorted()[b.count / 2] / Double(repetitions)216 FileHandle.standardError.write(217 Data(String(format: "%-34s n=%d×2 mean A %.1f ns B %.1f ns median A %.1f B %.1f t(raw) %+.2f max|t| %+.2f (crop p%d)\n",218 (name as NSString).utf8String!, n, r.meanA, r.meanB, r.medianA, r.medianB, tRaw, tMax, crop).utf8))219 return r220}221222func wanted(_ name: String) -> Bool {223 if options.internals { return name == "control-leaky-compare" || name == "control-same-class" }224 return options.only?.contains(name) ?? true225}226/// Targets on internal functions: present only in the internals build, run with `--internals` or when named.227func wantedInternal(_ name: String) -> Bool { options.only?.contains(name) ?? options.internals }228let pool = options.pool229nonisolated(unsafe) var results: [Result] = []230231// Every target follows the same discipline: the measured operation always reads its inputs from the SAME232// working buffers; before each measurement (outside the timed region) the contents of the class are copied233// into them. The two classes must differ by the contents of the inputs only. Three things were found to break234// this without any difference in the contents (QYV-AUD-005), and are handled as follows:235//236// 1. Where the contents are copied FROM. A class kept in its own buffers (one buffer for a repeated value, or its237// own pool of 512) has its own addresses, alignment, cache sets and pages for the whole run; the measured238// operation then differs between the classes by a constant 1 to 3 ns (AES-GCM seal, 10 µs: |t| between 15 and239// 76 at a million measurements per class for two classes drawn from the same distribution, the sign changing240// from one process to the next). `ClassStore` keeps both classes in one block whose slots are dealt at random.241// 2. The end of the preparation overlapping the timed region: the clock reading is not a serialising instruction.242// With "one buffer against a pool of 512" this gave 5 to 12 ns on an ML-KEM decapsulation (the reported243// finding). `measure` serialises the processor before the first clock reading and before the last.244// 3. Anything in the measuring loop that depends on the class: the loop uses the class as an index only.245//246// The controls keep these honest at every run: control-same-class, control-negative-aes-random-keys and247// control-negative-mlkem-ciphertexts-* (same distribution in both classes, through ClassStore) must stay below the248// threshold; control-leaky-compare and control-positive-mlkem-leak-* must exceed it. info-former-preparation-*249// keeps the former asymmetric preparation of mlkem-decaps-message as a record (no verdict).250251/// Overwrites `destination` in place with `source` (same length).252@inline(__always) func load(_ destination: inout Bytes, _ source: Bytes) {253 precondition(destination.count == source.count)254 destination.withUnsafeMutableBytes { d in source.withUnsafeBytes { s in d.copyMemory(from: s) } }255}256257func validKey() -> Bytes {258 while true {259 let k = rng.bytes(32)260 if Secp256k1.isValidPrivateKey(k) { return k }261 }262}263264func randomPool(_ size: Int) -> [Bytes] { (0..<pool).map { _ in rng.bytes(size) } }265266/// A copy with its own storage (a plain assignment would share the buffer of the original).267func uniqueCopy(_ b: Bytes) -> Bytes {268 var c = Bytes(repeating: 0, count: b.count)269 load(&c, b)270 return c271}272273/// One value repeated in `pool` separate buffers: the class "one repeated value", stored like a class of many values.274func repeated(_ b: Bytes) -> [Bytes] { (0..<pool).map { _ in uniqueCopy(b) } }275276/// The inputs of the two classes of a target, kept in ONE block of memory cut into 2 x `pool` slots that are dealt to277/// the classes at random. A class given as a single value is repeated in `pool` slots. The two classes therefore read278/// their inputs from memory with the same statistical layout (addresses, alignment, cache sets, pages): no property279/// of where a class keeps its values can persist for a whole run (QYV-AUD-005).280final class ClassStore {281 let size: Int282 private let arena: UnsafeMutablePointer<UInt8>283 private let offsets: UnsafeMutablePointer<Int> // offsets[c * pool + j]: where value j of class c is284285 init(_ a: [Bytes], _ b: [Bytes]) {286 precondition((a.count == 1 || a.count == pool) && (b.count == 1 || b.count == pool))287 let size = a[0].count288 precondition(a.allSatisfy { $0.count == size } && b.allSatisfy { $0.count == size })289 self.size = size290 arena = .allocate(capacity: 2 * pool * size)291 offsets = .allocate(capacity: 2 * pool)292 var slots = Array(0..<(2 * pool))293 slots.shuffle(using: &rng)294 for (c, values) in [a, b].enumerated() {295 for j in 0..<pool {296 let offset = slots[c * pool + j] * size297 offsets[c * pool + j] = offset298 let v = values[values.count == 1 ? 0 : j]299 v.withUnsafeBufferPointer { (arena + offset).update(from: $0.baseAddress!, count: size) }300 }301 }302 }303304 deinit {305 arena.deallocate()306 offsets.deallocate()307 }308309 /// Copies value `index` (modulo `pool`) of class `c` (0 or 1) into `destination`: an index computation, no branch on the class.310 @inline(__always) func load(_ destination: inout Bytes, _ c: Int, _ index: Int) {311 precondition(destination.count == size)312 let source = arena + offsets[c &* pool &+ index % pool]313 destination.withUnsafeMutableBufferPointer { $0.baseAddress!.update(from: source, count: size) }314 }315}316317// MARK: controls318319/// A comparison that stops at the first difference: the harness must flag it.320@inline(never) func leakyEqual(_ a: Bytes, _ b: Bytes) -> Bool {321 for i in 0..<a.count where a[i] != b[i] { return false }322 return true323}324325if wanted("control-leaky-compare") {326 let ref = rng.bytes(256)327 var early = ref, late = ref328 early[0] ^= 1329 late[255] ^= 1330 var work = Bytes(repeating: 0, count: 256)331 let store = ClassStore([early], [late])332 results.append(333 measure(334 "control-leaky-compare", description: "POSITIVE CONTROL: early-exit comparison of 256 bytes (not engine code)",335 classA: "difference in the first byte", classB: "difference in the last byte", expectation: "difference expected (|t| > 4.5)",336 samples: 100_000, repetitions: 16, prepare: { c, i in store.load(&work, c, i) }337 ) { consume(leakyEqual(ref, work)) })338}339340if wanted("control-same-class") {341 let ref = rng.bytes(256)342 var other = ref343 other[128] ^= 1344 var work = Bytes(repeating: 0, count: 256)345 let store = ClassStore([other], [other])346 results.append(347 measure(348 "control-same-class", description: "NEGATIVE CONTROL: ConstantTime.equal with the same contents in both classes",349 classA: "contents X", classB: "contents X", samples: 100_000, repetitions: 16, prepare: { c, i in store.load(&work, c, i) }350 ) { consume(ConstantTime.equal(ref, work)) })351}352353// MARK: ConstantTime.equal354355if wanted("ct-equal-position") {356 let ref = rng.bytes(64)357 var early = ref, late = ref358 early[0] ^= 0x80359 late[63] ^= 0x01360 var work = Bytes(repeating: 0, count: 64)361 let store = ClassStore([early], [late])362 results.append(363 measure(364 "ct-equal-position", description: "ConstantTime.equal, 64 bytes, position of the difference",365 classA: "difference in the first byte", classB: "difference in the last byte", samples: 200_000, repetitions: 32,366 prepare: { c, i in store.load(&work, c, i) }367 ) { consume(ConstantTime.equal(ref, work)) })368}369370if wanted("ct-equal-hamming") {371 // Both classes are unequal to the reference (the Boolean result is public and identical in both classes).372 let ref = rng.bytes(64)373 let far = randomPool(64)374 let near: [Bytes] = (0..<pool).map { _ in375 var b = ref376 b[rng.int(0...63)] ^= UInt8(1 << rng.int(0...7))377 return b378 }379 var work = Bytes(repeating: 0, count: 64)380 let store = ClassStore(near, far)381 results.append(382 measure(383 "ct-equal-hamming", description: "ConstantTime.equal, 64 bytes, one differing bit against random contents (both unequal)",384 classA: "one bit differs", classB: "random contents", samples: 200_000, repetitions: 32,385 prepare: { c, i in store.load(&work, c, i) }386 ) { consume(ConstantTime.equal(ref, work)) })387}388389// MARK: AEAD tag verification390391if wanted("aesgcm-tag-position") {392 let key = rng.bytes(32), nonce = rng.bytes(12), plaintext = rng.bytes(256), aad = rng.bytes(16)393 let cipher = try! AESGCM(key: key)394 let sealed = try! cipher.seal(nonce: nonce, plaintext: plaintext, associatedData: aad)395 var first = sealed.tag, last = sealed.tag396 first[0] ^= 1397 last[15] ^= 1398 var tag = Bytes(repeating: 0, count: 16)399 let store = ClassStore([first], [last])400 results.append(401 measure(402 "aesgcm-tag-position", description: "AES-256-GCM open with a forged tag, position of the wrong byte",403 classA: "tag wrong in the first byte", classB: "tag wrong in the last byte", samples: 150_000, repetitions: 2,404 prepare: { c, i in store.load(&tag, c, i) }405 ) { consume((try? cipher.open(nonce: nonce, ciphertext: sealed.ciphertext, tag: tag, associatedData: aad)) == nil) })406}407408if wanted("chachapoly-tag-position") {409 let key = rng.bytes(32), nonce = rng.bytes(12), plaintext = rng.bytes(256), aad = rng.bytes(16)410 let sealed = try! ChaCha20Poly1305.seal(key: key, nonce: nonce, plaintext: plaintext, associatedData: aad)411 var first = sealed.tag, last = sealed.tag412 first[0] ^= 1413 last[15] ^= 1414 var tag = Bytes(repeating: 0, count: 16)415 let store = ClassStore([first], [last])416 results.append(417 measure(418 "chachapoly-tag-position", description: "ChaCha20-Poly1305 open with a forged tag, position of the wrong byte",419 classA: "tag wrong in the first byte", classB: "tag wrong in the last byte", samples: 150_000, repetitions: 2,420 prepare: { c, i in store.load(&tag, c, i) }421 ) { consume((try? ChaCha20Poly1305.open(key: key, nonce: nonce, ciphertext: sealed.ciphertext, tag: tag, associatedData: aad)) == nil) })422}423424if wanted("aes-key-dependence") {425 // Key expansion and encryption with the all-zero key against random keys, same nonce and plaintext. The S-box is426 // computed, not looked up (see the source review), so no key-dependent memory access is expected.427 let zero = repeated(Bytes(repeating: 0, count: 32))428 let keys = randomPool(32)429 let nonce = rng.bytes(12), plaintext = rng.bytes(64)430 var key = Bytes(repeating: 0, count: 32)431 let store = ClassStore(zero, keys)432 results.append(433 measure(434 "aes-key-dependence", description: "AES-256-GCM key expansion and seal of 64 bytes, all-zero key against random keys",435 classA: "all-zero key", classB: "random keys", samples: 100_000, prepare: { c, i in store.load(&key, c, i) }436 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })437}438439// Diagnostic targets for aes-key-dependence (only run when named). They keep each class in its OWN buffers, as every440// target did before QYV-AUD-005, to reproduce the storage effect: same contents or same distribution in both classes.441if options.only?.contains("diag-aes-zero-vs-zero") ?? false {442 let a = repeated(Bytes(repeating: 0, count: 32)), b = repeated(Bytes(repeating: 0, count: 32))443 let nonce = rng.bytes(12), plaintext = rng.bytes(64)444 var key = Bytes(repeating: 0, count: 32)445 let classes = [a, b]446 results.append(447 measure(448 "diag-aes-zero-vs-zero", description: "DIAGNOSTIC AES-256-GCM seal: all-zero key in both classes (two sets of buffers)",449 classA: "all-zero key", classB: "all-zero key", samples: 100_000, prepare: { c, i in load(&key, classes[c][i % pool]) }450 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })451}452if options.only?.contains("diag-aes-random-vs-random") ?? false {453 let a = randomPool(32), b = randomPool(32)454 let nonce = rng.bytes(12), plaintext = rng.bytes(64)455 var key = Bytes(repeating: 0, count: 32)456 let classes = [a, b]457 results.append(458 measure(459 "diag-aes-random-vs-random", description: "DIAGNOSTIC AES-256-GCM seal: random keys in both classes",460 classA: "random keys", classB: "other random keys", samples: 100_000, prepare: { c, i in load(&key, classes[c][i % pool]) }461 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })462}463if options.only?.contains("diag-aes-null") ?? false {464 // the class is ignored by the preparation: any difference comes from the measuring loop itself465 let a = randomPool(32)466 let nonce = rng.bytes(12), plaintext = rng.bytes(64)467 var key = Bytes(repeating: 0, count: 32)468 results.append(469 measure(470 "diag-aes-null", description: "DIAGNOSTIC AES-256-GCM seal: the preparation ignores the class (one pool of random keys)",471 classA: "random keys", classB: "the same random keys", samples: 100_000, prepare: { _, i in load(&key, a[i % pool]) }472 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })473}474if options.only?.contains("diag-aes-random-vs-random-swapped") ?? false {475 // as diag-aes-random-vs-random with the two pools exchanged between the classes476 let a = randomPool(32), b = randomPool(32)477 let nonce = rng.bytes(12), plaintext = rng.bytes(64)478 var key = Bytes(repeating: 0, count: 32)479 let classes = [b, a]480 results.append(481 measure(482 "diag-aes-random-vs-random-swapped", description: "DIAGNOSTIC AES-256-GCM seal: random keys in both classes, pools exchanged",483 classA: "random keys (second pool)", classB: "random keys (first pool)", samples: 100_000, prepare: { c, i in load(&key, classes[c][i % pool]) }484 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })485}486if wanted("control-negative-aes-random-keys") {487 // NEGATIVE CONTROL at the scale of the symmetric-cipher targets: both classes are random keys, kept in the shared488 // storage. Before QYV-AUD-005 (each class in its own pool) this comparison gave |t| between 15 and 76 at --scale 10.489 let store = ClassStore(randomPool(32), randomPool(32))490 let nonce = rng.bytes(12), plaintext = rng.bytes(64)491 var key = Bytes(repeating: 0, count: 32)492 results.append(493 measure(494 "control-negative-aes-random-keys", description: "NEGATIVE CONTROL: AES-256-GCM key expansion and seal of 64 bytes, random keys in both classes",495 classA: "random keys", classB: "other random keys", samples: 100_000, prepare: { c, i in store.load(&key, c, i) }496 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })497}498if options.only?.contains("diag-aes-fixed-vs-random") ?? false {499 let a = repeated(rng.bytes(32)), b = randomPool(32)500 let nonce = rng.bytes(12), plaintext = rng.bytes(64)501 var key = Bytes(repeating: 0, count: 32)502 let classes = [a, b]503 results.append(504 measure(505 "diag-aes-fixed-vs-random", description: "DIAGNOSTIC AES-256-GCM seal: one repeated random key against random keys",506 classA: "one repeated random key", classB: "random keys", samples: 100_000, prepare: { c, i in load(&key, classes[c][i % pool]) }507 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })508}509if options.only?.contains("diag-aes-zero-single-vs-random") ?? false {510 let zero = Bytes(repeating: 0, count: 32)511 let keys = randomPool(32)512 let nonce = rng.bytes(12), plaintext = rng.bytes(64)513 var key = Bytes(repeating: 0, count: 32)514 results.append(515 measure(516 "diag-aes-zero-single-vs-random", description: "DIAGNOSTIC AES-256-GCM seal: all-zero key in ONE buffer against random keys (former preparation)",517 classA: "all-zero key, one buffer", classB: "random keys", samples: 100_000, prepare: { c, i in load(&key, c == 1 ? keys[i % pool] : zero) }518 ) { consume(try! AES256GCM.seal(key: key, nonce: nonce, plaintext: plaintext).tag) })519}520521// MARK: secp256k1522523if wanted("secp256k1-mul-sparse") {524 let sparse = repeated(Bytes(repeating: 0, count: 31) + [1])525 let keys = (0..<pool).map { _ in validKey() }526 var key = Bytes(repeating: 0, count: 32)527 let store = ClassStore(sparse, keys)528 results.append(529 measure(530 "secp256k1-mul-sparse", description: "secp256k1 k·G (public key derivation), scalar 1 against random scalars",531 classA: "scalar = 1 (one bit set)", classB: "random scalars", samples: 12_000,532 prepare: { c, i in store.load(&key, c, i) }533 ) { consume(try! Secp256k1.publicKey(privateKey: key)) })534}535536if wanted("secp256k1-mul-dense") {537 // n − 1: almost every high bit set538 let dense = repeated(Hex.decode("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140")!)539 let keys = (0..<pool).map { _ in validKey() }540 var key = Bytes(repeating: 0, count: 32)541 let store = ClassStore(dense, keys)542 results.append(543 measure(544 "secp256k1-mul-dense", description: "secp256k1 k·G, scalar n−1 against random scalars",545 classA: "scalar = n − 1", classB: "random scalars", samples: 12_000,546 prepare: { c, i in store.load(&key, c, i) }547 ) { consume(try! Secp256k1.publicKey(privateKey: key)) })548}549550if wanted("secp256k1-mul-fixed") {551 // One random-looking scalar repeated against fresh random scalars: the test that exposed the carry-dependent552 // branches of finding QYV-AUD-002 (a repeated scalar trains the branch predictor when such branches exist).553 let fixed = repeated(validKey())554 let keys = (0..<pool).map { _ in validKey() }555 var key = Bytes(repeating: 0, count: 32)556 let store = ClassStore(fixed, keys)557 results.append(558 measure(559 "secp256k1-mul-fixed", description: "secp256k1 k·G, one repeated random scalar against many random scalars",560 classA: "one repeated scalar", classB: "random scalars", samples: 12_000,561 prepare: { c, i in store.load(&key, c, i) }562 ) { consume(try! Secp256k1.publicKey(privateKey: key)) })563}564565if wanted("ecdsa-sign-key") {566 let fixed = repeated(validKey())567 let keys = (0..<pool).map { _ in validKey() }568 let digests = randomPool(32)569 var key = Bytes(repeating: 0, count: 32), digest = Bytes(repeating: 0, count: 32)570 let store = ClassStore(fixed, keys)571 results.append(572 measure(573 "ecdsa-sign-key", description: "ECDSA signing (RFC 6979 nonce, k·G, k⁻¹, low-s), one key against random keys, random digests",574 classA: "one fixed key", classB: "random keys", samples: 8_000,575 prepare: { c, i in576 store.load(&key, c, i)577 load(&digest, digests[i % pool])578 }579 ) { consume(try! Secp256k1.sign(digest: digest, privateKey: key).compact) })580}581582if wanted("ecdsa-sign-fixed-message") {583 // Key and digest both repeated in class A: the whole signature computation (nonce included) is identical at every584 // measurement, against random keys on the same digest in class B.585 let fixed = repeated(validKey())586 let keys = (0..<pool).map { _ in validKey() }587 let digest = rng.bytes(32)588 var key = Bytes(repeating: 0, count: 32)589 let store = ClassStore(fixed, keys)590 results.append(591 measure(592 "ecdsa-sign-fixed-message", description: "ECDSA signing of one digest, one repeated key against random keys",593 classA: "one repeated key", classB: "random keys", samples: 8_000, prepare: { c, i in store.load(&key, c, i) }594 ) { consume(try! Secp256k1.sign(digest: digest, privateKey: key).compact) })595}596597if wanted("schnorr-sign-key") {598 let fixed = repeated(validKey())599 let keys = (0..<pool).map { _ in validKey() }600 let message = rng.bytes(32), aux = rng.bytes(32)601 var key = Bytes(repeating: 0, count: 32)602 let store = ClassStore(fixed, keys)603 results.append(604 measure(605 "schnorr-sign-key", description: "BIP-340 signing (includes the self-verification), one repeated key against random keys",606 classA: "one repeated key", classB: "random keys", samples: 5_000, prepare: { c, i in store.load(&key, c, i) }607 ) { consume(try! Secp256k1.schnorrSign(message: message, privateKey: key, auxRand: aux)) })608}609610// MARK: ML-KEM decapsulation611612for ps in MLKEM.ParameterSet.allCases where wanted("mlkem-decaps-\(ps.name)") {613 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))614 let valid = (0..<pool).map { _ in try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }615 let invalid: [Bytes] = valid.map {616 var c = $0617 c[rng.int(0...(c.count - 1))] ^= UInt8(1 << rng.int(0...7))618 return c619 }620 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)621 let store = ClassStore(valid, invalid)622 results.append(623 measure(624 "mlkem-decaps-\(ps.name)", description: "\(ps.name) decapsulation, valid ciphertexts against ciphertexts with one flipped bit (implicit rejection)",625 classA: "valid ciphertexts", classB: "invalid ciphertexts", samples: 40_000,626 prepare: { c, i in store.load(&ciphertext, c, i) }627 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)) })628}629630for ps in MLKEM.ParameterSet.allCases where wanted("mlkem-decaps-message-\(ps.name)") {631 // Same key in both classes (the public matrix is the same): one ciphertext repeated against many valid632 // ciphertexts. A dependence of the running time on the decrypted message or on s·u would show here.633 // Both classes are kept in the shared storage: the repeated ciphertext occupies as many slots as the others (QYV-AUD-005).634 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))635 let one = repeated(try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext)636 let many = (0..<pool).map { _ in try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }637 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)638 let store = ClassStore(one, many)639 results.append(640 measure(641 "mlkem-decaps-message-\(ps.name)", description: "\(ps.name) decapsulation with one key, one ciphertext repeated against many valid ciphertexts",642 classA: "one repeated ciphertext", classB: "random valid ciphertexts", samples: 40_000,643 prepare: { c, i in store.load(&ciphertext, c, i) }644 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)) })645}646647for ps in MLKEM.ParameterSet.allCases where wanted("control-negative-mlkem-ciphertexts-\(ps.name)") {648 // NEGATIVE CONTROL of mlkem-decaps-message: the same key, 512 valid ciphertexts against 512 other valid649 // ciphertexts, through the shared storage. Same distribution in both classes: any difference is the harness.650 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))651 func fresh() -> Bytes { try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }652 let store = ClassStore((0..<pool).map { _ in fresh() }, (0..<pool).map { _ in fresh() })653 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)654 results.append(655 measure(656 "control-negative-mlkem-ciphertexts-\(ps.name)",657 description: "NEGATIVE CONTROL: \(ps.name) decapsulation, valid ciphertexts against other valid ciphertexts",658 classA: "random valid ciphertexts", classB: "other random valid ciphertexts", samples: 40_000,659 prepare: { c, i in store.load(&ciphertext, c, i) }660 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)) })661}662663for ps in MLKEM.ParameterSet.allCases where wanted("info-former-preparation-\(ps.name)") {664 // INFORMATIONAL, kept as the record of QYV-AUD-005: mlkem-decaps-message exactly as it was written before that665 // finding. The repeated ciphertext is read from ONE buffer, the others from a pool of 512, so the preparation of666 // the two classes differs (addresses, cache state, instructions) while the decapsulation code is the same. With667 // `--no-barrier` it reproduces the reported artefact (|t| between 5 and 13 at --scale 10 on a quiet M4 Max); with668 // the barrier most of it disappears, but each class still has its own memory, so a small difference can remain669 // (up to 4.35 seen at --scale 10). No verdict: a difference here says nothing about the engine.670 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))671 let one = try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext672 let many = (0..<pool).map { _ in try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }673 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)674 results.append(675 measure(676 "info-former-preparation-\(ps.name)",677 description: "INFORMATIONAL, harness only: \(ps.name) decapsulation with the asymmetric preparation that produced QYV-AUD-005 (one buffer against a pool of 512)",678 classA: "one repeated ciphertext in one buffer", classB: "random valid ciphertexts in 512 buffers",679 expectation: "a difference here comes from the preparation of the inputs, not from the decapsulation (QYV-AUD-005)",680 samples: 40_000, prepare: { c, i in load(&ciphertext, c == 1 ? many[i % pool] : one) }681 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)) })682}683684/// Deliberately variable-time code for the positive control below: a loop whose number of iterations is the value of685/// the first byte of its argument (about a nanosecond per unit).686@inline(never) func leakyStep(_ x: UInt64) -> UInt64 { (x &* 0x9E37_79B9_7F4A_7C15) ^ (x >> 29) }687@inline(never) func leakyLoop(_ secret: Bytes) -> UInt64 {688 var x: UInt64 = 1689 for _ in 0..<Int(secret[0]) { x = leakyStep(x) }690 return x691}692693for ps in [MLKEM.ParameterSet.mlkem768] where wanted("control-positive-mlkem-leak-\(ps.name)") {694 // POSITIVE CONTROL of mlkem-decaps-message: the same two classes, stored and prepared the same way, but the timed695 // operation is the decapsulation followed by a loop of K[0] iterations, K being the shared secret (not engine696 // code). The repeated ciphertext is chosen so that K[0] = 0: class A runs no iteration, class B 127.5 on average.697 // It shows that the corrected target still sees a running time that depends on a secret-derived value.698 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))699 var chosen: Bytes?700 while chosen == nil {701 let e = try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32))702 if e.sharedSecret[0] == 0 { chosen = e.ciphertext }703 }704 let one = repeated(chosen!)705 let many = (0..<pool).map { _ in try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }706 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)707 let store = ClassStore(one, many)708 results.append(709 measure(710 "control-positive-mlkem-leak-\(ps.name)",711 description: "POSITIVE CONTROL: \(ps.name) decapsulation followed by a loop of K[0] iterations on the shared secret K (not engine code)",712 classA: "one repeated ciphertext with K[0] = 0", classB: "random valid ciphertexts", expectation: "difference expected (|t| > 4.5)",713 samples: 40_000, prepare: { c, i in store.load(&ciphertext, c, i) }714 ) {715 let k = try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)716 sink ^= leakyLoop(k)717 })718}719720/// Deliberately data-dependent branches for diag-branch-*: one conditional branch per bit of the first `bytes` bytes,721/// each arm calling a different function so that the compiler keeps a real branch.722@inline(never) func leakyStepA(_ x: UInt64) -> UInt64 { (x &* 0x9E37_79B9_7F4A_7C15) ^ (x >> 29) }723@inline(never) func leakyStepB(_ x: UInt64) -> UInt64 { (x ^ 0xD1B5_4A32_D192_ED03) &+ (x << 7) }724@inline(never) func leakyBranches(_ secret: Bytes, bytes: Int) -> UInt64 {725 var x: UInt64 = 1726 for i in 0..<bytes {727 for j in 0..<8 { x = (secret[i] >> UInt8(j)) & 1 == 1 ? leakyStepA(x) : leakyStepB(x) }728 }729 return x730}731732for ps in [MLKEM.ParameterSet.mlkem768] where options.only?.contains("diag-branch-\(ps.name)") ?? false {733 // DIAGNOSTIC (only run when named): decapsulation followed by 32 conditional branches on bits of the shared secret.734 // Measures how well "one repeated value against a pool" sees a leak that exists only through the branch predictor:735 // with a pool of 512 values the predictor can learn the patterns of the pool as well (see --pool and QYV-AUD-005).736 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))737 let one = repeated(try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext)738 let many = (0..<pool).map { _ in try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }739 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)740 let classes = [one, many]741 results.append(742 measure(743 "diag-branch-\(ps.name)",744 description: "DIAGNOSTIC \(ps.name) decapsulation followed by 32 branches on bits of the shared secret (not engine code)",745 classA: "one repeated ciphertext", classB: "random valid ciphertexts", expectation: "difference expected",746 samples: 40_000, prepare: { c, i in load(&ciphertext, classes[c][i % pool]) }747 ) {748 let k = try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)749 sink ^= leakyBranches(k, bytes: 4)750 })751}752753// Diagnostic targets used to analyse QYV-AUD-005; they only run when named with --only (diag-<case>-<parameter set>).754// They separate the contents of the ciphertexts from where the harness keeps them: each class is kept in its OWN755// buffers (one buffer, or 512), as before the correction, and --no-barrier restores the former timed region.756for ps in MLKEM.ParameterSet.allCases {757 func named(_ n: String) -> Bool { options.only?.contains("diag-\(n)-\(ps.name)") ?? false }758 guard ["same-single-vs-copies", "copies-vs-pool", "pool-vs-pool", "single-vs-single", "u-only", "v-only", "single-touch-vs-copies"].contains(where: named) else { continue }759 let pair = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))760 func fresh() -> Bytes { try! MLKEM.encapsInternal(ps, encapsulationKey: pair.encapsulationKey, m: rng.bytes(32)).ciphertext }761 let one = fresh()762 let copies = (0..<pool).map { _ in uniqueCopy(one) }763 let many = (0..<pool).map { _ in fresh() }764 let many2 = (0..<pool).map { _ in fresh() }765 let other = fresh()766 let split = ps.ciphertextSize - 32 * (ps == .mlkem1024 ? 5 : 4) // bytes of u (32 du k)767 // ciphertexts that differ from `one` only in u, or only in v (not valid: implicit rejection in both classes)768 let uOnly = many.map { Array($0[0..<split]) + Array(one[split..<one.count]) }769 let vOnly = many.map { Array(one[0..<split]) + Array($0[split..<one.count]) }770 var ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)771 // each class is an array of buffers read in turn (one element = one repeated buffer)772 let cases: [(String, String, [Bytes], String, [Bytes])] = [773 ("same-single-vs-copies", "one ciphertext in one buffer", [one], "the SAME ciphertext in 512 buffers", copies),774 ("copies-vs-pool", "one ciphertext in 512 buffers", copies, "512 valid ciphertexts", many),775 ("pool-vs-pool", "512 valid ciphertexts", many, "512 other valid ciphertexts", many2),776 ("single-vs-single", "one ciphertext in one buffer", [one], "another ciphertext in one buffer", [other]),777 ("u-only", "one ciphertext in 512 buffers", copies, "ciphertexts differing in u only", uOnly),778 ("v-only", "one ciphertext in 512 buffers", copies, "ciphertexts differing in v only", vOnly),779 ]780 if named("single-touch-vs-copies") {781 // class A still copies its ciphertext from the single buffer, but first reads the pool entry that class B would782 // have read (into a scratch buffer): same memory traffic in the preparation of both classes.783 var scratch = Bytes(repeating: 0, count: ps.ciphertextSize)784 results.append(785 measure(786 "diag-single-touch-vs-copies-\(ps.name)", description: "DIAGNOSTIC \(ps.name) decapsulation: same ciphertext, class A also reads a pool entry",787 classA: "one buffer (after reading a pool entry)", classB: "the SAME ciphertext in 512 buffers", samples: 40_000,788 prepare: { c, i in789 if c == 1 {790 load(&scratch, one)791 load(&ciphertext, copies[i % pool])792 } else {793 load(&scratch, copies[i % pool])794 load(&ciphertext, one)795 }796 }797 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)) })798 }799 for (n, a, classA, b, classB) in cases where named(n) {800 let classes = [classA, classB]801 results.append(802 measure(803 "diag-\(n)-\(ps.name)", description: "DIAGNOSTIC \(ps.name) decapsulation: \(a) against \(b)", classA: a, classB: b, samples: 40_000,804 prepare: { c, i in load(&ciphertext, classes[c][i % classes[c].count]) }805 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: pair.decapsulationKey, ciphertext: ciphertext)) })806 }807}808809for ps in [MLKEM.ParameterSet.mlkem768] where wanted("info-mlkem-encaps-publickey-\(ps.name)") {810 // INFORMATIONAL (no secret key involved): encapsulation with one public key against many public keys.811 // The matrix A is expanded from the public seed rho by rejection sampling (FIPS 203, SampleNTT), whose812 // branches depend on rho: a difference here measures that public-data effect.813 let fixed = repeated(try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32)).encapsulationKey)814 let many = (0..<pool).map { _ in try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32)).encapsulationKey }815 let m = rng.bytes(32)816 var ek = Bytes(repeating: 0, count: ps.encapsulationKeySize)817 let store = ClassStore(fixed, many)818 results.append(819 measure(820 "info-mlkem-encaps-publickey-\(ps.name)", description: "INFORMATIONAL, public data only: \(ps.name) encapsulation, one public key against many",821 classA: "one repeated public key", classB: "random public keys",822 expectation: "difference expected from public data (matrix expansion by rejection sampling)",823 samples: 40_000, prepare: { c, i in store.load(&ek, c, i) }824 ) { consume(try! MLKEM.encapsInternal(ps, encapsulationKey: ek, m: m).sharedSecret) })825}826827for ps in [MLKEM.ParameterSet.mlkem768] where wanted("info-mlkem-decaps-key-\(ps.name)") {828 // INFORMATIONAL: one decapsulation key against many, each with its own valid ciphertext. A decapsulation key829 // contains the public seed rho: the re-encryption step expands the matrix from it (rejection sampling), so a830 // difference of the size measured for encapsulation above is expected and does not by itself indicate a831 // dependence on the secret vector s. Secret-dependent timing with the public data held constant is what the832 // targets mlkem-decaps-* (valid against invalid) and mlkem-decaps-message-* measure.833 let fixed = try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32))834 let fixedDk = repeated(fixed.decapsulationKey)835 let fixedCt = (0..<pool).map { _ in try! MLKEM.encapsInternal(ps, encapsulationKey: fixed.encapsulationKey, m: rng.bytes(32)).ciphertext }836 let pairs = (0..<pool).map { _ in try! MLKEM.keyGenInternal(ps, d: rng.bytes(32), z: rng.bytes(32)) }837 let cts = pairs.map { try! MLKEM.encapsInternal(ps, encapsulationKey: $0.encapsulationKey, m: rng.bytes(32)).ciphertext }838 var dk = Bytes(repeating: 0, count: ps.decapsulationKeySize), ciphertext = Bytes(repeating: 0, count: ps.ciphertextSize)839 let dkStore = ClassStore(fixedDk, pairs.map(\.decapsulationKey)), ctStore = ClassStore(fixedCt, cts)840 results.append(841 measure(842 "info-mlkem-decaps-key-\(ps.name)", description: "INFORMATIONAL, includes public data: \(ps.name) decapsulation, one key against many",843 classA: "one repeated key", classB: "random keys",844 expectation: "difference expected from the public part of the key (matrix expansion); compare with info-mlkem-encaps-publickey",845 samples: 40_000,846 prepare: { c, i in847 dkStore.load(&dk, c, i)848 ctStore.load(&ciphertext, c, i)849 }850 ) { consume(try! MLKEM.decapsulate(ps, decapsulationKey: dk, ciphertext: ciphertext)) })851}852853// MARK: Ed25519 (public interface: measured on the production build)854855if wanted("ed25519-publickey-fixed") {856 let fixed = repeated(rng.bytes(32))857 let seeds = randomPool(32)858 var seedBuffer = Bytes(repeating: 0, count: 32)859 let store = ClassStore(fixed, seeds)860 results.append(861 measure(862 "ed25519-publickey-fixed", description: "Ed25519 public key of a seed (SHA-512, clamping, [a]B, inversion, encoding), one repeated seed against random seeds",863 classA: "one repeated seed", classB: "random seeds", samples: 20_000,864 prepare: { c, i in store.load(&seedBuffer, c, i) }865 ) { consume(try! Ed25519.publicKey(seed: seedBuffer)) })866}867868if wanted("ed25519-sign-fixed-seed") {869 let fixed = repeated(rng.bytes(32))870 let seeds = randomPool(32)871 let messages = randomPool(64)872 var seedBuffer = Bytes(repeating: 0, count: 32), message = Bytes(repeating: 0, count: 64)873 let store = ClassStore(fixed, seeds)874 results.append(875 measure(876 "ed25519-sign-fixed-seed", description: "Ed25519 signing (key expansion, nonce, [r]B, S = r + k·a, verification of the result), one seed against random seeds, random messages",877 classA: "one fixed seed", classB: "random seeds", samples: 8_000,878 prepare: { c, i in879 store.load(&seedBuffer, c, i)880 load(&message, messages[i % pool])881 }882 ) { consume(try! Ed25519.sign(message: message, seed: seedBuffer)) })883}884885if wanted("ed25519-sign-fixed-nonce") {886 // One seed in both classes; one repeated message against random messages: the nonce r = H(prefix ‖ M) and the887 // challenge k are constant in class A and vary in class B (the secret scalar a is the same everywhere).888 let seedValue = rng.bytes(32)889 let fixed = repeated(rng.bytes(64))890 let messages = randomPool(64)891 var message = Bytes(repeating: 0, count: 64)892 let store = ClassStore(fixed, messages)893 results.append(894 measure(895 "ed25519-sign-fixed-nonce", description: "Ed25519 signing under one seed, one repeated message (constant nonce r) against random messages",896 classA: "one repeated message", classB: "random messages", samples: 8_000,897 prepare: { c, i in store.load(&message, c, i) }898 ) { consume(try! Ed25519.sign(message: message, seed: seedValue)) })899}900901if wanted("slip10-derive-fixed") {902 let fixed = repeated(rng.bytes(64))903 let seeds = randomPool(64)904 var seedBuffer = Bytes(repeating: 0, count: 64)905 let store = ClassStore(fixed, seeds)906 let path: [UInt32] = [44, 501, 0, 0]907 results.append(908 measure(909 "slip10-derive-fixed", description: "SLIP-0010 ed25519 derivation m/44'/501'/0'/0' (five HMAC-SHA512), one repeated master seed against random seeds",910 classA: "one repeated seed", classB: "random seeds", samples: 20_000,911 prepare: { c, i in store.load(&seedBuffer, c, i) }912 ) { consume(try! Ed25519.SLIP10.derive(seed: seedBuffer, path: path).privateKey) })913}914915#if QY_TIMING_INTERNALS916// MARK: Ed25519 internals (build with QY_TIMING_INTERNALS=1 and -enable-testing: the scalar is chosen directly)917//918// The public interface derives every scalar through SHA-512, so low-weight scalars cannot be reached through it.919// These targets call the internal functions of the module, which requires a build with testability enabled; the920// machine code of that build is compared with the production build by the branch-count check.921//922// The production entry points (`Ed25519.publicKey`, `Ed25519.sign`, HMAC) set the processor's data-independent-timing923// flag before they reach these functions, so the representative measurement is the one made with `--dit`: it carries924// the verdict. Without `--dit` the same targets are reported as `info-nodit-…`, without verdict: they show what the925// flag covers on this processor (operand-dependent duration of multiplications was measured on Apple M-series cores926// with the flag clear; see the review register security/audit/review/ed25519.json).927928func internalName(_ name: String) -> String { ditState ? name : "info-nodit-" + name }929func internalExpectation() -> String {930 ditState ? "no difference" : "informational: measured WITHOUT the data-independent-timing flag that the production entry points set"931}932933func edScalarTarget(_ name: String, _ what: String, classA: String, _ special: Bytes, variable: Bool) {934 guard wantedInternal(name) else { return }935 let fixed = repeated(special)936 let scalars = (0..<pool).map { _ in Sc.reduceWide(rng.bytes(64)).bytes }937 var scalar = Bytes(repeating: 0, count: 32)938 let store = ClassStore(fixed, scalars)939 let point = EdPoint.multiplyBase(scalar: Sc.reduceWide(rng.bytes(64)).bytes)940 results.append(941 measure(942 variable ? "info-public-" + name : internalName(name), description: what, classA: classA, classB: "random scalars below ℓ",943 expectation: variable944 ? "informational, public data only: the variable-base multiplication serves verification (public scalar and point) and keeps the plain table, whose zero windows add the neutral element"945 : internalExpectation(),946 samples: 20_000,947 prepare: { c, i in store.load(&scalar, c, i) }948 ) {949 let r = variable ? EdPoint.multiply(scalar: scalar, point) : EdPoint.multiplyBase(scalar: scalar)950 consume(r.x.l0 ^ r.y.l1 ^ r.z.l2 ^ r.t.l3)951 })952}953954// The base-point multiplication is the only one made with secret scalars (key derivation, nonce). Since QYV-AUD-006955// its table is shifted by one so that no window adds the neutral element: the scalars 0, 1 and 2^252, whose windows956// are almost all zero, are the regression targets of that finding.957edScalarTarget("ed25519-basemul-fixed", "Ed25519 [s]B (fixed-window, masked table lookups), one repeated random scalar against random scalars",958 classA: "one repeated scalar", Sc.reduceWide(rng.bytes(64)).bytes, variable: false)959edScalarTarget("ed25519-basemul-one", "Ed25519 [s]B, scalar 1 (one bit set) against random scalars",960 classA: "scalar = 1", [1] + Bytes(repeating: 0, count: 31), variable: false)961edScalarTarget("ed25519-basemul-zero", "Ed25519 [s]B, scalar 0 (every window selects the neutral element) against random scalars",962 classA: "scalar = 0", Bytes(repeating: 0, count: 32), variable: false)963edScalarTarget("ed25519-basemul-dense", "Ed25519 [s]B, scalar 2^256 − 1 (every window = 15) against random scalars",964 classA: "scalar = 2^256 − 1", Bytes(repeating: 0xff, count: 32), variable: false)965edScalarTarget("ed25519-basemul-highbit", "Ed25519 [s]B, scalar 2^252 (one high bit) against random scalars",966 classA: "scalar = 2^252", Bytes(repeating: 0, count: 31) + [0x10], variable: false)967edScalarTarget("ed25519-varmul-one", "Ed25519 [s]P (variable base, table built per call), scalar 1 against random scalars",968 classA: "scalar = 1", [1] + Bytes(repeating: 0, count: 31), variable: true)969edScalarTarget("ed25519-varmul-fixed", "Ed25519 [s]P (variable base), one repeated random scalar against random scalars",970 classA: "one repeated scalar", Sc.reduceWide(rng.bytes(64)).bytes, variable: true)971972func edWordsTarget(_ name: String, _ what: String, classA: String, special: Bytes, size: Int, repetitions: Int, samples: Int, _ body: @escaping (Bytes) -> UInt64) {973 guard wantedInternal(name) else { return }974 let fixed = repeated(special)975 let many = randomPool(size)976 var work = Bytes(repeating: 0, count: size)977 let store = ClassStore(fixed, many)978 results.append(979 measure(980 internalName(name), description: what, classA: classA, classB: "random values", expectation: internalExpectation(), samples: samples,981 repetitions: repetitions,982 prepare: { c, i in store.load(&work, c, i) }983 ) { consume(body(work)) })984}985986do {987 let other = Fe.fromBytes(rng.bytes(32))988 edWordsTarget("ed25519-field-mul-one", "GF(2^255−19) multiplication, operand 1 against random operands", classA: "operand = 1",989 special: [1] + Bytes(repeating: 0, count: 31), size: 32, repetitions: 64, samples: 100_000) { b in990 let r = Fe.mul(Fe.fromBytes(b), other)991 return r.l0 ^ r.l4992 }993 edWordsTarget("ed25519-field-mul-max", "GF(2^255−19) multiplication, operand 2^255 − 1 (all limbs full) against random operands", classA: "operand = 2^255 − 1",994 special: Bytes(repeating: 0xff, count: 32), size: 32, repetitions: 64, samples: 100_000) { b in995 let r = Fe.mul(Fe.fromBytes(b), other)996 return r.l0 ^ r.l4997 }998 edWordsTarget("ed25519-field-square-zero", "GF(2^255−19) squaring, 0 against random values", classA: "value = 0",999 special: Bytes(repeating: 0, count: 32), size: 32, repetitions: 64, samples: 100_000) { b in1000 let r = Fe.square(Fe.fromBytes(b))1001 return r.l0 ^ r.l41002 }1003 edWordsTarget("ed25519-field-invert-one", "GF(2^255−19) inversion (fixed addition chain), 1 against random values", classA: "value = 1",1004 special: [1] + Bytes(repeating: 0, count: 31), size: 32, repetitions: 1, samples: 40_000) { b in1005 let r = Fe.invert(Fe.fromBytes(b))1006 return r.l0 ^ r.l41007 }1008 edWordsTarget("ed25519-field-tobytes-edge", "GF(2^255−19) canonical encoding, p − 1 (the largest canonical value) against random values", classA: "value = p − 1",1009 special: [0xec] + Bytes(repeating: 0xff, count: 30) + [0x7f], size: 32, repetitions: 64, samples: 100_000) { b in1010 let w = Fe.fromBytes(b).canonicalWords1011 return w.0 ^ w.31012 }1013 let k = Sc.reduceWide(rng.bytes(64)), nonce = Sc.reduceWide(rng.bytes(64))1014 edWordsTarget("ed25519-scalar-muladd-one", "S = r + k·a mod ℓ (Montgomery), secret scalar a = 1 against random a", classA: "a = 1",1015 special: [1] + Bytes(repeating: 0, count: 31), size: 32, repetitions: 64, samples: 100_000) { b in1016 let s = Sc.mulAdd(k, Sc(littleEndian: b), nonce)1017 return s.a0 ^ s.a31018 }1019 edWordsTarget("ed25519-scalar-muladd-max", "S = r + k·a mod ℓ, a = 2^255 − 1 against random a", classA: "a = 2^255 − 1",1020 special: Bytes(repeating: 0xff, count: 31) + [0x7f], size: 32, repetitions: 64, samples: 100_000) { b in1021 let s = Sc.mulAdd(k, Sc(littleEndian: b), nonce)1022 return s.a0 ^ s.a31023 }1024 edWordsTarget("ed25519-scalar-reducewide-zero", "reduction of a 512-bit value modulo ℓ (nonce derivation), 0 against random values", classA: "value = 0",1025 special: Bytes(repeating: 0, count: 64), size: 64, repetitions: 64, samples: 100_000) { b in1026 let s = Sc.reduceWide(b)1027 return s.a0 ^ s.a31028 }1029 edWordsTarget("ed25519-scalar-reducewide-max", "reduction of a 512-bit value modulo ℓ, 2^512 − 1 against random values", classA: "value = 2^512 − 1",1030 special: Bytes(repeating: 0xff, count: 64), size: 64, repetitions: 64, samples: 100_000) { b in1031 let s = Sc.reduceWide(b)1032 return s.a0 ^ s.a31033 }1034}1035#endif10361037// MARK: output10381039var host = [CChar](repeating: 0, count: 256)1040gethostname(&host, 255)1041let report: [String: Any] = [1042 "tool": "qytiming",1043 "method": "dudect-style Welch t-test, two input classes in random interleaved order, raw and percentile-cropped (99, 95, 90, 75, 50); "1044 + "timed region separated from the preparation of the inputs by dsb sy + isb unless --no-barrier",1045 "threshold": 4.5,1046 "seed": String(seed),1047 "scale": options.scale,1048 "dit_supported": qy_audit_dit_supported() == 1,1049 "dit_enabled": ditState,1050 "serialised_timed_region": options.barrier,1051 "pool": pool,1052 "internals_build": internalsBuild,1053 "host": String(cString: host),1054 "clock": "clock_gettime_nsec_np(CLOCK_UPTIME_RAW)",1055 "results": results.map { r -> [String: Any] in1056 [1057 "name": r.name, "description": r.description, "class_a": r.classA, "class_b": r.classB, "expectation": r.expectation,1058 "samples_a": r.samplesA, "samples_b": r.samplesB, "repetitions": r.repetitions,1059 "mean_a_ns": (r.meanA * 10).rounded() / 10, "mean_b_ns": (r.meanB * 10).rounded() / 10,1060 "median_a_ns": (r.medianA * 100).rounded() / 100, "median_b_ns": (r.medianB * 100).rounded() / 100,1061 "t_raw": (r.tRaw * 100).rounded() / 100, "t_max": (r.tMax * 100).rounded() / 100, "crop_of_max": r.cropOfMax,1062 "exceeds_threshold": abs(r.tMax) > 4.5,1063 ]1064 },1065]1066let data = try! JSONSerialization.data(withJSONObject: report, options: [.prettyPrinted, .sortedKeys])1067if let path = options.json {1068 try! data.write(to: URL(fileURLWithPath: path))1069} else {1070 FileHandle.standardOutput.write(data)1071}1072if sink == 0xdead_beef { print("") }1073