openentropy-core 0.12.3

Core entropy harvesting library — hardware noise sources, raw or SHA-256 conditioned
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Keychain/securityd IPC timing — entropy from the Security framework's
//! multi-domain round-trip through securityd, SEP, and APFS.

use crate::source::{EntropySource, Platform, Requirement, SourceCategory, SourceInfo};
#[cfg(target_os = "macos")]
use crate::sources::helpers::mach_time;

#[cfg(target_os = "macos")]
use crate::sources::helpers::extract_timing_entropy_variance;

/// Configuration for keychain timing entropy collection.
///
/// # Example
/// ```
/// # use openentropy_core::sources::ipc::KeychainTimingConfig;
/// let config = KeychainTimingConfig::default();
/// ```
#[derive(Debug, Clone, Default)]
pub struct KeychainTimingConfig {
    /// Use SecItemAdd/Delete (write path) instead of SecItemCopyMatching (read path).
    ///
    /// **Default:** `false` (use read path for speed)
    pub use_write_path: bool,
}

/// Harvests timing jitter from Security.framework keychain operations.
///
/// # What it measures
/// Nanosecond timing of keychain operations (SecItemCopyMatching or SecItemAdd/Delete)
/// that traverse the full Apple security stack.
///
/// # Why it's entropic
/// Every keychain operation travels through multiple independent physical domains:
/// 1. **XPC IPC** to securityd — scheduling/dispatch jitter
/// 2. **securityd processing** — SQLite database lookup, access control evaluation
/// 3. **Kernel scheduling** — context switches between our process and securityd
/// 4. **Database I/O** — SQLite page reads from the keychain database file
///
/// The write path additionally involves APFS copy-on-write and NVMe controller
/// timing. The read path may or may not traverse the Secure Enclave depending
/// on the item's access control policy.
///
/// # What makes it unique
/// No prior work has used keychain operation timing as an entropy source.
/// The round-trip through XPC IPC, securityd scheduling, and database I/O
/// aggregates jitter from multiple independent domains in a single measurement.
///
/// # Caveats
/// - High autocorrelation at lag-1 (~0.43): variance extraction mitigates this
/// - Warm-up effect: first ~100 reads are slower due to securityd cold caches
/// - Slow: ~0.6ms per sample, not suitable for high-throughput collection
///
/// # Configuration
/// See [`KeychainTimingConfig`] for tunable parameters.
#[derive(Default)]
pub struct KeychainTimingSource {
    /// Source configuration. Use `Default::default()` for recommended settings.
    pub config: KeychainTimingConfig,
}

static KEYCHAIN_TIMING_INFO: SourceInfo = SourceInfo {
    name: "keychain_timing",
    description: "Keychain/securityd round-trip timing jitter",
    physics: "Times keychain operations that traverse: XPC IPC to securityd → SQLite \
              database lookup → access control evaluation → return. Each domain (IPC \
              scheduling, securityd process scheduling, database page I/O, kernel context \
              switches) contributes independent jitter. Variance extraction removes serial \
              correlation (lag-1 autocorrelation ~0.43 in raw timings). First 100 samples \
              discarded to avoid warm-up transient from securityd cold caches.",
    category: SourceCategory::IPC,
    platform: Platform::MacOS,
    requirements: &[Requirement::SecurityFramework],
    entropy_rate_estimate: 3.0,
    composite: false,
    is_fast: false,
};

impl EntropySource for KeychainTimingSource {
    fn info(&self) -> &SourceInfo {
        &KEYCHAIN_TIMING_INFO
    }

    fn is_available(&self) -> bool {
        cfg!(target_os = "macos")
    }

    fn collect(&self, n_samples: usize) -> Vec<u8> {
        #[cfg(target_os = "macos")]
        {
            if self.config.use_write_path {
                collect_write_path(n_samples)
            } else {
                collect_read_path(n_samples)
            }
        }
        #[cfg(not(target_os = "macos"))]
        {
            let _ = n_samples;
            Vec::new()
        }
    }
}

