keyring-manager 0.10.0

Cross-platform library for managing passwords
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
427
428
429
430
// Locked-device probes for the iOS keychain backend, driven by the app rather than by the suite:
// what they prove exists only on hardware whose screen is locked, and a simulator has neither a
// lock screen nor an enforced protection class. Run by hand from
// ViewController.runLockedDeviceTest, once per release; the maintainer's runbook for it is kept
// outside this repo.
//
// Each numbered step below gets its own key so a single lock cycle covers all of them at once. The
// seed runs unlocked, the probe runs once a second across the lock, and the report runs after the
// unlock and decides. The step numbers are the report's own: they name what failed in a log read
// hours after the phone was locked.
//
// The flag the probe is handed is UIApplication.isProtectedDataAvailable, which tracks the
// WhenUnlocked class key, the one an unpromoted item holds. A read taken while it is still true
// proves nothing, so only probes taken while it is false decide anything.
//
// Reading the legacy fixtures through the manager promotes them, which is the thing under test, so
// the probe touches those two keys only while locked. One unlocked read would spend the fixture
// before the lock cycle it was seeded for.
//
// Nothing asserts. A panic partway through a lock cycle costs the observation, which is the part
// that took a human and a phone to produce.

use super::ios_accessibility::{account_name, item_class, legacy_class, target_class};
use crate::tests::*;
use log::*;
use security_framework::passwords::{
    delete_generic_password, get_generic_password, set_generic_password,
};
use std::sync::{Mutex, MutexGuard};

static LOCKED_SERVICE: &str = "locked.keychain-rs\tio";
static LEGACY_KEY: &str = "locked-legacy@keychain-rs.io";
static PROMOTED_KEY: &str = "locked-promoted@keychain-rs.io";
static ABSENT_KEY: &str = "locked-absent@keychain-rs.io";
static REPAIR_KEY: &str = "locked-repair@keychain-rs.io";
static WRITE_KEY: &str = "locked-write@keychain-rs.io";

static LEGACY_VALUE: &str = "negative control";
static PROMOTED_VALUE: &str = "promoted secret";
static REPAIR_VALUE: &str = "repair fixture";
static WRITE_VALUE: &str = "provisioned while locked";

static FIXTURES: [&str; 5] = [LEGACY_KEY, PROMOTED_KEY, ABSENT_KEY, REPAIR_KEY, WRITE_KEY];

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ReadOutcome {
    Value,
    Mismatch,
    Locked,
    Absent,
    Failed,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum WriteOutcome {
    Wrote,
    Locked,
    Failed,
}

/// What one side of the lock cycle observed. The legacy, repair and write fields are only ever
/// filled in on the locked side: exercising them unlocked consumes the fixture.
struct Phase {
    probes: u32,
    legacy: Option<ReadOutcome>,
    legacy_value_reads: u32,
    promoted: Option<ReadOutcome>,
    promoted_value_reads: u32,
    promoted_other_reads: u32,
    promoted_promotions: u64,
    absent: Option<ReadOutcome>,
    absent_claims: u32,
    write: Option<WriteOutcome>,
    repair: Option<bool>,
}

impl Phase {
    const fn new() -> Self {
        Phase {
            probes: 0,
            legacy: None,
            legacy_value_reads: 0,
            promoted: None,
            promoted_value_reads: 0,
            promoted_other_reads: 0,
            promoted_promotions: 0,
            absent: None,
            absent_claims: 0,
            write: None,
            repair: None,
        }
    }
}

struct State {
    seeded: bool,
    locked: Phase,
    unlocked: Phase,
}

static STATE: Mutex<State> = Mutex::new(State {
    seeded: false,
    locked: Phase::new(),
    unlocked: Phase::new(),
});

/// A poisoned lock would cost every observation taken so far, and there is no invariant here worth
/// more than the record.
fn state() -> MutexGuard<'static, State> {
    STATE.lock().unwrap_or_else(|e| e.into_inner())
}

fn account(key: &str) -> String {
    account_name(LOCKED_SERVICE, key)
}

fn read(manager: &KeyringManager, key: &str, expect: &str) -> ReadOutcome {
    match manager.with_keyring(LOCKED_SERVICE, key, |kr| kr.get_value()) {
        Ok(ref v) if v == expect => ReadOutcome::Value,
        Ok(v) => {
            error!("LOCKTEST {} read {:?}, expected {:?}", key, v, expect);
            ReadOutcome::Mismatch
        }
        Err(KeyringError::Locked) => ReadOutcome::Locked,
        Err(KeyringError::NoPasswordFound) => ReadOutcome::Absent,
        Err(e) => {
            error!("LOCKTEST {} read failed: {:?}", key, e);
            ReadOutcome::Failed
        }
    }
}

/// Write an item the way a build predating the accessibility invariant did, and confirm it landed
/// with the old class.
fn seed_legacy(key: &str, value: &str) -> bool {
    let account = account(key);
    let _ = delete_generic_password("", &account);
    if let Err(e) = set_generic_password("", &account, value.as_bytes()) {
        error!("LOCKTEST could not seed {}: {}", key, e);
        return false;
    }
    let class = item_class(&account);
    if class.as_deref() != Some(legacy_class().as_str()) {
        error!(
            "LOCKTEST {} seeded with class {:?}, expected {:?}",
            key,
            class,
            legacy_class()
        );
        return false;
    }
    true
}

