Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
197 changes: 177 additions & 20 deletions crates/sandlock-core/src/time.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
// Time offset handler — calculates virtual time offset and handles absolute
// timer syscalls for time virtualization support.

use std::time::SystemTime;
use std::time::{Duration, SystemTime};

use crate::seccomp::notif::{read_child_mem, write_child_mem, NotifAction};
use crate::seccomp::notif::{id_valid, read_child_mem, write_child_mem, Deferred, NotifAction};
use crate::sys::structs::SeccompNotif;
use std::os::unix::io::RawFd;

const TIMER_ABSTIME: u64 = 1;
const NANOS_PER_SEC: i64 = 1_000_000_000;

// Monotonic clocks whose absolute deadlines need un-shifting
const CLOCK_MONOTONIC: u32 = 1;
const CLOCK_MONOTONIC_RAW: u32 = 4;
const CLOCK_MONOTONIC_COARSE: u32 = 6;
const CLOCK_BOOTTIME: u32 = 7;
/// How often a sleep the supervisor waits out for the child looks for a
/// signal that ends it early, or a child that is gone.
const SLEEP_CHECK: Duration = Duration::from_millis(20);

/// The clocks the vDSO stubs shift. An absolute deadline the child computed
/// from one of them carries the offset; every other clock reads real time.
fn is_shifted_clock(clockid: i64) -> bool {
clockid == libc::CLOCK_REALTIME as i64 || clockid == libc::CLOCK_REALTIME_COARSE as i64
}