#[cfg(target_os = "macos")]
const WARMUP_SAMPLES: usize = 100;

/// Collect entropy via the keychain read path (SecItemCopyMatching).
/// Faster (~0.6ms/sample) with excellent entropy (H∞ ≈ 6.5–7.0).
#[cfg(target_os = "macos")]
fn collect_read_path(n_samples: usize) -> Vec<u8> {
    // Bind Security framework symbols.
    #[link(name = "Security", kind = "framework")]
    unsafe extern "C" {
        static kSecClass: CFStringRef;
        static kSecClassGenericPassword: CFStringRef;
        static kSecAttrLabel: CFStringRef;
        static kSecReturnData: CFStringRef;
        static kCFBooleanTrue: CFBooleanRef;
        static kSecValueData: CFStringRef;
        static kSecAttrAccessible: CFStringRef;
        static kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly: CFStringRef;

        fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> i32;
        fn SecItemDelete(query: CFDictionaryRef) -> i32;
        fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> i32;
    }

    #[link(name = "CoreFoundation", kind = "framework")]
    unsafe extern "C" {
        fn CFStringCreateWithCString(
            alloc: CFAllocatorRef,
            cStr: *const i8,
            encoding: u32,
        ) -> CFStringRef;
        fn CFDataCreate(alloc: CFAllocatorRef, bytes: *const u8, length: isize) -> CFDataRef;
        fn CFDictionaryCreateMutable(
            alloc: CFAllocatorRef,
            capacity: isize,
            keyCallBacks: *const std::ffi::c_void,
            valueCallBacks: *const std::ffi::c_void,
        ) -> CFMutableDictionaryRef;
        fn CFDictionarySetValue(
            dict: CFMutableDictionaryRef,
            key: *const std::ffi::c_void,
            value: *const std::ffi::c_void,
        );
        fn CFRelease(cf: CFTypeRef);

        static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks;
        static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks;
    }

    // Opaque CF types (we only use them as pointers).
    type CFAllocatorRef = *const std::ffi::c_void;
    type CFStringRef = *const std::ffi::c_void;
    type CFDataRef = *const std::ffi::c_void;
    type CFBooleanRef = *const std::ffi::c_void;
    type CFDictionaryRef = *const std::ffi::c_void;
    type CFMutableDictionaryRef = *mut std::ffi::c_void;
    type CFTypeRef = *const std::ffi::c_void;

    #[repr(C)]
    struct CFDictionaryKeyCallBacks {
        _data: [u8; 40],
    }
    #[repr(C)]
    struct CFDictionaryValueCallBacks {
        _data: [u8; 40],
    }

    const K_CF_STRING_ENCODING_UTF8: u32 = 0x08000100;

    let label_cstr = b"openentropy-timing-probe\0";

    unsafe {
        // Create a keychain item to query.
        let label_cf = CFStringCreateWithCString(
            std::ptr::null(),
            label_cstr.as_ptr() as *const i8,
            K_CF_STRING_ENCODING_UTF8,
        );
        let secret: [u8; 16] = [0x42; 16];
        let secret_cf = CFDataCreate(std::ptr::null(), secret.as_ptr(), 16);

        // Create the item.
        let add_dict = CFDictionaryCreateMutable(
            std::ptr::null(),
            0,
            &kCFTypeDictionaryKeyCallBacks as *const _ as *const std::ffi::c_void,
            &kCFTypeDictionaryValueCallBacks as *const _ as *const std::ffi::c_void,
        );
        CFDictionarySetValue(add_dict, kSecClass as _, kSecClassGenericPassword as _);
        CFDictionarySetValue(add_dict, kSecAttrLabel as _, label_cf as _);
        CFDictionarySetValue(add_dict, kSecValueData as _, secret_cf as _);
        CFDictionarySetValue(
            add_dict,
            kSecAttrAccessible as _,
            kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as _,
        );

        // Delete any existing item, then add.
        let del_dict = CFDictionaryCreateMutable(
            std::ptr::null(),
            0,
            &kCFTypeDictionaryKeyCallBacks as *const _ as *const std::ffi::c_void,
            &kCFTypeDictionaryValueCallBacks as *const _ as *const std::ffi::c_void,
        );
        CFDictionarySetValue(del_dict, kSecClass as _, kSecClassGenericPassword as _);
        CFDictionarySetValue(del_dict, kSecAttrLabel as _, label_cf as _);
        SecItemDelete(del_dict as _);
        SecItemAdd(add_dict as _, std::ptr::null_mut());

        // Build query dictionary.
        let query = CFDictionaryCreateMutable(
            std::ptr::null(),
            0,
            &kCFTypeDictionaryKeyCallBacks as *const _ as *const std::ffi::c_void,
            &kCFTypeDictionaryValueCallBacks as *const _ as *const std::ffi::c_void,
        );
        CFDictionarySetValue(query, kSecClass as _, kSecClassGenericPassword as _);
        CFDictionarySetValue(query, kSecAttrLabel as _, label_cf as _);
        CFDictionarySetValue(query, kSecReturnData as _, kCFBooleanTrue as _);

        // Warm-up: discard first samples to avoid securityd cold cache transient.
        for _ in 0..WARMUP_SAMPLES {
            let mut result: CFTypeRef = std::ptr::null();
            SecItemCopyMatching(query as _, &mut result);
            if !result.is_null() {
                CFRelease(result);
            }
        }

        // Collect timings.
        let raw_count = n_samples * 2 + 64;
        let mut timings: Vec<u64> = Vec::with_capacity(raw_count);

        for _ in 0..raw_count {
            let mut result: CFTypeRef = std::ptr::null();
            let t0 = mach_time();
            SecItemCopyMatching(query as _, &mut result);
            let t1 = mach_time();
            timings.push(t1.wrapping_sub(t0));
            if !result.is_null() {
                CFRelease(result);
            }
        }

        // Cleanup.
        SecItemDelete(del_dict as _);
        CFRelease(del_dict as CFTypeRef);
        CFRelease(add_dict as CFTypeRef);
        CFRelease(query as CFTypeRef);
        CFRelease(secret_cf);
        CFRelease(label_cf);

        extract_timing_entropy_variance(&timings, n_samples)
    }
}