fn check(pass: bool, step: &str, detail: String) -> bool {
    if pass {
        info!("LOCKTEST PASS {}: {}", step, detail);
    } else {
        error!("LOCKTEST FAIL {}: {}", step, detail);
    }
    pass
}

/// Plant every fixture while the device is unlocked. Answers 0 when the device is locked or has not
/// been unlocked since boot, which is step 4's window and where the report changes what it asks.
#[no_mangle]
pub extern "C" fn locked_device_seed() -> i32 {
    super::ios::init_logging();

    let manager = match KeyringManager::new_secure(TEST_APPLICATION) {
        Ok(manager) => manager,
        Err(e) => {
            error!("LOCKTEST no keychain: {}", e);
            return 0;
        }
    };
    let mut ok = true;

    // step 1: left unpromoted, and never read through the manager until the report
    ok &= seed_legacy(LEGACY_KEY, LEGACY_VALUE);

    // step 2: the migration under test, one read promotes it and logs "keychain accessibility
    // updated"
    ok &= seed_legacy(PROMOTED_KEY, PROMOTED_VALUE);
    let promoting = manager.with_keyring(LOCKED_SERVICE, PROMOTED_KEY, |kr| kr.get_value());
    if !matches!(promoting.as_deref(), Ok(v) if v == PROMOTED_VALUE) {
        error!("LOCKTEST promoting read returned {:?}", promoting);
        ok = false;
    }
    let class = item_class(&account(PROMOTED_KEY));
    if class.as_deref() != Some(target_class().as_str()) {
        error!(
            "LOCKTEST {} did not promote, class is {:?}",
            PROMOTED_KEY, class
        );
        ok = false;
    }

    // step 5: left unpromoted on purpose, so the repair attempted under lock has something to fail
    // on
    ok &= seed_legacy(REPAIR_KEY, REPAIR_VALUE);

    // step 3's positive control: an unlocked device can prove absence, so this must not say Locked
    let _ = manager.with_keyring(LOCKED_SERVICE, ABSENT_KEY, |kr| kr.delete_value());
    let absent = manager.with_keyring(LOCKED_SERVICE, ABSENT_KEY, |kr| kr.get_value());
    if !matches!(absent, Err(KeyringError::NoPasswordFound)) {
        error!("LOCKTEST absent key answered {:?} while unlocked", absent);
        ok = false;
    }

    // step 4: provisioning a key that does not exist yet
    let _ = manager.with_keyring(LOCKED_SERVICE, WRITE_KEY, |kr| kr.delete_value());

    state().seeded = ok;
    if ok {
        info!("LOCKTEST seeded, lock the device now");
    } else {
        error!("LOCKTEST seeding failed; a device before its first unlock cannot seed, which is step 4 itself");
    }
    ok as i32
}

/// One observation, taken with the flag the caller read at the same instant.
#[no_mangle]
pub extern "C" fn locked_device_probe(protected_data_available: i32) {
    let available = protected_data_available != 0;
    let manager = match KeyringManager::new_secure(TEST_APPLICATION) {
        Ok(manager) => manager,
        Err(e) => {
            error!("LOCKTEST no keychain: {}", e);
            return;
        }
    };

    // the counter delta is per read: the repair probe below bumps it too, and step 2 is only about
    // what a read of an already promoted item does
    let before = crate::ios::promotion_count();
    let promoted = read(&manager, PROMOTED_KEY, PROMOTED_VALUE);
    let promotions = crate::ios::promotion_count() - before;
    // never Ok, so any expected value does
    let absent = read(&manager, ABSENT_KEY, "");
    let legacy = if available {
        None
    } else {
        Some(read(&manager, LEGACY_KEY, LEGACY_VALUE))
    };

    info!(
        "LOCKTEST protected_data={} promoted={:?} absent={:?} legacy={:?} promotions={}",
        available, promoted, absent, legacy, promotions
    );

    let mut state = state();
    let phase = if available {
        &mut state.unlocked
    } else {
        &mut state.locked
    };
    phase.probes += 1;
    phase.promoted = Some(promoted);
    if promoted == ReadOutcome::Value {
        phase.promoted_value_reads += 1;
    } else {
        phase.promoted_other_reads += 1;
    }
    phase.promoted_promotions += promotions;
    phase.absent = Some(absent);
    if absent == ReadOutcome::Absent {
        phase.absent_claims += 1;
    }
    if let Some(legacy) = legacy {
        phase.legacy = Some(legacy);
        if legacy == ReadOutcome::Value {
            phase.legacy_value_reads += 1;
        }
    }

    // once, on the first locked probe: these write, and a stream of them would drown the reads
    if available || phase.repair.is_some() {
        return;
    }
    let write =
        match manager.with_keyring(LOCKED_SERVICE, WRITE_KEY, |kr| kr.set_value(WRITE_VALUE)) {
            Ok(()) => WriteOutcome::Wrote,
            Err(KeyringError::Locked) => WriteOutcome::Locked,
            Err(e) => {
                error!("LOCKTEST write while locked failed: {:?}", e);
                WriteOutcome::Failed
            }
        };
    let repair = crate::ios::promote_accessibility(&account(REPAIR_KEY));
    info!("LOCKTEST while locked: write={:?} repair={}", write, repair);
    phase.write = Some(write);
    phase.repair = Some(repair);
}