/// Calculate the time offset in seconds.
/// offset = desired_start_time - current_real_time
Expand All @@ -36,9 +41,12 @@ fn epoch_secs(t: SystemTime) -> i64 {

/// Handle clock_nanosleep/timerfd_settime/timer_settime with TIMER_ABSTIME.
///
/// For absolute monotonic timers, the child computed the deadline using a
/// vDSO-shifted clock (offset was added). We subtract the offset here so the
/// kernel receives the correct real deadline.
/// An absolute deadline on CLOCK_REALTIME was computed from the vDSO-shifted
/// wall clock (offset added), so the offset is taken out and the real
/// deadline is what counts. clock_nanosleep is answered by the supervisor
/// sleeping until then; for the timers the kernel receives the real deadline
/// in the caller's itimerspec. The monotonic and CPU-time clocks are never
/// shifted, so their deadlines pass through untouched.
///
/// Continue safety (issue #27): every `Continue` in this function is safe.
/// This handler does virtual-time correctness, not access control — it never
Expand All @@ -60,23 +68,42 @@ pub(crate) fn handle_timer(notif: &SeccompNotif, time_offset: i64, notif_fd: Raw
}

if nr == libc::SYS_clock_nanosleep as i64 {
let clockid = (notif.data.args[0] & 0xFFFFFFFF) as u32;
// Only un-shift monotonic clocks (realtime is handled differently)
if clockid != CLOCK_MONOTONIC
&& clockid != CLOCK_MONOTONIC_RAW
&& clockid != CLOCK_MONOTONIC_COARSE
&& clockid != CLOCK_BOOTTIME
{
// The only shifted clock that can be slept on: the kernel refuses
// CLOCK_REALTIME_COARSE here with EOPNOTSUPP.
if notif.data.args[0] as i32 != libc::CLOCK_REALTIME {
return NotifAction::Continue;
}
// timespec is directly at args[2]
let ts_addr = notif.data.args[2];
if ts_addr == 0 {
return NotifAction::Continue;
}
adjust_tv_sec(notif_fd, notif.id, notif.pid, ts_addr, time_offset);
// Rewriting the deadline in place would leave the real one in the
// caller's timespec, and a caller that reuses it (a periodic loop, a
// retry after EINTR) would have it un-shifted a second time. So the
// timespec is only read, and the supervisor sleeps until the real
// deadline. One that can't be read or isn't valid goes to the kernel,
// which fails it as it would without time_start.
return match read_timespec(notif_fd, notif.id, notif.pid, ts_addr) {
Some((sec, nsec)) if sec >= 0 && (0..NANOS_PER_SEC).contains(&nsec) => {
let deadline = (i128::from(sec) - i128::from(time_offset))
* i128::from(NANOS_PER_SEC)
+ i128::from(nsec);
sleep_until(deadline, notif_fd, notif.id, notif.pid)
}
_ => NotifAction::Continue,
};
} else {
// timerfd_settime or timer_settime: it_value at offset 16 in itimerspec
// timerfd_settime or timer_settime: the clock was fixed when the timer
// was created, so look it up; it_value is at offset 16 in itimerspec.
let clockid = if nr == libc::SYS_timerfd_settime {
timerfd_clock(notif.pid, notif.data.args[0] as i32)
} else {
posix_timer_clock(notif.pid, notif.data.args[0] as i32)
};
if !clockid.is_some_and(is_shifted_clock) {
return NotifAction::Continue;
}
let itimerspec_addr = notif.data.args[2];
if itimerspec_addr == 0 {
return NotifAction::Continue;
Expand All @@ -93,6 +120,90 @@ pub(crate) fn handle_timer(notif: &SeccompNotif, time_offset: i64, notif_fd: Raw
NotifAction::Continue
}

/// Answer a clock_nanosleep once the wall clock reaches `deadline`, in
/// nanoseconds since the epoch. The deadline is checked against the wall clock
/// again on every wakeup, so the sleep follows the clock if it is set, like
/// the kernel's. As there, a signal the thread doesn't block ends the sleep
/// with EINTR: with WAIT_KILLABLE_RECV the kernel would not deliver it before
/// the notification is answered.
fn sleep_until(deadline: i128, notif_fd: RawFd, id: u64, tid: u32) -> NotifAction {
NotifAction::Defer(Deferred::patient(async move {
loop {
let left = deadline - now_nanos();
if left <= 0 {
return NotifAction::ReturnValue(0);
}
// A killed child leaves nobody to answer.
if id_valid(notif_fd, id).is_err() || signal_pending(tid) {
return NotifAction::Errno(libc::EINTR);
}
let nap = left.min(SLEEP_CHECK.as_nanos() as i128);
tokio::time::sleep(Duration::from_nanos(nap as u64)).await;
}
}))
}

fn now_nanos() -> i128 {
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(d) => d.as_nanos() as i128,
Err(e) => -(e.duration().as_nanos() as i128),
}
}

/// Whether thread `tid` has a signal pending that it doesn't block.
fn signal_pending(tid: u32) -> bool {
std::fs::read_to_string(format!("/proc/{tid}/status"))
.is_ok_and(|status| unblocked_signal_pending(&status))
}

/// From a /proc/<tid>/status: a signal pending for the thread or its process
/// that the thread doesn't block.
fn unblocked_signal_pending(status: &str) -> bool {
let mask = |name: &str| {
status
.lines()
.find_map(|line| line.strip_prefix(name))
.and_then(|v| u64::from_str_radix(v.trim(), 16).ok())
.unwrap_or(0)
};
(mask("SigPnd:") | mask("ShdPnd:")) & !mask("SigBlk:") != 0
}

/// The clock of timerfd `fd`, from the `clockid:` line of its fdinfo.
fn timerfd_clock(pid: u32, fd: i32) -> Option<i64> {
let info = std::fs::read_to_string(format!("/proc/{pid}/fdinfo/{fd}")).ok()?;
info.lines()
.find_map(|line| line.strip_prefix("clockid:"))
.and_then(|v| v.trim().parse().ok())
}

/// The clock of POSIX timer `id`, from the `ClockID:` line that follows its
/// `ID:` line in /proc/<pid>/timers.
fn posix_timer_clock(pid: u32, id: i32) -> Option<i64> {
let timers = std::fs::read_to_string(format!("/proc/{pid}/timers")).ok()?;
parse_timer_clock(&timers, id)
}

fn parse_timer_clock(timers: &str, id: i32) -> Option<i64> {
let mut lines = timers.lines();
lines.find(|line| line.strip_prefix("ID:").map(str::trim) == Some(&id.to_string()))?;
lines
.take_while(|line| !line.starts_with("ID:"))
.find_map(|line| line.strip_prefix("ClockID:"))
.and_then(|v| v.trim().parse().ok())
}

/// Read a timespec (tv_sec, tv_nsec) from child memory at `addr`.
fn read_timespec(notif_fd: RawFd, notif_id: u64, pid: u32, addr: u64) -> Option<(i64, i64)> {
let bytes = read_child_mem(notif_fd, notif_id, pid, addr, 16).ok()?;
if bytes.len() != 16 {
return None;
}
let sec = i64::from_ne_bytes(bytes[..8].try_into().unwrap());
let nsec = i64::from_ne_bytes(bytes[8..].try_into().unwrap());
Some((sec, nsec))
}

/// Read tv_sec from child memory at `addr`, subtract `offset`, write back.
fn adjust_tv_sec(notif_fd: RawFd, notif_id: u64, pid: u32, addr: u64, offset: i64) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rewrites the caller's timespec in place, so a reused deadline is un-shifted twice. A periodic loop (ts.tv_sec += 1; clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &ts, NULL)) or an EINTR retry with the same ts sleeps for decades on the second call. Pre-existing, but this PR makes it reachable for realtime clock_nanosleep. Could you restore the original value after the syscall (or keep the rewrite out of the child's view), and add a second iteration reusing the struct to the test?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, thanks. Restoring it after the syscall doesn't work with Continue, since the supervisor never sees the call come back, and writing the old value back right after the response would race the kernel's read. So I went the other way in bf364c2: for an absolute CLOCK_REALTIME clock_nanosleep the timespec is only read, and the supervisor sleeps until the real deadline in a patient deferral (like the FIFO open wait) and answers 0. Because WAIT_KILLABLE_RECV holds signals until the notification is answered, it checks every 20ms for a pending signal the thread doesn't block and answers EINTR, and it stops when the notification id goes invalid. One difference is that the wakeup goes through the tokio timer, so it's millisecond rather than microsecond precise.

The test now sleeps twice reusing the same struct, and also retries with the same struct after an EINTR. The reuse case hangs until the 30s guard on the previous commit, and the EINTR case fails without the signal check.

timerfd_settime and timer_settime still adjust the itimerspec in place, so reusing one there has the same problem. The timerfd one could be set on the child's behalf through pidfd_getfd, POSIX timers can't, so I left both as they were. Happy to do the timerfd part here or in a follow-up if you want it.

let bytes = match read_child_mem(notif_fd, notif_id, pid, addr, 8) {
Expand Down Expand Up @@ -158,9 +269,55 @@ mod tests {
assert_eq!(epoch_secs(t), -2);
}

#[test]
fn test_parse_timer_clock() {
let timers = "ID: 0\nsignal: 14/0000000000000000\nnotify: signal/pid.7\nClockID: 1\n\
ID: 1\nsignal: 14/0000000000000000\nnotify: signal/pid.7\nClockID: -6\n\
ID: 10\nsignal: 14/0000000000000000\nnotify: signal/pid.7\nClockID: 0\n";
assert_eq!(parse_timer_clock(timers, 0), Some(1));
assert_eq!(parse_timer_clock(timers, 1), Some(-6));
assert_eq!(parse_timer_clock(timers, 10), Some(0));
assert_eq!(parse_timer_clock(timers, 2), None);
}

#[test]
fn test_unblocked_signal_pending() {
let status = |pnd: &str, shd: &str, blk: &str| {
format!(
"Name:\tpython3\nSigQ:\t0/63432\nSigPnd:\t{pnd}\nShdPnd:\t{shd}\n\
SigBlk:\t{blk}\nSigIgn:\t0000000001001000\nSigCgt:\t0000000180000202\n"
)
};
let none = "0000000000000000";
// SIGUSR1 is bit 9 (1 << (10 - 1)), SIGALRM bit 13.
let usr1 = "0000000000000200";
let alrm = "0000000000002000";
assert!(!unblocked_signal_pending(&status(none, none, none)));
assert!(unblocked_signal_pending(&status(usr1, none, none)));
assert!(unblocked_signal_pending(&status(none, usr1, alrm)));
assert!(!unblocked_signal_pending(&status(alrm, none, alrm)));
assert!(!unblocked_signal_pending(&status(none, alrm, alrm)));
assert!(!unblocked_signal_pending(""));
}

#[test]
fn test_only_wall_clocks_are_shifted() {
assert!(is_shifted_clock(libc::CLOCK_REALTIME as i64));
assert!(is_shifted_clock(libc::CLOCK_REALTIME_COARSE as i64));
for clock in [
libc::CLOCK_MONOTONIC,
libc::CLOCK_MONOTONIC_RAW,
libc::CLOCK_BOOTTIME,
libc::CLOCK_PROCESS_CPUTIME_ID,
libc::CLOCK_TAI,
] {
assert!(!is_shifted_clock(clock as i64), "clock {clock}");
}
}

#[test]
fn test_adjust_arithmetic() {
// Monotonic clock: vDSO adds offset, so absolute deadline is shifted.
// Realtime clock: vDSO adds offset, so absolute deadline is shifted.
// Un-shifting: adjusted = original - offset
let offset: i64 = -3600; // 1 hour in past
let shifted_deadline: i64 = 1700000000;
Expand Down
91 changes: 91 additions & 0 deletions crates/sandlock-core/tests/integration/test_determinism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,94 @@ async fn test_hostname_virtualization_resists_path_bypasses() {
);
}
}

/// Only the wall clock is shifted under time_start: the vDSO adds the offset
/// to CLOCK_REALTIME and leaves the monotonic clocks alone. An absolute
/// deadline therefore needs the offset taken back out only when it was
/// computed from CLOCK_REALTIME. Python's time.sleep() sleeps to an absolute
/// CLOCK_MONOTONIC deadline, so shifting that one hung it for decades.
#[tokio::test]
async fn test_time_start_absolute_deadlines() {
let past = SystemTime::UNIX_EPOCH + Duration::from_secs(961027200);
let policy = Sandbox::builder()
.fs_read("/usr")
.fs_read("/lib")
.fs_read_if_exists("/lib64")
.fs_read("/bin")
.fs_read("/etc")
.fs_read("/proc")
.time_start(past)
.build()
.unwrap();
let script = r#"
import ctypes, errno, os, signal, threading, time
libc = ctypes.CDLL(None, use_errno=True)
CLOCK_REALTIME, CLOCK_MONOTONIC, TIMER_ABSTIME = 0, 1, 1
class Timespec(ctypes.Structure):
_fields_ = [('sec', ctypes.c_long), ('nsec', ctypes.c_long)]
def deadline(clock, delay):
t = time.clock_gettime_ns(clock) + int(delay * 1e9)
return Timespec(t // 10**9, t % 10**9)
def elapsed(f):
start = time.monotonic()
f()
return time.monotonic() - start
def nanosleep(clock):
# The second deadline is the first one moved on in the same struct, as a
# periodic loop does it.
ts = deadline(clock, 0.1)
for _ in range(2):
assert libc.clock_nanosleep(clock, TIMER_ABSTIME, ctypes.byref(ts), None) == 0
t = ts.sec * 10**9 + ts.nsec + 10**8
ts.sec, ts.nsec = t // 10**9, t % 10**9
def interrupted():
# A handled signal ends the sleep early, and the retry with the same
# struct still ends at the deadline.
ts = deadline(CLOCK_REALTIME, 0.3)
main = threading.main_thread().ident
threading.Timer(0.1, signal.pthread_kill, (main, signal.SIGUSR1)).start()
assert libc.clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, ctypes.byref(ts), None) == errno.EINTR
assert libc.clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, ctypes.byref(ts), None) == 0
def timerfd(clock):
fd = libc.timerfd_create(clock, 0)
assert fd >= 0, ctypes.get_errno()
ts = (Timespec * 2)(Timespec(0, 0), deadline(clock, 0.2))
assert libc.timerfd_settime(fd, TIMER_ABSTIME, ts, None) == 0, ctypes.get_errno()
os.read(fd, 8)
os.close(fd)
def posix_timer(clock):
timer = ctypes.c_void_p()
assert libc.timer_create(clock, None, ctypes.byref(timer)) == 0, ctypes.get_errno()
ts = (Timespec * 2)(Timespec(0, 0), deadline(clock, 0.2))
assert libc.timer_settime(timer, TIMER_ABSTIME, ts, None) == 0, ctypes.get_errno()
signal.sigwait({signal.SIGALRM})
libc.timer_delete(timer)
signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGALRM})
signal.signal(signal.SIGUSR1, lambda *_: None)
assert time.gmtime(time.time()).tm_year == 2000
# A deadline the kernel would refuse is still refused.
for sec, nsec in [(-1, 0), (0, 10**9)]:
bad = Timespec(sec, nsec)
assert libc.clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, ctypes.byref(bad), None) == errno.EINVAL, (sec, nsec)
for name, f in [('sleep', lambda: time.sleep(0.2)),
('nanosleep realtime', lambda: nanosleep(CLOCK_REALTIME)),
('nanosleep monotonic', lambda: nanosleep(CLOCK_MONOTONIC)),
('nanosleep interrupted', interrupted),
('timerfd realtime', lambda: timerfd(CLOCK_REALTIME)),
('timerfd monotonic', lambda: timerfd(CLOCK_MONOTONIC)),
('timer realtime', lambda: posix_timer(CLOCK_REALTIME)),
('timer monotonic', lambda: posix_timer(CLOCK_MONOTONIC))]:
took = elapsed(f)
assert 0.15 < took < 5, (name, took)
print('OK')
"#;
let result = tokio::time::timeout(
Duration::from_secs(30),
policy.clone().run(&["python3", "-c", script]),
)
.await
.expect("an absolute deadline was shifted and the sleep never ended")
.unwrap();
assert!(result.success(), "{}", result.stderr_str().unwrap_or(""));
assert_eq!(result.stdout_str().unwrap_or("").trim(), "OK");
}
Loading