/// Collect entropy via the keychain write path (SecItemAdd/Delete).
/// Slower (~5ms/sample) but highest entropy (H∞ ≈ 7.4).
#[cfg(target_os = "macos")]
fn collect_write_path(n_samples: usize) -> Vec<u8> {
    #[link(name = "Security", kind = "framework")]
    unsafe extern "C" {
        static kSecClass: CFStringRef;
        static kSecClassGenericPassword: CFStringRef;
        static kSecAttrLabel: CFStringRef;
        static kSecValueData: CFStringRef;
        static kSecAttrAccessible: CFStringRef;
        static kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly: CFStringRef;

        fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> i32;
        fn SecItemDelete(query: CFDictionaryRef) -> i32;
    }

    #[link(name = "CoreFoundation", kind = "framework")]
    unsafe extern "C" {
        fn CFStringCreateWithCString(
            alloc: CFAllocatorRef,
            cStr: *const i8,
            encoding: u32,
        ) -> CFStringRef;
        fn CFDataCreate(alloc: CFAllocatorRef, bytes: *const u8, length: isize) -> CFDataRef;
        fn CFDictionaryCreateMutable(
            alloc: CFAllocatorRef,
            capacity: isize,
            keyCallBacks: *const std::ffi::c_void,
            valueCallBacks: *const std::ffi::c_void,
        ) -> CFMutableDictionaryRef;
        fn CFDictionarySetValue(
            dict: CFMutableDictionaryRef,
            key: *const std::ffi::c_void,
            value: *const std::ffi::c_void,
        );
        fn CFRelease(cf: CFTypeRef);

        static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks;
        static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks;
    }

    type CFAllocatorRef = *const std::ffi::c_void;
    type CFStringRef = *const std::ffi::c_void;
    type CFDataRef = *const std::ffi::c_void;
    type CFDictionaryRef = *const std::ffi::c_void;
    type CFMutableDictionaryRef = *mut std::ffi::c_void;
    type CFTypeRef = *const std::ffi::c_void;

    #[repr(C)]
    struct CFDictionaryKeyCallBacks {
        _data: [u8; 40],
    }
    #[repr(C)]
    struct CFDictionaryValueCallBacks {
        _data: [u8; 40],
    }

    const K_CF_STRING_ENCODING_UTF8: u32 = 0x08000100;

    let raw_count = n_samples * 4 + 64;
    let mut timings: Vec<u64> = Vec::with_capacity(raw_count);

    unsafe {
        for i in 0..raw_count {
            let mut label_buf = [0u8; 64];
            let label_str = format!("oe-ent-{}\0", i);
            label_buf[..label_str.len()].copy_from_slice(label_str.as_bytes());

            let label_cf = CFStringCreateWithCString(
                std::ptr::null(),
                label_buf.as_ptr() as *const i8,
                K_CF_STRING_ENCODING_UTF8,
            );

            let secret: [u8; 16] = [i as u8; 16];
            let secret_cf = CFDataCreate(std::ptr::null(), secret.as_ptr(), 16);

            let attrs = CFDictionaryCreateMutable(
                std::ptr::null(),
                0,
                &kCFTypeDictionaryKeyCallBacks as *const _ as *const std::ffi::c_void,
                &kCFTypeDictionaryValueCallBacks as *const _ as *const std::ffi::c_void,
            );
            CFDictionarySetValue(attrs, kSecClass as _, kSecClassGenericPassword as _);
            CFDictionarySetValue(attrs, kSecAttrLabel as _, label_cf as _);
            CFDictionarySetValue(attrs, kSecValueData as _, secret_cf as _);
            CFDictionarySetValue(
                attrs,
                kSecAttrAccessible as _,
                kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as _,
            );

            let t0 = mach_time();
            let status = SecItemAdd(attrs as _, std::ptr::null_mut());
            let t1 = mach_time();

            if status == 0 {
                // errSecSuccess
                timings.push(t1.wrapping_sub(t0));
            }

            // Delete.
            let del = CFDictionaryCreateMutable(
                std::ptr::null(),
                0,
                &kCFTypeDictionaryKeyCallBacks as *const _ as *const std::ffi::c_void,
                &kCFTypeDictionaryValueCallBacks as *const _ as *const std::ffi::c_void,
            );
            CFDictionarySetValue(del, kSecClass as _, kSecClassGenericPassword as _);
            CFDictionarySetValue(del, kSecAttrLabel as _, label_cf as _);
            SecItemDelete(del as _);

            CFRelease(del as CFTypeRef);
            CFRelease(attrs as CFTypeRef);
            CFRelease(secret_cf);
            CFRelease(label_cf);
        }
    }

    extract_timing_entropy_variance(&timings, n_samples)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn info() {
        let src = KeychainTimingSource::default();
        assert_eq!(src.name(), "keychain_timing");
        assert_eq!(src.info().category, SourceCategory::IPC);
        assert!(!src.info().composite);
    }

    #[test]
    fn default_config() {
        let config = KeychainTimingConfig::default();
        assert!(!config.use_write_path);
    }

    #[test]
    #[ignore] // Requires macOS keychain access
    fn collects_bytes_read_path() {
        let src = KeychainTimingSource::default();
        if src.is_available() {
            let data = src.collect(64);
            assert!(!data.is_empty());
            assert!(data.len() <= 64);
        }
    }

    #[test]
    #[ignore] // Requires macOS keychain access, slow
    fn collects_bytes_write_path() {
        let src = KeychainTimingSource {
            config: KeychainTimingConfig {
                use_write_path: true,
            },
        };
        if src.is_available() {
            let data = src.collect(32);
            assert!(!data.is_empty());
            assert!(data.len() <= 32);
        }
    }
}