diff --git a/.github/workflows/sep-source.yml b/.github/workflows/sep-source.yml index 0ce9ff281d715..bdd29eae560ad 100644 --- a/.github/workflows/sep-source.yml +++ b/.github/workflows/sep-source.yml @@ -87,6 +87,8 @@ jobs: python3 -O -m unittest tools/aurora-sep/tests/test_store_open_errors.py -v python3 -m unittest tools/aurora-sep/tests/test_identity_preservation.py -v python3 -O -m unittest tools/aurora-sep/tests/test_identity_preservation.py -v + - name: Test sensor registration before capture + run: python3 -m unittest tools/aurora-sep/tests/test_verify_bringup.py -v - name: Test capture wiping on rejected reads run: | python3 -I tools/aurora-sep/tests/capture-error-wipe/run.py diff --git a/drivers/soc/apple/registration.rs b/drivers/soc/apple/registration.rs index 08438937ac906..1d3b3156f6019 100644 --- a/drivers/soc/apple/registration.rs +++ b/drivers/soc/apple/registration.rs @@ -210,9 +210,9 @@ pub(crate) const ATTACH: Retry = Retry { budget_ms: 10_000, }; -/// Before a verify, which someone is waiting on: three attempts, back to +/// Before an interactive capture: three attempts, back to /// back. -pub(crate) const VERIFY: Retry = Retry { +pub(crate) const CAPTURE: Retry = Retry { attempts: 3, first_pause_ms: 0, budget_ms: u64::MAX, @@ -265,6 +265,10 @@ impl Outcome { pub(crate) trait Attempts { /// One bring-up, from a power-cycled sensor. fn attempt(&mut self) -> bool; + /// Whether this failure can be recovered by a new registration. + fn retryable(&self) -> bool { + true + } /// Whether the result is still wanted. fn wanted(&self) -> bool; /// Milliseconds since the first attempt began. @@ -285,6 +289,9 @@ pub(crate) fn bring_up(retry: &Retry, steps: &mut impl Attempts) -> Outcome { if steps.attempt() { return Outcome::Online(attempt); } + if !steps.retryable() { + return Outcome::GaveUp(attempt); + } let Some(pause) = retry.pause_before(attempt + 1, steps.elapsed_ms()) else { return Outcome::GaveUp(attempt); }; @@ -669,13 +676,13 @@ mod tests { #[test] fn verify_attempts_follow_each_other_at_once() { - assert_eq!(VERIFY.pause_before(2, 0), Some(0)); - assert_eq!(VERIFY.pause_before(3, u64::MAX - 1), Some(0)); - assert_eq!(VERIFY.pause_before(4, 0), None); + assert_eq!(CAPTURE.pause_before(2, 0), Some(0)); + assert_eq!(CAPTURE.pause_before(3, u64::MAX - 1), Some(0)); + assert_eq!(CAPTURE.pause_before(4, 0), None); let mut m = Model::new(); m.nonce = [false; 8]; - assert_eq!(bring_up(&VERIFY, &mut m), Outcome::GaveUp(3)); + assert_eq!(bring_up(&CAPTURE, &mut m), Outcome::GaveUp(3)); assert_eq!(m.paused, 0); assert_eq!(m.failed, 2); } @@ -732,14 +739,17 @@ mod tests { stage: u32, session: bool, shares: [bool; 8], + clears: usize, + /// Stage at power-on and the SBIO status returned by REGISTER_SERIAL. + serial_replies: [Option<(u32, u16)>; 8], attempt: usize, /// The first `fail` attempts fail after the session commit, as at /// the sequence counter's challenge. fail: usize, /// As the J314s did after a failed sequence counter init: the - /// enclave refuses the serial re-registration that follows - /// CLEAR_STATE, and a fresh registration starts a new session. - clear_refused: bool, + /// enclave accepts CLEAR_STATE but refuses the REGISTER_SERIAL + /// that follows it. A fresh registration is accepted. + refuse_serial_after_clear: bool, /// Whether the system begins to sleep during this attempt, once the /// serial is registered and before the session share. suspend_at: Option, @@ -752,9 +762,11 @@ mod tests { stage: FRESH, session: false, shares: [false; 8], + clears: 0, + serial_replies: [None; 8], attempt: 0, fail, - clear_refused: false, + refuse_serial_after_clear: false, suspend_at: None, suspending: false, } @@ -767,13 +779,19 @@ mod tests { self.stage = retry_stage(self.stage, false, retry); } let clear = plan(self.stage, true, false, true).clear_state; - if clear && self.clear_refused { - // REGISTER_SERIAL after CLEAR_STATE: 0x16. - return false; - } - if clear || (self.clear_refused && self.stage == FRESH) { + if clear { + self.clears += 1; self.session = false; } + let status = if clear && self.refuse_serial_after_clear { + crate::sbio::SBIO_STATUS_16 + } else { + 0 + }; + self.serial_replies[this] = Some((self.stage, status)); + if status != 0 { + return false; + } self.stage = ESTABLISHED; if self.suspend_at == Some(this) { self.suspending = true; @@ -837,7 +855,7 @@ mod tests { // The J314s: after a failed sequence counter init, the CLEAR_STATE // re-registration is refused for the rest of the boot. let mut e = SessionEnclave::new(1); - e.clear_refused = true; + e.refuse_serial_after_clear = true; let mut round = Round { enclave: &mut e, retry: 0, @@ -849,6 +867,32 @@ mod tests { assert_eq!(e.stage, ESTABLISHED); } + #[test] + fn t6000_verify_retries_register_serial_0x16_from_fresh() { + // On J316c an established registration cleared successfully, then + // REGISTER_SERIAL returned 0x16 at 26-33 ms after power-on. Keep + // returning that status on re-registration to exercise the fresh try. + let mut e = SessionEnclave::new(0); + e.stage = ESTABLISHED; + e.session = true; + e.refuse_serial_after_clear = true; + let mut round = Round { + enclave: &mut e, + retry: 0, + }; + assert_eq!(bring_up(&CAPTURE, &mut round), Outcome::Online(3)); + assert_eq!(e.clears, 2); + assert_eq!( + &e.serial_replies[..3], + &[ + Some((ESTABLISHED, 0x16)), + Some((ESTABLISHED, 0x16)), + Some((FRESH, 0)), + ] + ); + assert_eq!(&e.shares[..3], &[false, false, true]); + } + #[test] fn a_suspend_mid_attempt_stops_cleanly_and_resume_recovers() { // The system begins to sleep after the first attempt registered the diff --git a/drivers/soc/apple/sbio.rs b/drivers/soc/apple/sbio.rs index 0ba52b88ee240..4d996ada09ac6 100644 --- a/drivers/soc/apple/sbio.rs +++ b/drivers/soc/apple/sbio.rs @@ -2058,7 +2058,8 @@ impl SepData { purpose, wanted, began_ns: shim::boottime_ns(), - attach: kind == Bringup::Attach, + kind, + retry_serial: false, // The late and the restore rounds follow a failed attach-time one. retry: u32::from(matches!(kind, Bringup::Late | Bringup::Restore)), }; @@ -2069,10 +2070,10 @@ impl SepData { /// wakes and patches the sensor here; its first verify calibrates it. fn attach_bring_sensor_online(&self) -> bool { if self.profile.nonce_session { - return self.bring_sensor_online(); + return self.bring_sensor_online(&mut false); } let bind = diag::sensor_bind(); - let Some(patch) = self.wake_sensor() else { + let Some(patch) = self.wake_sensor(&mut false) else { dev_warn_ratelimited!(self.dev, "sbio: the sensor did not wake at attach\n"); diag::sensor_brought_up(bind, false); return false; @@ -2239,9 +2240,9 @@ impl SepData { self.late_attach_wanted.xchg(false, Relaxed) } - fn bring_sensor_online(&self) -> bool { + fn bring_sensor_online(&self, retry_serial: &mut bool) -> bool { let bind = diag::sensor_bind(); - let Some(mut patch) = self.wake_sensor() else { + let Some(mut patch) = self.wake_sensor(retry_serial) else { diag::sensor_brought_up(bind, false); return false; }; @@ -2264,7 +2265,7 @@ impl SepData { } self.sensor_calibrated.store(true, Relaxed); if parameters.is_none() { - let Some(reloaded_patch) = self.wake_sensor() else { + let Some(reloaded_patch) = self.wake_sensor(retry_serial) else { diag::sensor_brought_up(bind, false); return false; }; @@ -2555,6 +2556,7 @@ impl SepData { if self.templates_restored.load(Relaxed) || !self.cold_restore_candidate.load(Relaxed) || self.device_view_synced.load(Relaxed) + || !self.verify_wanted() { return; } @@ -2571,7 +2573,7 @@ impl SepData { if !outcome.online() { dev_err_ratelimited!(self.dev, "verify: the retried sensor bring-up failed\n"); } - let _ = sensor::idle(); + self.release_capture_sensor(); self.refresh_match_credential(); } @@ -2580,22 +2582,80 @@ impl SepData { /// `/dev/sep-key` call, not given up for `/dev/sep-bio` (see /// [`Self::capture_live`]). fn verify_wanted(&self) -> bool { - !self.shutting_down.load(Relaxed) && self.capture_live() + registration::may_continue(self.shutting_down.load(Relaxed), self.suspending.load(Relaxed)) + && self.capture_live() + } + + fn release_capture_sensor(&self) { + let _ = sensor::idle(); + self.sensor_kept.store(false, Relaxed); + self.forget_finger_lift(); + sensor::power(false); } - // Every verify registers the sensor again. On a profile with a nonce - // session that registration can fail as the attach-time one does, most - // often the first one after a system suspend, and a new attempt recovers - // it in the same way. Without one, the failure ends the user's - // authentication even though the sensor works. - fn bring_sensor_online_for_verify(&self) -> bool { - if !self.profile.nonce_session { - return self.bring_sensor_online(); + // Recover a failed serial exchange before any capture or enrolment begins. + // The underlying intermittent transport failure is tracked in + // . + fn register_for_capture( + &self, + purpose: &CStr, + kind: Bringup, + wanted: impl Fn() -> bool, + ) -> registration::Outcome { + use registration::Outcome; + if !wanted() { + return Outcome::Abandoned(0); + } + let result = + self.bring_sensor_online_retrying(purpose, kind, ®istration::CAPTURE, &wanted); + let result = match result { + Outcome::Online(n) | Outcome::GaveUp(n) if !wanted() => Outcome::Abandoned(n), + other => other, + }; + if !result.online() { + self.release_capture_sensor(); + } + result + } + + fn prepare_verify_sensor(&self, token_bytes: [u8; bio::TOKEN_LEN]) -> bool { + if !self.verify_wanted() { + return false; + } + // Keep registration and its match context together for subsequent + // touches of the same authentication. A new prompt needs a fresh + // registration: on J815 a sensor idle for 57 s had lost its patch. + if self.sensor_kept.load(Relaxed) { + if !self.key_touch_active.load(Relaxed) + && self.match_scope_gen.load(Relaxed) == self.bio_open_gen.load(Relaxed) + && self.match_context.lock().is_some() + { + let lifted = self.await_finger_lift(c"verify"); + if !self.verify_wanted() { + return false; + } + if !lifted { + self.finish_verify(bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), token_bytes); + } + return lifted; + } + self.end_match_scope(c"a fresh sensor registration"); + self.release_capture_sensor(); + } else { + self.forget_finger_lift(); + } + match self.register_for_capture(c"verify", Bringup::Verify, || self.verify_wanted()) { + registration::Outcome::Online(_) => { + self.sensor_kept.store(true, Relaxed); + true + } + registration::Outcome::Abandoned(_) => false, + registration::Outcome::GaveUp(_) => { + dev_err_ratelimited!(self.dev, "verify: the sensor did not come back online\n"); + self.finish_verify(bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), token_bytes); + false + } } - self.bring_sensor_online_retrying(c"verify", Bringup::Verify, ®istration::VERIFY, || { - self.verify_wanted() - }) - .online() } pub(crate) fn run_verify(&self) { @@ -2648,6 +2708,9 @@ impl SepData { return; } self.retry_restore_proof(); + if !self.verify_wanted() { + return; + } if !self.templates_restored.load(Relaxed) { dev_err_ratelimited!( self.dev, @@ -2675,47 +2738,10 @@ impl SepData { return; }; - // Reuse the kept sensor only for the next touch of the authentication - // that is still open. A new authentication brings it up afresh: on - // J815 a sensor kept idle for 57 s between two sudo prompts had reset - // itself and lost its patch (state 9 in the next capture, boot - // 0f4c4bbd), while a fresh bring-up takes about 40 ms. - if self.sensor_kept.load(Relaxed) - && (self.key_touch_active.load(Relaxed) - || self.match_scope_gen.load(Relaxed) != self.bio_open_gen.load(Relaxed) - || self.match_context.lock().is_none()) - { - dev_info_ratelimited!(self.dev, "verify: a new authentication; bringing the sensor up afresh instead of reusing it\n"); - let _ = sensor::idle(); - self.sensor_kept.store(false, Relaxed); - self.forget_finger_lift(); - sensor::power(false); - } - - // Arm the capture once the last touch's finger is off the sensor, as - // macOS does; a sensor brought up afresh has no touch to wait out. - if !self.sensor_kept.load(Relaxed) { - self.forget_finger_lift(); - } else if !self.await_finger_lift(c"verify") { - self.finish_verify(bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), token_bytes); + if !self.prepare_verify_sensor(token_bytes) { return; } - // macOS registers the sensor once and keeps it for later matches: no - // power cycle, CLEAR_STATE or re-registration per touch. Do the same - // while the sensor stayed up since the last verify. - if self.sensor_kept.load(Relaxed) { - dev_info_ratelimited!(self.dev, "verify: sensor still registered from the last verify; no new bring-up\n"); - } else if !self.bring_sensor_online_for_verify() { - // The enclave refuses a capture from an uncalibrated sensor (0x65 answers 1). - dev_err_ratelimited!(self.dev, "verify: the sensor did not come back online\n"); - self.finish_verify(bio::VerifyOutcome::Failed(ENROL_STATUS_SENSOR), token_bytes); - let _ = sensor::idle(); - return; - } else { - self.sensor_kept.store(true, Relaxed); - } - // Each verify matches under its own unlock evaluation: a context whose // preflight leaves a biometric match outstanding, carried in the image // init and completed after an enrolled match. @@ -3257,22 +3283,40 @@ impl SepData { bio::VerifyOutcome::Matched(bio::MatchEvidence::from_enclave_reply(identity)) } - pub(crate) fn run_enrolment(&self) { + fn prepare_enrolment_sensor(&self) -> bool { + let epoch = self.capture_epoch.load(Relaxed); + let wanted = || { + registration::may_continue(self.shutting_down.load(Relaxed), self.suspending.load(Relaxed)) + && bio::enrol_is_live(&self.bio_session.lock(), epoch) + }; + if !wanted() { + return false; + } self.end_match_scope(c"an enrolment"); + if self.sensor_kept.load(Relaxed) { + self.release_capture_sensor(); + } self.enrol_frames_accepted.store(0, Relaxed); - self.sensor_kept.store(false, Relaxed); + match self.register_for_capture(c"enrol", Bringup::Enrol, wanted) { + registration::Outcome::Online(_) => true, + registration::Outcome::Abandoned(_) => false, + registration::Outcome::GaveUp(_) => { + dev_err_ratelimited!(self.dev, "enrol: the sensor did not come back online\n"); + self.finish_enrolment(Err(ENROL_STATUS_SENSOR)); + false + } + } + } - if !self.bring_sensor_online() { - dev_err_ratelimited!(self.dev, "enrol: the sensor did not come back online\n"); - self.finish_enrolment(Err(ENROL_STATUS_SENSOR)); - let _ = sensor::idle(); + pub(crate) fn run_enrolment(&self) { + if !self.prepare_enrolment_sensor() { return; } let Some(open) = self.begin_enrolment_on_enclave() else { dev_err_ratelimited!(self.dev, "enrol: the enclave would not start an enrolment; see the preceding step\n"); + self.release_capture_sensor(); self.finish_enrolment(Err(ENROL_STATUS_ENCLAVE)); - let _ = sensor::idle(); return; }; @@ -3392,10 +3436,7 @@ impl SepData { self.reconcile_identities(); } - let _ = sensor::idle(); - self.sensor_kept.store(false, Relaxed); - self.forget_finger_lift(); - sensor::power(false); + self.release_capture_sensor(); if let Some(result) = outcome { let filed = match (result, identity, enrolment_persisted) { @@ -3479,7 +3520,7 @@ impl SepData { } } - fn register_sensor(&self, id: &sensor::Identifier) -> bool { + fn register_sensor(&self, id: &sensor::Identifier, retry_serial: &mut bool) -> bool { let stage = self.bringup.load(Relaxed); let plan = registration::plan( stage, @@ -3550,16 +3591,23 @@ impl SepData { } if self.profile.nonce_session { - if !self.authenticate_sensor() { + if !self.authenticate_sensor(retry_serial) { return false; } } else { let Some(serial) = self.read_serial_logged() else { + *retry_serial = true; return false; }; - let op = crate::sbio::sbio_register_sensor_serial(&serial); - if self.sensor_enclave_step(&op).is_none() { - return false; + match self.send_sensor_serial(&serial) { + registration::SerialAnswer::Accepted => {} + registration::SerialAnswer::Refused16 => { + dev_warn_ratelimited!(self.dev, "sensor: REGISTER_SERIAL refused with status 0x16\n"); + self.sensor_step_failed(c"REGISTER_SERIAL"); + *retry_serial = true; + return false; + } + registration::SerialAnswer::Failed => return false, } } self.bringup.store(BRINGUP_ESTABLISHED, Relaxed); @@ -3568,6 +3616,34 @@ impl SepData { true } + fn send_sensor_serial(&self, serial: &sensor::SensorSerial) -> registration::SerialAnswer { + let op = crate::sbio::sbio_register_sensor_serial(serial); + match self.sbio_transfer(&op) { + Ok(done) if done.status.is_ok() => { + self.sensor_trace(op.name()); + registration::SerialAnswer::Accepted + } + Ok(done) if done.status.answered() == Some(u32::from(crate::sbio::SBIO_STATUS_16)) => { + registration::SerialAnswer::Refused16 + } + Ok(done) => { + dev_warn_ratelimited!( + self.dev, + "sensor: {} refused with status {}\n", + op.name(), + done.status + ); + self.sensor_step_failed(op.name()); + registration::SerialAnswer::Failed + } + Err(e) => { + dev_warn_ratelimited!(self.dev, "sensor: {} transfer failed: {:?}\n", op.name(), e); + self.sensor_step_failed(op.name()); + registration::SerialAnswer::Failed + } + } + } + fn sensor_platform_identity() -> Result<[u8; 12]> { let node = kernel::of::root().ok_or(ENODEV)?; let property: KVec = node.get_property(c"serial-number")?; @@ -3610,7 +3686,7 @@ impl SepData { /// Authenticates the sensor on a profile with a nonce session, in the /// order [`registration::authenticate`] gives. - fn authenticate_sensor(&self) -> bool { + fn authenticate_sensor(&self, retry_serial: &mut bool) -> bool { let mut steps = SensorAuthentication { sep: self, refused16: false, @@ -3627,7 +3703,12 @@ impl SepData { ); true } + Err(registration::Stopped::Serial) => { + *retry_serial = true; + false + } Err(registration::Stopped::RegisterSerial) if steps.refused16 => { + *retry_serial = true; dev_warn_ratelimited!(self.dev, "sensor: REGISTER_SERIAL refused with status 0x16\n"); self.sensor_step_failed(c"REGISTER_SERIAL"); false @@ -3700,7 +3781,7 @@ impl SepData { } } - fn wake_sensor(&self) -> Option { + fn wake_sensor(&self, retry_serial: &mut bool) -> Option { self.sensor_kept.store(false, Relaxed); let _source = sensor::power_source(); self.sensor_power_ns.store(shim::boottime_ns(), Relaxed); @@ -3757,7 +3838,7 @@ impl SepData { self.sensor_ms() ); } - if !self.register_sensor(&id) { + if !self.register_sensor(&id, retry_serial) { dev_warn_ratelimited!(self.dev, "sensor: the enclave did not register the sensor\n"); return None; } @@ -6565,6 +6646,8 @@ enum Bringup { Attach, /// The late round after an attach that fell short. Late, + /// Before opening an enrolment. + Enrol, /// Before a verify. Verify, /// Before a verify, when the attach left the restored enrolment @@ -6578,8 +6661,9 @@ struct BringupAttempts<'a, W: Fn() -> bool> { purpose: &'a CStr, wanted: W, began_ns: u64, - /// Each attempt is the attach-time one rather than a verify's. - attach: bool, + kind: Bringup, + /// The last attempt could not read the serial or received REGISTER_SERIAL status 0x16. + retry_serial: bool, /// How many failed attempts the next one follows, in this round or the /// one before it; [`registration::retry_stage`] restarts from it. retry: u32, @@ -6596,10 +6680,11 @@ impl bool> registration::Attempts for BringupAttempts<'_, W> { self.sep.bringup.store(stage, Relaxed); } self.retry += 1; - let online = if self.attach { + self.retry_serial = false; + let online = if self.kind == Bringup::Attach { self.sep.attach_bring_sensor_online() } else { - self.sep.bring_sensor_online() + self.sep.bring_sensor_online(&mut self.retry_serial) }; if !online { // Each failure is logged at the step that failed; the count @@ -6609,6 +6694,14 @@ impl bool> registration::Attempts for BringupAttempts<'_, W> { online } + fn retryable(&self) -> bool { + match self.kind { + Bringup::Enrol => self.retry_serial, + Bringup::Verify => self.sep.profile.nonce_session || self.retry_serial, + _ => true, + } + } + fn wanted(&self) -> bool { (self.wanted)() } @@ -6685,37 +6778,9 @@ impl registration::Authentication for SensorAuthentication<'_> { } fn register_serial(&mut self, serial: &sensor::SensorSerial) -> registration::SerialAnswer { - let op = crate::sbio::sbio_register_sensor_serial(serial); - match self.sep.sbio_transfer(&op) { - Ok(done) if done.status.is_ok() => { - self.sep.sensor_trace(op.name()); - registration::SerialAnswer::Accepted - } - Ok(done) - if matches!( - done.status.answered(), - Some(err) if err as u16 == crate::sbio::SBIO_STATUS_16 - ) => - { - self.refused16 = true; - registration::SerialAnswer::Refused16 - } - Ok(done) => { - dev_warn_ratelimited!( - self.sep.dev, - "sensor: {} refused with status {}\n", - op.name(), - done.status - ); - self.sep.sensor_step_failed(op.name()); - registration::SerialAnswer::Failed - } - Err(e) => { - dev_warn_ratelimited!(self.sep.dev, "sensor: {} transfer failed: {:?}\n", op.name(), e); - self.sep.sensor_step_failed(op.name()); - registration::SerialAnswer::Failed - } - } + let answer = self.sep.send_sensor_serial(serial); + self.refused16 = answer == registration::SerialAnswer::Refused16; + answer } fn open_session(&mut self, nonce: &[u8; 32]) -> bool { diff --git a/drivers/soc/apple/sensor_shim.c b/drivers/soc/apple/sensor_shim.c index 978d562d647f5..02732f5c9d260 100644 --- a/drivers/soc/apple/sensor_shim.c +++ b/drivers/soc/apple/sensor_shim.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +25,13 @@ #include "shim.h" +/* + * Userspace checks this before loading the driver. T6000 retries sensor + * registration before both verification and enrolment. Backports must + * provide both paths to advertise this capability. + */ +MODULE_INFO(t6000_registration, "1"); + /* The board selects the SPI mode; an override is diagnostic only. */ #define SEP_SENSOR_HZ 8000000 #define SEP_SENSOR_BITS 8 diff --git a/tools/aurora-sep/tests/test_sensor_recheck.py b/tools/aurora-sep/tests/test_sensor_recheck.py index e54f114d07015..5b866ed19b75d 100644 --- a/tools/aurora-sep/tests/test_sensor_recheck.py +++ b/tools/aurora-sep/tests/test_sensor_recheck.py @@ -31,7 +31,7 @@ def method(source, name): class SensorRecheckTest(unittest.TestCase): def test_status_is_read_after_registration_on_every_profile(self): body = method(SBIO.read_text(), 'wake_sensor') - after = body[body.index('self.register_sensor(&id)'):] + after = body[body.index('self.register_sensor('):] read = after.index('sensor::status()') # Nothing between the registration and the read: no profile branch, # no patch step, no other sensor request. diff --git a/tools/aurora-sep/tests/test_sensor_wake.py b/tools/aurora-sep/tests/test_sensor_wake.py index 8142c6d42502b..fb0d90f347b70 100644 --- a/tools/aurora-sep/tests/test_sensor_wake.py +++ b/tools/aurora-sep/tests/test_sensor_wake.py @@ -92,11 +92,11 @@ def test_post_registration_status_drives_patch_readiness(self): pub fn patch_ack(&self)->u8 {self.ack} } } -struct Driver { profile: Profile, sensor_power_ns: AtomicU64 } +struct Driver { sensor_kept: std::sync::atomic::AtomicBool, profile: Profile, sensor_power_ns: AtomicU64 } impl Driver { - fn new()->Self { Driver { profile: Profile { nonce_session: false }, sensor_power_ns: AtomicU64::new(0) } } + fn new()->Self { Driver { sensor_kept: false.into(), profile: Profile { nonce_session: false }, sensor_power_ns: AtomicU64::new(0) } } fn sensor_ms(&self)->u64 {0} - fn register_sensor(&self,_:&sensor::Identifier)->bool { + fn register_sensor(&self,_:&sensor::Identifier,_:&mut bool)->bool { MOCK.with(|m| {let mut m=m.borrow_mut();assert_eq!(m.reads,1);m.registered=true;}); true } fn bringup_may_continue(&self,_:&std::ffi::CStr)->bool { @@ -117,8 +117,8 @@ def test_post_registration_status_drives_patch_readiness(self): (Some(sensor::Status{state:0,ack:0,silent:false}),true,Some(0)), ] { MOCK.with(|m| *m.borrow_mut()=Mock{next,..Mock::default()}); - let driver = Driver { profile: Profile { nonce_session: true }, sensor_power_ns: AtomicU64::new(0) }; - assert_eq!(driver.wake_sensor().is_some(),ready); + let driver = Driver { sensor_kept: false.into(), profile: Profile { nonce_session: true }, sensor_power_ns: AtomicU64::new(0) }; + assert_eq!(driver.wake_sensor(&mut false).is_some(),ready); MOCK.with(|m| {let m=m.borrow();assert_eq!(m.reads,2);assert!(m.registered);assert_eq!(m.patch,patch);}); } // Without a nonce session the status is read after registration too, and @@ -130,7 +130,7 @@ def test_post_registration_status_drives_patch_readiness(self): ] { MOCK.with(|m| *m.borrow_mut()=Mock{next,..Mock::default()}); let driver = Driver::new(); - assert_eq!(driver.wake_sensor().is_some(),ready); + assert_eq!(driver.wake_sensor(&mut false).is_some(),ready); MOCK.with(|m| {let m=m.borrow();assert_eq!(m.reads,2);assert!(m.registered);assert_eq!(m.patch,patch);}); } // A suspend that begins once register_sensor() has returned stops the @@ -141,8 +141,8 @@ def test_post_registration_status_drives_patch_readiness(self): // the session. for nonce_session in [false, true] { MOCK.with(|m| *m.borrow_mut()=Mock{next:Some(sensor::Status{state:0,ack:0,silent:false}),suspend:true,..Mock::default()}); - let driver = Driver { profile: Profile { nonce_session }, sensor_power_ns: AtomicU64::new(0) }; - assert!(driver.wake_sensor().is_none()); + let driver = Driver { sensor_kept: false.into(), profile: Profile { nonce_session }, sensor_power_ns: AtomicU64::new(0) }; + assert!(driver.wake_sensor(&mut false).is_none()); MOCK.with(|m| {let m=m.borrow();assert_eq!(m.reads,1);assert!(m.registered);assert_eq!(m.patch,None);}); } } diff --git a/tools/aurora-sep/tests/test_verify_bringup.py b/tools/aurora-sep/tests/test_verify_bringup.py index 778d7b3fe6bbc..40df15af57b01 100644 --- a/tools/aurora-sep/tests/test_verify_bringup.py +++ b/tools/aurora-sep/tests/test_verify_bringup.py @@ -1,15 +1,5 @@ # SPDX-License-Identifier: MIT -"""Execute the actual verify and attach sensor bring-up code with mocks. - -The first verify after a system suspend re-registers the sensor, and on a -nonce-session profile that registration can fail in a way a new attempt from -a power-cycled sensor recovers. A verify makes up to three attempts back to -back and stops as soon as it is no longer wanted. Attach makes up to five, -spaced 0.5, 1, 2 and 4 s apart, on every profile, and asks for a late retry -when all fail. A retry keeps the stage the failed attempt left, so a -registered serial is cleared first; without a nonce session every second -retry starts from a fresh registration instead. -""" +"""Exercise the driver's registration and cancellation boundaries against scripted bus replies.""" from pathlib import Path import re import subprocess @@ -56,44 +46,39 @@ def method(source, name): use std::cell::RefCell; use std::ffi::CStr; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::Relaxed}; -macro_rules! dev_err { ($($args:tt)*) => {} } -macro_rules! dev_info_refusal { ($($args:tt)*) => {} } macro_rules! dev_err_ratelimited { ($($args:tt)*) => {} } -macro_rules! dev_info_ratelimited { ($($args:tt)*) => {} } -macro_rules! dev_dbg { ($($args:tt)*) => {} } -macro_rules! dev_warn { ($($args:tt)*) => {} } macro_rules! dev_warn_ratelimited { ($($args:tt)*) => {} } -macro_rules! dev_info { ($($args:tt)*) => {} } - -const ENROL_STATUS_SENSOR: u32 = 1; -const ENROL_STATUS_ENCLAVE: u32 = 2; -const SBIO_PROBE_USER_ID: u32 = 1; +macro_rules! dev_info_ratelimited { ($($args:tt)*) => {} } const LATE_ATTACH_DELAY_MS: u32 = 10_000; const BRINGUP_PAUSE_STEP_MS: u32 = 100; +const BRINGUP_FRESH: u32 = registration::FRESH; +const BRINGUP_IDENTIFIED: u32 = registration::IDENTIFIED; +const BRINGUP_ESTABLISHED: u32 = registration::ESTABLISHED; #[derive(Default)] struct Mock { - /// Outcomes of successive bring-up attempts; missing ones fail. - script: Vec, attempts: usize, - /// The verify stops being wanted once this many attempts have run. + replies: Vec<(&'static CStr, u32)>, + stages: Vec, + errors: Vec, cancel_after: Option, - captured: bool, - finished: Option, - /// What attach reported to diag, and whether it asked for a late retry. + off: usize, + credentials: usize, attach: Option, - late: bool, - /// Milliseconds slept. clock_ms: u64, - /// The bring-up stage each attempt started from. - stages: Vec, + failures: usize, + serial_timeout: bool, + cancel_on_lift: bool, + cancel_on_scope_close: bool, + finished: usize, } thread_local! { static MOCK: RefCell = RefCell::new(Mock::default()); } mod shim { pub fn boottime_ns() -> u64 { - super::MOCK.with(|m| m.borrow().clock_ms * 1_000_000) + // Zero is the driver's sentinel for a sensor that has never captured. + super::MOCK.with(|m| (1 + m.borrow().clock_ms) * 1_000_000) } } mod kernel { @@ -110,200 +95,268 @@ def method(source, name): } } +const ENROL_STATUS_SENSOR: u32 = 2; mod bio { - pub const TOKEN_LEN: usize = 4; - #[derive(Clone, Copy, Debug, PartialEq)] - pub enum VerifyOutcome { Matched(u8), NoMatch, Failed(u32) } - pub struct Session; - pub fn verify_is_live(_: &Session, _: u64) -> bool { - super::MOCK.with(|m| { - let m = m.borrow(); - m.cancel_after.map_or(true, |n| m.attempts < n) - }) - } + pub const TOKEN_LEN: usize = 32; + pub enum VerifyOutcome { Failed(u32) } + pub fn enrol_is_live(_: &(), _: u64) -> bool { super::live() } +} +fn live() -> bool { + MOCK.with(|m| m.borrow().cancel_after.map_or(true, |n| m.borrow().attempts < n)) +} +struct Lock(RefCell); +impl Lock { + fn lock(&self) -> std::cell::RefMut<'_, T> { self.0.borrow_mut() } } mod sbio { + pub const SBIO_STATUS_16: u16 = 0x16; pub struct UserId; impl UserId { pub fn new(_: u32) -> Option { Some(UserId) } } + pub struct SbioOp(&'static super::CStr); + impl SbioOp { pub fn name(&self) -> &'static super::CStr { self.0 } } + pub fn sbio_register_sensor(_: &super::sensor::Identifier) -> SbioOp { SbioOp(c"REGISTER_SENSOR") } + pub fn sbio_clear_state() -> SbioOp { SbioOp(c"CLEAR_STATE") } + pub fn sbio_register_sensor_serial(_: &()) -> SbioOp { SbioOp(c"REGISTER_SERIAL") } } +type KVec = Vec; +enum SbioOutcome { Ok(Vec), Other } +struct Status(u32); +impl Status { fn is_ok(&self) -> bool { self.0 == 0 } fn answered(&self) -> Option { Some(self.0) } } +struct Reply { status: Status, payload: Vec } + mod sensor { + pub struct Identifier; + pub type SensorSerial = (); + pub fn session_nonce() -> Result<[u8; 32], ()> { Ok([1; 32]) } pub fn idle() -> Result<(), ()> { Ok(()) } - pub fn power(_: bool) -> bool { true } + pub fn power(on: bool) { assert!(!on); super::MOCK.with(|m| m.borrow_mut().off += 1); } pub fn is_bound() -> bool { true } } mod diag { pub fn sensor_bind() -> u32 { 0 } pub fn sensor_brought_up(_: u32, _: bool) {} + pub fn sensor_bringup_failed() { super::MOCK.with(|m| m.borrow_mut().failures += 1); } pub fn sensor_attach(state: super::registration::AttachState) { super::MOCK.with(|m| m.borrow_mut().attach = Some(state)); } } struct PatchLoaded(()); -struct Profile { nonce_session: bool } -// The bring-up adapter names the driver by its real type. +mod profile { pub enum KeyStore { Sepos13 {} } } +struct Profile { nonce_session: bool, key_store: profile::KeyStore } type SepData = Driver; -struct SessionLock(bio::Session); -impl SessionLock { fn lock(&self) -> &bio::Session { &self.0 } } - struct Driver { - dev: (), - profile: Profile, - templates_restored: AtomicBool, - device_view_synced: AtomicBool, - shutting_down: AtomicBool, - suspending: AtomicBool, - capture_epoch: AtomicU64, - bio_session: SessionLock, - bringup: AtomicU32, + dev: (), profile: Profile, sensor_kept: AtomicBool, sensor_held: AtomicBool, + templates_restored: AtomicBool, cold_restore_candidate: AtomicBool, + device_view_synced: AtomicBool, shutting_down: AtomicBool, + suspending: AtomicBool, bringup: AtomicU32, + serial_unfinished: AtomicBool, key_touch_active: AtomicBool, match_scope_gen: AtomicU64, bio_open_gen: AtomicU64, + match_context: Lock>, bio_session: Lock<()>, capture_epoch: AtomicU64, + enrol_frames_accepted: AtomicU32, } - impl Driver { - fn new(nonce_session: bool) -> Self { - Driver { - dev: (), - profile: Profile { nonce_session }, - templates_restored: AtomicBool::new(true), - device_view_synced: AtomicBool::new(false), - shutting_down: AtomicBool::new(false), - suspending: AtomicBool::new(false), - capture_epoch: AtomicU64::new(1), - bio_session: SessionLock(bio::Session), - bringup: AtomicU32::new(registration::FRESH), - } + fn new(nonce: bool) -> Self { + Self { dev: (), profile: Profile { nonce_session: nonce, key_store: profile::KeyStore::Sepos13 {} }, + sensor_kept: false.into(), sensor_held: true.into(), templates_restored: false.into(), + cold_restore_candidate: true.into(), device_view_synced: false.into(), + shutting_down: false.into(), suspending: false.into(), bringup: BRINGUP_ESTABLISHED.into(), + serial_unfinished: false.into(), key_touch_active: false.into(), match_scope_gen: 1.into(), bio_open_gen: 1.into(), + match_context: Lock(RefCell::new(None)), bio_session: Lock(RefCell::new(())), + capture_epoch: 1.into(), enrol_frames_accepted: 0.into() } } - /// The next scripted attempt. Its registration gets through and a - /// later step fails, as on the M1 Pro, leaving the stage established. - fn scripted_attempt(&self) -> bool { - let stage = self.bringup.swap(registration::ESTABLISHED, Relaxed); + fn capture_live(&self) -> bool { live() } + fn await_finger_lift(&self, _: &CStr) -> bool { MOCK.with(|m| { let mut m = m.borrow_mut(); - m.stages.push(stage); - let ok = m.script.get(m.attempts).copied().unwrap_or(false); - m.attempts += 1; - ok - }) + if m.cancel_on_lift { m.cancel_after = Some(m.attempts); } + }); + true } - fn bring_sensor_online(&self) -> bool { - let ok = self.scripted_attempt(); - // A bring-up that completes proves the identity view. - self.device_view_synced.fetch_or(ok, Relaxed); - ok + fn end_match_scope(&self, _: &CStr) { + self.match_context.lock().take(); + MOCK.with(|m| { + let mut m = m.borrow_mut(); + if m.cancel_on_scope_close { m.cancel_after = Some(m.attempts); } + }); + } + fn finish_verify(&self, _: bio::VerifyOutcome, _: [u8; bio::TOKEN_LEN]) { + MOCK.with(|m| m.borrow_mut().finished += 1); + } + fn finish_enrolment(&self, _: Result<[u8; 16], u32>) { + MOCK.with(|m| m.borrow_mut().finished += 1); } - fn retry_restore_proof(&self) {} - fn mint_token_bytes(&self) -> Option<[u8; bio::TOKEN_LEN]> { Some([1; bio::TOKEN_LEN]) } - fn settle_before_capture(&self) {} - fn verify_one_image(&self) -> bio::VerifyOutcome { - MOCK.with(|m| m.borrow_mut().captured = true); - bio::VerifyOutcome::Matched(1) + fn forget_finger_lift(&self) {} + fn refresh_match_credential(&self) { MOCK.with(|m| m.borrow_mut().credentials += 1); } + fn sensor_trace(&self, _: &CStr) {} + fn sensor_step_failed(&self, _: &CStr) {} + fn log_identity_count(&self, _: &CStr) {} + fn note_sensor_recoveries(&self) {} + fn sensor_platform_identity() -> Result<(), ()> { Ok(()) } + fn sensor_session_request(&self, _: u16, _: &CStr, _: &()) -> bool { true } + fn sbio_call(&self, _: &sbio::SbioOp) -> SbioOutcome { SbioOutcome::Ok(vec![]) } + fn read_serial_logged(&self) -> Option<()> { + MOCK.with(|m| if m.borrow().serial_timeout && m.borrow().attempts == 1 { None } else { Some(()) }) } - fn note_capture_end(&self) {} - fn save_after_match(&self, _: sbio::UserId) -> bool { true } - fn finish_verify(&self, outcome: bio::VerifyOutcome, _: [u8; bio::TOKEN_LEN]) { + fn sbio_transfer(&self, op: &sbio::SbioOp) -> Result { MOCK.with(|m| { let mut m = m.borrow_mut(); - assert!(m.finished.is_none(), "the verify reported twice"); - m.finished = Some(outcome); + let status = if op.name() == c"REGISTER_SERIAL" { + m.errors.get(m.attempts - 1).copied().unwrap_or(0) + } else { 0 }; + m.replies.push((op.name(), status)); + Ok(Reply { status: Status(status), payload: Vec::new() }) + }) + } + fn sensor_nonce_session(&self, _: &[u8; 32]) -> bool { true } + fn wake_sensor(&self, retry: &mut bool) -> Option { + MOCK.with(|m| { + let mut m = m.borrow_mut(); + m.stages.push(self.bringup.load(Relaxed)); + m.attempts += 1; }); + self.register_sensor(&sensor::Identifier, retry).then_some(PatchLoaded(())) } - fn wake_sensor(&self) -> Option { - self.scripted_attempt().then_some(PatchLoaded(())) + fn bring_sensor_online(&self, retry: &mut bool) -> bool { + let ok = self.wake_sensor(retry).is_some(); + self.device_view_synced.fetch_or(ok, Relaxed); + self.templates_restored.fetch_or(ok, Relaxed); + ok } fn complete_bringup(&self, _: PatchLoaded) -> bool { true } ''' MAIN = r''' -} -fn run(script: &[bool], cancel_after: Option, nonce: bool, verify: bool) -> Mock { - MOCK.with(|m| *m.borrow_mut() = Mock { script: script.to_vec(), cancel_after, ..Mock::default() }); - let driver = Driver::new(nonce); - if verify { - driver.run_verify() - } else { - let late = driver.attach_bringup(); - MOCK.with(|m| m.borrow_mut().late = late); - } - MOCK.with(|m| std::mem::take(&mut *m.borrow_mut())) } +fn reset(errors: &[u32], cancel_after: Option) { + MOCK.with(|m| *m.borrow_mut() = Mock { errors: errors.to_vec(), cancel_after, ..Mock::default() }); +} fn main() { - use bio::VerifyOutcome::*; - - // The case seen after a suspend: the first attempt fails, the next works. - let m = run(&[false, true], None, true, true); - assert!(m.captured && m.finished == Some(Matched(1)) && m.attempts == 2, - "a verify gave up after one failed sensor bring-up (attempts {}, finished {:?})", - m.attempts, m.finished); - - // A sensor that never comes up: three attempts, then a sensor failure. - let m = run(&[], None, true, true); - assert_eq!((m.attempts, m.captured, m.finished), (3, false, Some(Failed(ENROL_STATUS_SENSOR)))); - - // Cancelled or suspending during the first attempt: no second one. - let m = run(&[false, true], Some(1), true, true); - assert_eq!((m.attempts, m.captured, m.finished), (1, false, Some(Failed(ENROL_STATUS_SENSOR)))); - - // A first attempt that works is the only one. - let m = run(&[true], None, true, true); - assert_eq!((m.attempts, m.captured, m.finished), (1, true, Some(Matched(1)))); - - // Profiles without a nonce session keep their single attempt. - let m = run(&[false, true], None, false, true); - assert_eq!((m.attempts, m.captured, m.finished), (1, false, Some(Failed(ENROL_STATUS_SENSOR)))); - - // Verify attempts follow each other at once. - assert_eq!(run(&[], None, true, true).clock_ms, 0); - - // Attach spaces its attempts and recovers without a late retry. - let m = run(&[false, false, true], None, true, false); - assert_eq!((m.attempts, m.clock_ms, m.late), (3, 1500, false)); - assert_eq!(m.attach, Some(registration::AttachState::Attached)); - // A nonce-session profile clears instead of starting afresh. - assert_eq!(m.stages, [registration::FRESH, registration::ESTABLISHED, registration::ESTABLISHED]); - - // An attach that never comes up: five attempts within the budget, then - // a late retry is asked for and diag says so. - let m = run(&[], None, true, false); - assert_eq!((m.attempts, m.clock_ms, m.late), (5, 7500, true)); - assert_eq!(m.attach, Some(registration::AttachState::Retrying)); - - let m = run(&[true], None, true, false); - assert_eq!((m.attempts, m.clock_ms, m.late), (1, 0, false)); - assert_eq!(m.attach, Some(registration::AttachState::Attached)); - - // Without a nonce session: the M1 Pro's sensor did not wake at attach. - // The same spacing; the first retry clears the registered serial (and - // with it the enclave's session), the second starts fresh. - let m = run(&[false, false, true], None, false, false); - assert_eq!((m.attempts, m.clock_ms, m.late), (3, 1500, false)); - assert_eq!(m.stages, [registration::FRESH, registration::ESTABLISHED, registration::FRESH]); - assert_eq!(m.attach, Some(registration::AttachState::Attached)); - - let m = run(&[], None, false, false); - assert_eq!((m.attempts, m.clock_ms, m.late), (5, 7500, true)); - assert_eq!(m.attach, Some(registration::AttachState::Retrying)); - - let m = run(&[true], None, false, false); - assert_eq!((m.attempts, m.clock_ms, m.late), (1, 0, false)); - assert_eq!(m.attach, Some(registration::AttachState::Attached)); + use registration::Outcome::*; + for kind in [Bringup::Verify, Bringup::Enrol] { + let run = |driver: &Driver| driver.register_for_capture(c"capture", kind, || driver.verify_wanted()); + reset(&[0x16, 0x16, 0], None); + assert_eq!(run(&Driver::new(false)), Online(3)); + MOCK.with(|m| { + let m = m.borrow(); + assert_eq!(m.replies, [(c"CLEAR_STATE",0),(c"REGISTER_SERIAL",0x16), + (c"CLEAR_STATE",0),(c"REGISTER_SERIAL",0x16),(c"REGISTER_SERIAL",0)]); + assert_eq!(m.stages, [BRINGUP_ESTABLISHED, BRINGUP_ESTABLISHED, BRINGUP_FRESH]); + assert_eq!((m.failures, m.clock_ms, m.off), (2, 0, 0)); + }); + reset(&[], None); + MOCK.with(|m| m.borrow_mut().serial_timeout = true); + assert_eq!(run(&Driver::new(false)), Online(2)); + reset(&[0x16; 3], None); + assert_eq!(run(&Driver::new(false)), GaveUp(3)); + reset(&[0x0001_0016], None); + assert_eq!(run(&Driver::new(false)), GaveUp(1)); + reset(&[0x16, 0x27], None); + assert_eq!(run(&Driver::new(false)), GaveUp(2)); + MOCK.with(|m| assert_eq!(m.borrow().off, 1)); + for (errors, after) in [(&[][..], 0), (&[][..], 1), (&[0x16][..], 1)] { + reset(errors, Some(after)); + assert_eq!(run(&Driver::new(false)), Abandoned(after as u32)); + MOCK.with(|m| assert_eq!(m.borrow().off, usize::from(after > 0))); + } + reset(&[], None); + let driver = Driver::new(false); + driver.suspending.store(true, Relaxed); + assert_eq!(run(&driver), Abandoned(0)); + } + for verify in [true, false] { + let start = |d: &Driver| if verify { + d.prepare_verify_sensor([0; bio::TOKEN_LEN]) + } else { + d.prepare_enrolment_sensor() + }; + reset(&[0x16, 0x16], None); + assert!(start(&Driver::new(false))); + MOCK.with(|m| assert_eq!((m.borrow().attempts, m.borrow().finished), (3, 0))); + reset(&[0x27], None); + assert!(!start(&Driver::new(false))); + MOCK.with(|m| assert_eq!((m.borrow().off, m.borrow().finished), (1, 1))); + reset(&[], Some(1)); + assert!(!start(&Driver::new(false))); + MOCK.with(|m| assert_eq!((m.borrow().off, m.borrow().finished), (1, 0))); + } + let kept = Driver::new(false); + kept.sensor_kept.store(true, Relaxed); + *kept.match_context.lock() = Some(1); + reset(&[], Some(0)); + assert!(!kept.prepare_enrolment_sensor()); + assert!(kept.sensor_kept.load(Relaxed) && kept.match_context.lock().is_some()); + reset(&[], None); + MOCK.with(|m| m.borrow_mut().cancel_on_lift = true); + assert!(!kept.prepare_verify_sensor([0; bio::TOKEN_LEN])); + assert!(kept.sensor_kept.load(Relaxed) && kept.match_context.lock().is_some()); + reset(&[], None); + assert!(kept.prepare_verify_sensor([0; bio::TOKEN_LEN])); + MOCK.with(|m| assert_eq!((m.borrow().attempts, m.borrow().off), (0, 0))); + MOCK.with(|m| m.borrow_mut().cancel_on_scope_close = true); + assert!(!kept.prepare_enrolment_sensor()); + assert!(!kept.sensor_kept.load(Relaxed) && kept.match_context.lock().is_none()); + MOCK.with(|m| assert_eq!((m.borrow().attempts, m.borrow().off), (0, 1))); + + // Existing nonce-session verify recovery and spaced attach attempts. + reset(&[1], None); + let driver = Driver::new(true); + assert_eq!(driver.register_for_capture(c"verify", Bringup::Verify, || true), Online(2)); + let enrol = || driver.register_for_capture(c"enrol", Bringup::Enrol, || true); + reset(&[1], None); + assert_eq!(enrol(), GaveUp(1)); + reset(&[], None); + MOCK.with(|m| m.borrow_mut().serial_timeout = true); + assert_eq!(enrol(), Online(2)); + reset(&[0x16], None); + assert_eq!(enrol(), Online(2)); + reset(&[0x0001_0016], None); + assert_eq!(enrol(), GaveUp(1)); + // An unfinished nonce session can resume on an exact 0x16 without another attempt. + driver.serial_unfinished.store(true, Relaxed); + reset(&[0x16], None); + assert_eq!(enrol(), Online(1)); + for nonce in [false, true] { + reset(&[1, 1], None); + let driver = Driver::new(nonce); + assert!(!driver.attach_bringup()); + MOCK.with(|m| assert_eq!((m.borrow().attempts, m.borrow().clock_ms), (3, 1500))); + reset(&[1; 5], None); + assert!(Driver::new(nonce).attach_bringup()); + MOCK.with(|m| assert_eq!((m.borrow().attempts, m.borrow().clock_ms), (5, 7500))); + } + // Cold proof starts after a failed attach and refreshes credentials even + // when the request ends during the successful recovery. + reset(&[0x16, 0], Some(2)); + Driver::new(false).retry_restore_proof(); + MOCK.with(|m| { + let m = m.borrow(); + assert_eq!(m.stages, [BRINGUP_ESTABLISHED, BRINGUP_FRESH]); + assert_eq!((m.off, m.credentials), (1, 1)); + }); + reset(&[], Some(0)); + Driver::new(false).retry_restore_proof(); + MOCK.with(|m| assert_eq!((m.borrow().attempts, m.borrow().off, m.borrow().credentials), (0, 0, 0))); } ''' - class VerifyBringupTest(unittest.TestCase): - def test_verify_retries_a_failed_bring_up_like_attach(self): + def test_interactive_registration_and_attach(self): source = (APPLE / 'sbio.rs').read_text() methods = [method(source, name) for name in ( - 'run_verify', 'attach_bringup', - 'bring_sensor_online_retrying', 'bring_sensor_online_for_verify', - 'attach_bring_sensor_online', 'attach_complete', 'bringup_may_continue', - 'verify_wanted')] + 'prepare_verify_sensor', 'prepare_enrolment_sensor', 'register_for_capture', + 'release_capture_sensor', 'retry_restore_proof', + 'register_sensor', 'authenticate_sensor', 'send_sensor_serial', 'sensor_enclave_step', 'attach_bringup', + 'bring_sensor_online_retrying', 'attach_bring_sensor_online', + 'attach_complete', 'bringup_may_continue', 'verify_wanted')] self.assertTrue(all(methods)) - attempts = (item(source, '#[derive(Clone, Copy, PartialEq, Eq)]\nenum Bringup {') + adapters = (item(source, '#[derive(Clone, Copy, PartialEq, Eq)]\nenum Bringup {') + '\n' + item(source, 'struct BringupAttempts<') - + '\n' + item(source, 'impl bool> registration::Attempts')) + + '\n' + item(source, 'impl bool> registration::Attempts') + + '\n' + item(source, 'struct SensorAuthentication<') + + '\n' + item(source, 'impl registration::Authentication for SensorAuthentication')) program = (PRELUDE + '\n'.join(methods) + MAIN - + registration_module() + attempts) + + registration_module() + adapters) with tempfile.TemporaryDirectory() as directory: root = Path(directory) (root / 'test.rs').write_text(program)