/// Decide, once the device is unlocked again. Answers 1 when every step held.
#[no_mangle]
pub extern "C" fn locked_device_report() -> i32 {
    let manager = match KeyringManager::new_secure(TEST_APPLICATION) {
        Ok(manager) => manager,
        Err(e) => {
            error!("LOCKTEST no keychain: {}", e);
            return 0;
        }
    };

    let state = state();
    let locked = &state.locked;
    if locked.probes == 0 {
        error!("LOCKTEST no probe ran while protected data was unavailable, nothing is proven");
        return 0;
    }
    info!(
        "LOCKTEST {} probes while locked, {} while unlocked",
        locked.probes, state.unlocked.probes
    );

    // seeding failed, so the fixtures every step reads do not exist and the only thing left to ask
    // is whether anything at all got through
    if !state.seeded {
        let verdict = check(
            locked.write != Some(WriteOutcome::Wrote)
                && locked.promoted_value_reads == 0
                && locked.absent_claims == 0,
            "nothing was seeded, so nothing should have answered",
            format!(
                "the write answered {:?}, and reads returned a value on {} of {} locked probes",
                locked.write, locked.promoted_value_reads, locked.probes
            ),
        );
        info!("LOCKTEST no step was observed; reseed by relaunching while the device is unlocked");
        return verdict as i32;
    }

    let mut ok = true;

    // -25308 and the absence probe's Locked both arrive as KeyringError::Locked; a "keychain probe
    // failed" line in the log above marks which one happened
    ok &= check(
        locked.legacy_value_reads == 0 && locked.legacy == Some(ReadOutcome::Locked),
        "step 1 negative control",
        format!(
            "an unpromoted item answered {:?} while locked, returning its value on {} of {} probes",
            locked.legacy, locked.legacy_value_reads, locked.probes
        ),
    );

    ok &= check(
        locked.promoted_value_reads > 0 && locked.promoted_other_reads == 0,
        "step 2 the fix",
        format!(
            "the promoted item returned its value on {} of {} locked probes, last answer {:?}",
            locked.promoted_value_reads, locked.probes, locked.promoted
        ),
    );
    ok &= check(
        locked.promoted_promotions == 0,
        "step 2 promotion converged",
        format!(
            "locked reads of the promoted item issued {} accessibility updates",
            locked.promoted_promotions
        ),
    );

    ok &= check(
        locked.absent_claims == 0 && locked.absent == Some(ReadOutcome::Locked),
        "step 3 absence is never claimed under lock",
        format!(
            "a key that was never written answered {:?} while locked, claiming absence on {} of {} probes",
            locked.absent, locked.absent_claims, locked.probes
        ),
    );

    // past the first unlock the target class key is available, so provisioning has to work
    ok &= check(
        locked.write == Some(WriteOutcome::Wrote),
        "step 4 a new key can be provisioned while locked",
        format!("a write to an absent key answered {:?}", locked.write),
    );

    ok &= check(
        locked.repair == Some(false),
        "step 5 repair under lock is inert",
        format!(
            "promote_accessibility answered {:?} while locked",
            locked.repair
        ),
    );
    // raw, so the check itself cannot be what repaired it
    let raw = get_generic_password("", &account(REPAIR_KEY));
    ok &= check(
        matches!(&raw, Ok(v) if v == REPAIR_VALUE.as_bytes()),
        "step 5 the item survived the failed repair",
        format!(
            "it holds {:?}",
            raw.as_ref().map(|v| String::from_utf8_lossy(v))
        ),
    );
    let repaired = read(&manager, REPAIR_KEY, REPAIR_VALUE);
    let repaired_class = item_class(&account(REPAIR_KEY));
    ok &= check(
        repaired == ReadOutcome::Value
            && repaired_class.as_deref() == Some(target_class().as_str()),
        "step 5 the item promotes once unlocked",
        format!(
            "it read {:?} and now holds class {:?}",
            repaired, repaired_class
        ),
    );

    // the negative control has to have been a property of the lock, not of a broken item
    let legacy = read(&manager, LEGACY_KEY, LEGACY_VALUE);
    ok &= check(
        legacy == ReadOutcome::Value,
        "the negative control was a lock artifact",
        format!("the same item read {:?} once unlocked", legacy),
    );

    for key in FIXTURES {
        let _ = manager.with_keyring(LOCKED_SERVICE, key, |kr| kr.delete_value());
    }

    if ok {
        info!("LOCKTEST locked device test PASSED");
    } else {
        error!("LOCKTEST locked device test FAILED");
    }
    ok as i32
}