Skip to content

openvmm: restoring an extreme snapshot RTC time overflows the RTC clock #1376

Closed

Description

@tangruize

Restoring a CMOS RTC saved state whose clock_time_millis is near i64::MIN or i64::MAX overflows the i64 offset that the RTC's host clock, SystemTimeClock, keeps from the host time. In a debug build, a very early time panics the restore itself with "attempt to subtract with overflow", and a very late one restores, after which the next read of the clock (the next save, or the guest's next read of status A or of the calendar) panics with "attempt to add with overflow". A release build does not panic: the clock reads a time about 292 million years before the epoch, so the RTC invalidates its calendar, and the guest reads the calendar registers as 0 and status D as 0x00. The time-ABI restore's downtime advance can also leave such a clock within a few milliseconds of i64::MAX: its checked_add passes, and the next read overflows the same way. No RTC saves such a time, and the downtime is at most 30 days, so only a crafted or foreign snapshot reaches this.

Reproduction

With the RTC on SystemTimeClock, restore an RTC SavedState with clock_time_millis = i64::MIN: the restore should fail, and in a debug build it panics in set_time. Or call advance_time with a downtime that brings the clock to i64::MAX - 2: it should fail, but returns Ok, and a save more than 2 ms later panics in get_time. The new tests below fail at the pin.

Cause

Rtc::restore_clock passes any i64 millisecond epoch to set_time:

// vm/devices/chipset/src/cmos_rtc/save_restore/snapshot.rs
pub(super) fn restore_clock(&mut self, clock_time_millis: i64) {
    self.real_time_source
        .set_time(LocalClockTime::from_millis_since_unix_epoch(
            clock_time_millis,
        ));
}

Rtc::advance_clock checks only its own addition:

// vm/devices/chipset/src/cmos_rtc/clock.rs
let advanced = current
    .as_millis_since_unix_epoch()
    .checked_add(delta)
    .context("RTC time overflow while applying snapshot downtime")?;
self.real_time_source
    .set_time(LocalClockTime::from_millis_since_unix_epoch(advanced));

SystemTimeClock (support/local_clock) stores the guest time minus the host time, and adds the host time back on every read, both with plain i64 arithmetic. Neither function checks that the result fits.

Fix

fix.patch refuses clock times outside a bound: the times the guest's calendar can set (0000-01-01 to 9999-12-30T22:00Z, jiff's last UTC instant) widened by Linux's host-clock range (KTIME_SEC_MAX seconds). Every time an OpenVMM save produces, with the RTC's default zero offset, is inside it, and the clock's arithmetic cannot overflow for any time inside it. Out of the bound, Fields::validate fails with RestoreError::InvalidSavedState ("RTC clock time out of range") before the restore changes anything, and advance_clock fails with its existing overflow error and leaves the clock as it was, so such a time-ABI restore fails with "failed to advance restored VM time". The four tests in cmos_rtc/tests/snapshot.rs check both paths, with the test clock and with SystemTimeClock, including both bounds:

  • restore_refuses_a_clock_time_no_rtc_saves
  • restore_rejects_extreme_clock_time_with_system_clock
  • advance_time_refuses_a_downtime_past_the_clock_range
  • advance_time_rejects_extreme_downtime_with_system_clock

Activity

  1. tangruize commented on Nov 8, 2026

    @tangruize
    ContributorAuthor

    Proposed patch

    Patch against OpenVMM 3cf58a5234ed824435825c9f87187f5129219724. Save the contents below as fix.patch and run git apply fix.patch.

    fix.patch
    diff --git a/vm/devices/chipset/src/cmos_rtc/clock.rs b/vm/devices/chipset/src/cmos_rtc/clock.rs
    index 8093503..84207b0 100644
    --- a/vm/devices/chipset/src/cmos_rtc/clock.rs
    +++ b/vm/devices/chipset/src/cmos_rtc/clock.rs
    @@ -88,6 +88,14 @@ pub(super) fn advance_clock(&mut self, duration: Duration) -> anyhow::Result<()>
                 .as_millis_since_unix_epoch()
                 .checked_add(delta)
                 .context("RTC time overflow while applying snapshot downtime")?;
    +        // Keep enough headroom for the local clock's offset and subsequent
    +        // reads: the RTC calendar range, widened by Linux KTIME_SEC_MAX.
    +        const HOST_CLOCK_MAX_MILLIS: i64 = 9_223_372_036_000;
    +        const MIN_CLOCK_TIME_MILLIS: i64 = -62_167_219_200_000 - HOST_CLOCK_MAX_MILLIS;
    +        const MAX_CLOCK_TIME_MILLIS: i64 = 253_402_207_200_000 + HOST_CLOCK_MAX_MILLIS;
    +        if !(MIN_CLOCK_TIME_MILLIS..=MAX_CLOCK_TIME_MILLIS).contains(&advanced) {
    +            anyhow::bail!("RTC time overflow while applying snapshot downtime");
    +        }
             self.real_time_source
                 .set_time(LocalClockTime::from_millis_since_unix_epoch(advanced));
             self.update_timers();
    diff --git a/vm/devices/chipset/src/cmos_rtc/save_restore/snapshot.rs b/vm/devices/chipset/src/cmos_rtc/save_restore/snapshot.rs
    index ea3c1ef..e0b033d 100644
    --- a/vm/devices/chipset/src/cmos_rtc/save_restore/snapshot.rs
    +++ b/vm/devices/chipset/src/cmos_rtc/save_restore/snapshot.rs
    @@ -12,6 +12,13 @@
     use vmcore::save_restore::RestoreError;
     use vmcore::save_restore::SaveError;
     
    +// Widen the RTC calendar range by the Linux CLOCK_REALTIME range
    +// (KTIME_SEC_MAX seconds). This admits saved guest epochs after host-clock
    +// jumps while keeping the local clock's i64 offset arithmetic in range.
    +const HOST_CLOCK_MAX_MILLIS: i64 = 9_223_372_036_000;
    +const MIN_CLOCK_TIME_MILLIS: i64 = -62_167_219_200_000 - HOST_CLOCK_MAX_MILLIS;
    +const MAX_CLOCK_TIME_MILLIS: i64 = 253_402_207_200_000 + HOST_CLOCK_MAX_MILLIS;
    +
     /// The validated snapshot fields of a saved state.
     pub(super) struct Fields {
         pub(super) time_valid: bool,
    @@ -30,6 +37,12 @@ pub(super) fn validate(state: &SavedState) -> Result<Self, RestoreError> {
                 )));
             }
     
    +        if !(MIN_CLOCK_TIME_MILLIS..=MAX_CLOCK_TIME_MILLIS).contains(&state.clock_time_millis) {
    +            return Err(RestoreError::InvalidSavedState(anyhow::anyhow!(
    +                "RTC clock time out of range"
    +            )));
    +        }
    +
             Ok(Self {
                 time_valid: state.time_valid,
                 clock_time_millis: state.clock_time_millis,
    diff --git a/vm/devices/chipset/src/cmos_rtc/tests/snapshot.rs b/vm/devices/chipset/src/cmos_rtc/tests/snapshot.rs
    index bca4ca0..954921d 100644
    --- a/vm/devices/chipset/src/cmos_rtc/tests/snapshot.rs
    +++ b/vm/devices/chipset/src/cmos_rtc/tests/snapshot.rs
    @@ -78,3 +78,126 @@ fn restore_restores_the_calendar_validity() {
             );
         }
     }
    +
    +#[test]
    +fn restore_refuses_a_clock_time_no_rtc_saves() {
    +    let min = -62_167_219_200_000 - 9_223_372_036_000;
    +    let max = 253_402_207_200_000 + 9_223_372_036_000;
    +    for millis in [i64::MIN, min - 1, max + 1, i64::MAX] {
    +        let (_pool, _keeper, clock, mut rtc) = new_test_rtc();
    +        let before = rtc.save().unwrap();
    +        let epoch = clock.get_time();
    +        let mut invalid = rtc.save().unwrap();
    +        invalid.clock_time_millis = millis;
    +
    +        assert!(matches!(
    +            rtc.restore(invalid),
    +            Err(vmcore::save_restore::RestoreError::InvalidSavedState(_))
    +        ));
    +        let after = rtc.save().unwrap();
    +        assert_eq!(clock.get_time(), epoch);
    +        assert_eq!(after.cmos, before.cmos);
    +        assert_eq!(after.clock_time_millis, before.clock_time_millis);
    +        assert_eq!(after.time_valid, before.time_valid);
    +    }
    +    for millis in [min, max] {
    +        let (_pool, _keeper, _clock, mut rtc) = new_test_rtc();
    +        let mut saved = rtc.save().unwrap();
    +        saved.clock_time_millis = millis;
    +        rtc.restore(saved).unwrap();
    +        assert_eq!(rtc.save().unwrap().clock_time_millis, millis);
    +    }
    +}
    +
    +#[test]
    +fn restore_rejects_extreme_clock_time_with_system_clock() {
    +    use crate::cmos_rtc::Rtc;
    +    use local_clock::LocalClockDelta;
    +    use local_clock::SystemTimeClock;
    +    use vmcore::line_interrupt::LineInterrupt;
    +    use vmcore::vmtime::VmTime;
    +    use vmcore::vmtime::VmTimeKeeper;
    +
    +    let mut pool = pal_async::DefaultPool::new();
    +    let driver = pool.driver();
    +    let keeper = VmTimeKeeper::new(&driver, VmTime::from_100ns(0));
    +    let source = pool.run_until(keeper.builder().build(&driver)).unwrap();
    +    let mut rtc = Rtc::new(
    +        Box::new(SystemTimeClock::new(LocalClockDelta::ZERO)),
    +        LineInterrupt::detached(),
    +        &source,
    +        0x32,
    +        None,
    +        false,
    +    );
    +    for millis in [i64::MIN, i64::MAX] {
    +        let mut saved = rtc.save().unwrap();
    +        let before = saved.clock_time_millis;
    +        saved.clock_time_millis = millis;
    +        assert!(matches!(
    +            rtc.restore(saved),
    +            Err(vmcore::save_restore::RestoreError::InvalidSavedState(_))
    +        ));
    +        let after = rtc.save().unwrap().clock_time_millis;
    +        assert!((before..before + 60_000).contains(&after));
    +    }
    +}
    +
    +#[test]
    +fn advance_time_refuses_a_downtime_past_the_clock_range() {
    +    let (mut pool, _keeper, clock, mut rtc) = new_test_rtc();
    +    let now = clock.get_time().as_millis_since_unix_epoch();
    +    let max = 253_402_207_200_000 + 9_223_372_036_000;
    +    let before = rtc.save().unwrap();
    +    for downtime in [(i64::MAX - now - 2) as u64, (max - now + 1) as u64] {
    +        assert!(
    +            pool.run_until(rtc.advance_time(Duration::from_millis(downtime)))
    +                .is_err()
    +        );
    +        let after = rtc.save().unwrap();
    +        assert_eq!(after.clock_time_millis, now);
    +        assert_eq!(after.cmos, before.cmos);
    +    }
    +
    +    pool.run_until(rtc.advance_time(Duration::from_millis((max - now) as u64)))
    +        .unwrap();
    +    assert_eq!(rtc.save().unwrap().clock_time_millis, max);
    +    assert!(
    +        pool.run_until(rtc.advance_time(Duration::from_millis(1)))
    +            .is_err()
    +    );
    +    assert_eq!(rtc.save().unwrap().clock_time_millis, max);
    +}
    +
    +#[test]
    +fn advance_time_rejects_extreme_downtime_with_system_clock() {
    +    use crate::cmos_rtc::Rtc;
    +    use local_clock::LocalClockDelta;
    +    use local_clock::SystemTimeClock;
    +    use vmcore::line_interrupt::LineInterrupt;
    +    use vmcore::vmtime::VmTime;
    +    use vmcore::vmtime::VmTimeKeeper;
    +
    +    let mut pool = pal_async::DefaultPool::new();
    +    let driver = pool.driver();
    +    let keeper = VmTimeKeeper::new(&driver, VmTime::from_100ns(0));
    +    let source = pool.run_until(keeper.builder().build(&driver)).unwrap();
    +    let mut rtc = Rtc::new(
    +        Box::new(SystemTimeClock::new(LocalClockDelta::ZERO)),
    +        LineInterrupt::detached(),
    +        &source,
    +        0x32,
    +        None,
    +        false,
    +    );
    +    let now = rtc.save().unwrap().clock_time_millis;
    +    assert!(
    +        pool.run_until(rtc.advance_time(Duration::from_millis((i64::MAX - now - 2) as u64)))
    +            .is_err()
    +    );
    +    let read = rtc.save().unwrap().clock_time_millis;
    +    assert!((now..now + 60_000).contains(&read));
    +    let month = Duration::from_secs(30 * 24 * 60 * 60);
    +    pool.run_until(rtc.advance_time(month)).unwrap();
    +    assert!(rtc.save().unwrap().clock_time_millis >= now + month.as_millis() as i64);
    +}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions