Preserve rejected abstract Chrony transport and native kernel fixture evidence

This commit is contained in:
2026-11-15 11:09:54 +01:00
parent 2af5db16f1
commit 636362aea5
3 changed files with 534 additions and 112 deletions
+106 -112
View File
@@ -6,7 +6,7 @@ use std::ffi::CString;
use std::fs::File;
use std::io::Read;
use std::mem::{self, size_of, size_of_val};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use std::os::unix::fs::MetadataExt;
use uuid::Uuid;
@@ -429,11 +429,30 @@ fn address(path: &str) -> Result<(libc::sockaddr_un, libc::socklen_t)> {
(mem::offset_of!(libc::sockaddr_un, sun_path) + path.len() + 1) as _,
))
}
fn abstract_address(random: Uuid) -> (libc::sockaddr_un, libc::socklen_t) {
let name = format!("rmm-time-source-tracking-{}", random.simple());
let mut addr: libc::sockaddr_un = unsafe { mem::zeroed() };
addr.sun_family = libc::AF_UNIX as _;
// Leading NUL selects Linux's abstract namespace. The exact length excludes
// a trailing NUL: every byte after sun_path[0] belongs to the kernel name.
for (dst, src) in addr.sun_path[1..].iter_mut().zip(name.bytes()) {
*dst = src as _;
}
let len = mem::offset_of!(libc::sockaddr_un, sun_path) + 1 + name.len();
(addr, len as _)
}
fn bind_once(fd: RawFd, addr: &libc::sockaddr_un, len: libc::socklen_t) -> Result<()> {
ensure!(
unsafe { libc::bind(fd, (addr as *const libc::sockaddr_un).cast(), len) } == 0,
"TIME_CLIENT_BIND_ONCE"
);
Ok(())
}
struct Client {
fd: OwnedFd,
dir: OwnedFd,
name: String,
own: Option<Identity>,
address: libc::sockaddr_un,
address_len: libc::socklen_t,
}
impl Client {
fn open(gid: u32) -> Result<Self> {
@@ -458,62 +477,17 @@ impl Client {
0,
)
})?;
let name = format!("tracking-{}.sock", Uuid::new_v4().simple());
let mut value = Self {
// UUIDv4 uses the OS CSPRNG. A collision denies this observation: no new
// name, adoption, connect retry or filesystem cleanup is attempted.
let (abstract_addr, address_len) = abstract_address(Uuid::new_v4());
let value = Self {
fd,
dir,
name,
own: None,
address: abstract_addr,
address_len,
};
let (addr, len) = address(&format!("{CLIENT_DIR}/{}", value.name))?;
bound_dir(CLIENT_DIR, &value.dir, None)?;
ensure!(
unsafe {
libc::bind(
value.fd.as_raw_fd(),
(&addr as *const libc::sockaddr_un).cast(),
len,
)
} == 0,
"TIME_CLIENT_BIND_ONCE"
);
let mut own = socket_identity(value.dir.as_raw_fd(), &value.name)?;
ensure!(
own.uid == 0 && own.mode & libc::S_IFMT == libc::S_IFSOCK && own.links == 1,
"TIME_CLIENT_INITIAL_IDENTITY"
);
value.own = Some(own);
let name = cstr(&value.name)?;
ensure!(
unsafe {
libc::fchownat(
value.dir.as_raw_fd(),
name.as_ptr(),
0,
gid,
libc::AT_SYMLINK_NOFOLLOW,
)
} == 0,
"TIME_CLIENT_GROUP"
);
// Parent is root-write-only: no daemon or unprivileged process can swap
// the leaf between this identity capture and chmod.
ensure!(
unsafe { libc::fchmodat(value.dir.as_raw_fd(), name.as_ptr(), 0o660, 0) } == 0,
"TIME_CLIENT_MODE"
);
let next = socket_identity(value.dir.as_raw_fd(), &value.name)?;
ensure!(
next.dev == own.dev
&& next.ino == own.ino
&& next.uid == 0
&& next.gid == gid
&& next.mode & 0o7777 == 0o660
&& next.links == 1,
"TIME_CLIENT_READY_IDENTITY"
);
own = next;
value.own = Some(own);
bind_once(value.fd.as_raw_fd(), &value.address, value.address_len)?;
value.verify()?;
let yes: libc::c_int = 1;
ensure!(
@@ -543,21 +517,31 @@ impl Client {
}
fn verify(&self) -> Result<()> {
bound_dir(CLIENT_DIR, &self.dir, None)?;
let mut actual: libc::sockaddr_un = unsafe { mem::zeroed() };
let mut len = size_of::<libc::sockaddr_un>() as libc::socklen_t;
ensure!(
Some(socket_identity(self.dir.as_raw_fd(), &self.name)?) == self.own,
"TIME_CLIENT_REPLACED"
unsafe {
libc::getsockname(
self.fd.as_raw_fd(),
(&mut actual as *mut libc::sockaddr_un).cast(),
&mut len,
)
} == 0
&& len == self.address_len
&& actual.sun_family == self.address.sun_family
&& actual.sun_path == self.address.sun_path,
"TIME_CLIENT_ABSTRACT_IDENTITY"
);
Ok(())
}
fn cleanup(&mut self) -> Result<()> {
// Consume cleanup authority before any fallible work. Unknown cleanup
// never retries from Drop and never adopts a newly observed leaf.
let expected = self
.own
.take()
.context("TIME_CLIENT_CLEANUP_ALREADY_ATTEMPTED")?;
bound_dir(CLIENT_DIR, &self.dir, None)?;
unlink_owned(self.dir.as_raw_fd(), &self.name, expected)
fn cleanup(self) -> Result<()> {
self.verify()?;
// Consume descriptor ownership before close. Linux releases the fd even
// on a close error; retrying could close a reused descriptor. Any error
// leaves the source poisoned and cannot produce positive quality.
let fd = self.fd.into_raw_fd();
ensure!(unsafe { libc::close(fd) } == 0, "TIME_CLIENT_CLOSE_ONCE");
Ok(())
}
fn exchange(&self, sequence: u32, daemon: &Pin, start: Capture) -> Result<tracking::Tracking> {
let request = tracking::request(sequence);
@@ -654,27 +638,6 @@ impl Client {
tracking::reply(&packet, sequence)
}
}
fn unlink_owned(dir: RawFd, name: &str, expected: Identity) -> Result<()> {
ensure!(
socket_identity(dir, name)? == expected,
"TIME_CLIENT_CLEANUP_IDENTITY"
);
let name = cstr(name)?;
ensure!(
unsafe { libc::unlinkat(dir, name.as_ptr(), 0) } == 0,
"TIME_CLIENT_UNLINK"
);
Ok(())
}
impl Drop for Client {
fn drop(&mut self) {
// Lost identity is intentionally retained, never recursively removed.
if self.own.is_some() {
let _ = self.cleanup();
}
}
}
// Linux pathname DGRAM send requires socket write permission; read/execute
// bits grant no sending authority. Directory ancestry is separately held and
// verified. Neither group nor other may write this daemon-owned socket.
@@ -744,7 +707,7 @@ impl NativeTimeSource {
let first = kernel()?;
self.verify()?;
self.poisoned = true;
let mut client = Client::open(self.daemon.pin.daemon_gid)?;
let client = Client::open(self.daemon.pin.daemon_gid)?;
let random = Uuid::new_v4();
let sequence = u32::from_ne_bytes(random.as_bytes()[..4].try_into()?);
let report = client.exchange(sequence, &self.daemon.pin, before)?;
@@ -852,22 +815,14 @@ mod tests {
);
}
#[test]
fn socket_cleanup_preserves_replaced_name_and_removes_only_exact_own_inode() {
use std::os::unix::{fs::PermissionsExt, net::UnixDatagram};
let path = std::env::temp_dir().join(format!("rmm-time-source-unit-{}", Uuid::new_v4()));
std::fs::create_dir(&path).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap();
let dir = openat(
libc::AT_FDCWD,
path.to_str().unwrap(),
libc::O_RDONLY | libc::O_DIRECTORY,
)
.unwrap();
let old = UnixDatagram::bind(path.join("own.sock")).unwrap();
let expected = socket_identity(dir.as_raw_fd(), "own.sock").unwrap();
fn server_socket_protection_requires_pinned_owner_and_no_group_write() {
let server = Identity {
dev: 1,
ino: 2,
uid: 989,
gid: 989,
mode: libc::S_IFSOCK | 0o755,
..expected
links: 1,
};
assert!(protected_server_socket(server, server.uid, server.gid));
for mode in [0o775, 0o757] {
@@ -880,15 +835,54 @@ mod tests {
server.gid,
));
}
std::fs::rename(path.join("own.sock"), path.join("held.sock")).unwrap();
let new = UnixDatagram::bind(path.join("own.sock")).unwrap();
assert!(unlink_owned(dir.as_raw_fd(), "own.sock", expected).is_err());
assert!(path.join("own.sock").exists());
let current = socket_identity(dir.as_raw_fd(), "own.sock").unwrap();
unlink_owned(dir.as_raw_fd(), "own.sock", current).unwrap();
assert!(!path.join("own.sock").exists());
unlink_owned(dir.as_raw_fd(), "held.sock", expected).unwrap();
drop((old, new));
std::fs::remove_dir(&path).unwrap();
assert!(!protected_server_socket(server, 0, server.gid));
assert!(!protected_server_socket(server, server.uid, 0));
}
#[test]
fn abstract_address_is_exact_kernel_namespace_and_not_a_pathname() {
let (addr, len) = abstract_address(Uuid::from_bytes([0x17; 16]));
let name = b"rmm-time-source-tracking-17171717171717171717171717171717";
assert_eq!(addr.sun_family as i32, libc::AF_UNIX);
assert_eq!(addr.sun_path[0], 0);
assert_eq!(
addr.sun_path[1..=name.len()]
.iter()
.map(|v| *v as u8)
.collect::<Vec<_>>(),
name
);
assert_eq!(
len as usize,
mem::offset_of!(libc::sockaddr_un, sun_path) + 1 + name.len()
);
assert!((len as usize) < size_of::<libc::sockaddr_un>());
}
#[test]
fn abstract_bind_is_exclusive_and_close_releases_only_own_kernel_name() {
let socket = || {
fd_result(unsafe {
libc::socket(
libc::AF_UNIX,
libc::SOCK_DGRAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
0,
)
})
.unwrap()
};
let (addr, len) = abstract_address(Uuid::new_v4());
let first = socket();
bind_once(first.as_raw_fd(), &addr, len).unwrap();
let second = socket();
assert!(bind_once(second.as_raw_fd(), &addr, len).is_err());
let (other, other_len) = abstract_address(Uuid::new_v4());
let unrelated = socket();
bind_once(unrelated.as_raw_fd(), &other, other_len).unwrap();
let raw = first.into_raw_fd();
assert_eq!(unsafe { libc::close(raw) }, 0);
// A fresh socket can acquire the released name, while the unrelated
// held socket still excludes all others. No pathname was ever created.
bind_once(second.as_raw_fd(), &addr, len).unwrap();
let third = socket();
assert!(bind_once(third.as_raw_fd(), &other, other_len).is_err());
}
}
@@ -0,0 +1,317 @@
#!/usr/bin/env python3
"""Frozen six Linux source units only; no actual Chrony or kernel query; no updater service or Apply.
Prepare copies the source-frozen snapshot locally. Execute is one
root-only Cloud-VM fixture run. After any lost reply read the original case;
never execute it again or substitute another binary/source generation.
"""
import argparse
import base64
import hashlib
import inspect
import json
import os
from pathlib import Path
import stat
import uuid
import windows_msi_runtime_acceptance as support
ROOT = Path(__file__).resolve().parents[1]
ACCESS_ROOT = ROOT.parent / 'rust-discovery'
QUALIFICATION = ROOT / 'devstate/server-time-source-abstract-client/945ec634-f787-4496-b019-28f03949f58f'
STATE = ROOT / 'devstate/time-source-abstract-native-linux'
PROFILE = 'rmm.time-source.six-abstract-transport-units.v1'
RECEIPT_SHA = '082666f3d9c07ebda4e935d5a67d16d6a5d7b62963044a6c638f17ae0bc93d09'
INPUTS_SHA = 'd14487a2fd9403e385ea889c1720c31e50d462a8f786e4f07d11b7518b6d1bd9'
BINARY_SHA = 'de9591c30f71d5a46d38cdb799051a22cb17617f2089bce2f12b9864c395462d'
BINARY_BYTES = 1147336
TESTS = sorted(['native::tests::abstract_address_is_exact_kernel_namespace_and_not_a_pathname', 'native::tests::abstract_bind_is_exclusive_and_close_releases_only_own_kernel_name', 'native::tests::clock_brackets_reject_suspend_step_backwards_and_total_timeout', 'native::tests::server_socket_protection_requires_pinned_owner_and_no_group_write', 'tracking::tests::exact_packet_sequence_and_network_source', 'tracking::tests::signed_float_ceil_and_overflow_are_conservative'])
AGENT_SHA = '0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f'
HELPER_SHA = '79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf'
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def save_local(path, value):
support.save(path, value)
fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def copy_exact(source, destination, digest, size):
metadata = source.lstat()
support.require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1
and metadata.st_uid in (0, os.getuid()) and not metadata.st_mode & 0o002
and metadata.st_size == size and size <= 2 * 1024 * 1024, 'bounded regular frozen input')
raw = source.read_bytes()
support.require(sha(raw) == digest, 'frozen snapshot input hash')
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
support.private(destination.parent, True)
fd = os.open(destination, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
with os.fdopen(fd, 'wb') as stream:
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
fd = os.open(destination.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def verify_case(folder):
value = support.load(folder / 'manifest.json')
support.require(value['profile'] == PROFILE and value['tests'] == TESTS
and value['runner_sha256'] == sha(Path(__file__).read_bytes())
and value['receipt_sha256'] == RECEIPT_SHA and value['binary_sha256'] == BINARY_SHA
and value['binary_bytes'] == BINARY_BYTES, 'same original reviewed manifest')
support.require(sha((folder / 'receipt.json').read_bytes()) == RECEIPT_SHA
and sha((folder / 'inputs.json').read_bytes()) == INPUTS_SHA, 'original qualification provenance')
source = support.load(folder / 'inputs.json')['source_files']
support.require(len(source) == 14 and source == value['source_files'], 'exact frozen fourteen complete recipe inputs')
for item in source:
path = Path(item['path'])
support.require(not path.is_absolute() and '..' not in path.parts, 'fixed snapshot relative path')
file = folder / 'source' / path
support.private(file)
support.require(file.stat().st_size == item['bytes'] and sha(file.read_bytes()) == item['sha256'], 'retained source freeze')
binary = folder / 'time-contract-tests'; support.private(binary)
support.require(binary.stat().st_size == BINARY_BYTES and sha(binary.read_bytes()) == BINARY_SHA, 'original qualified test bytes')
for path, digest in value['transport_sources'].items():
support.require(sha((ROOT / path).read_bytes()) == digest, 'original strict transport source')
return value
def remote(p):
import base64
import hashlib
import json
import os
from pathlib import Path
import selectors
import signal
import stat
import subprocess
import time
import uuid
def require(ok, message):
if not ok:
raise RuntimeError(message)
def enc(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def create(path, raw, mode=0o600):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, mode)
with os.fdopen(fd, 'wb') as stream:
stream.write(raw); stream.flush(); os.fsync(stream.fileno())
fd = os.open(path.parent, os.O_DIRECTORY | os.O_RDONLY | os.O_NOFOLLOW)
try:
os.fsync(fd)
finally:
os.close(fd)
def run(args, timeout=20):
# Keep the owned group leader unreaped until its entire group has been
# cleaned up. Its PID therefore cannot be recycled before killpg.
child = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, start_new_session=True,
env={'PATH': '/usr/bin:/bin', 'LC_ALL': 'C', 'HOME': '/nonexistent'})
selector = selectors.DefaultSelector()
buffers = {'stdout': bytearray(), 'stderr': bytearray()}
deadline = time.monotonic() + timeout
try:
for stream, name in ((child.stdout, 'stdout'), (child.stderr, 'stderr')):
os.set_blocking(stream.fileno(), False); selector.register(stream, selectors.EVENT_READ, name)
while True:
require(time.monotonic() < deadline, 'owned native command timeout; read original case only')
for key, _ in selector.select(0.02):
raw = os.read(key.fileobj.fileno(), 4096)
if raw:
buffers[key.data].extend(raw)
require(len(buffers[key.data]) <= 65536, 'bounded native output')
else:
selector.unregister(key.fileobj)
ended = os.waitid(os.P_PID, child.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT)
if ended is not None:
# Child remains a zombie until finally: no PID/group reuse.
os.killpg(child.pid, signal.SIGKILL)
for key in list(selector.get_map().values()):
while True:
try:
raw = os.read(key.fileobj.fileno(), 4096)
except BlockingIOError:
break
if not raw:
break
buffers[key.data].extend(raw)
require(len(buffers[key.data]) <= 65536, 'bounded native output')
code = ended.si_status if ended.si_code == os.CLD_EXITED else -ended.si_status
return code, bytes(buffers['stdout']), bytes(buffers['stderr'])
finally:
os.killpg(child.pid, signal.SIGKILL)
child.wait()
selector.close(); child.stdout.close(); child.stderr.close()
def metadata_identity(value):
return (value.st_dev, value.st_ino, value.st_uid, value.st_gid, value.st_mode,
value.st_nlink, value.st_size, value.st_mtime_ns, value.st_ctime_ns)
def hashed(path, maximum, process_image=False):
fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | (0 if process_image else os.O_NOFOLLOW))
with os.fdopen(fd, 'rb') as stream:
before = os.fstat(stream.fileno()); require(stat.S_ISREG(before.st_mode) and before.st_size <= maximum, 'bounded witness file')
digest = hashlib.sha256(); total = 0
while True:
raw = stream.read(32768)
if not raw:
break
total += len(raw); require(total <= maximum, 'bounded witness hash'); digest.update(raw)
after = os.fstat(stream.fileno())
require(metadata_identity(before) == metadata_identity(after) and total == before.st_size, 'stable witness hash')
return before, digest.hexdigest()
def witness():
out = {'boot_id': Path('/proc/sys/kernel/random/boot_id').read_text().strip(), 'services': {}, 'files': {}}
release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line)
require(release.get('ID', '').strip('"') == 'ubuntu' and release.get('VERSION_ID', '').strip('"') == '24.04', 'fixed native Ubuntu24.04')
out['os'] = {'id': 'ubuntu', 'version': '24.04', 'machine': os.uname().machine, 'kernel': os.uname().release}
for name, uid, binary in (
('rmm-agent-remote.service', 993, p['agent_sha256']),
('rmm-helper-cloud.service', 0, p['helper_sha256']),
('rmm-full-maintenance-helper.service', 0, p['helper_sha256'])):
code, stdout, _ = run(['/usr/bin/systemctl', 'show', name, '-p', 'ActiveState', '-p', 'MainPID', '-p', 'UnitFileState', '-p', 'InvocationID'])
require(code == 0, 'existing service read')
service = dict(line.split('=', 1) for line in stdout.decode().splitlines())
pid = int(service['MainPID']); require(service['ActiveState'] == 'active' and pid > 1, 'three existing services active')
proc = Path('/proc', str(pid)); birth = (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19]
ids = {line.split(':')[0]: line.split()[1:] for line in (proc / 'status').read_text().splitlines() if line.startswith(('Uid:', 'Gid:'))}
metadata, image = hashed(proc / 'exe', 256 * 1024 * 1024, process_image=True)
current = (proc / 'exe').stat()
require(ids['Uid'] == [str(uid)] * 4 and ids['Gid'] == ['984'] * 4 and image == binary
and (metadata.st_dev, metadata.st_ino) == (current.st_dev, current.st_ino)
and (proc / 'stat').read_text().rsplit(') ', 1)[1].split()[19] == birth, 'current generation/account/image')
out['services'][name] = dict(service, birth=birth, image=image, ids=ids)
code, stdout, _ = run(['/usr/bin/systemctl', 'show', 'rmm-apt-helper.service', '-p', 'ActiveState', '-p', 'UnitFileState'])
apt = dict(line.split('=', 1) for line in stdout.decode().splitlines())
require(code == 0 and apt == {'ActiveState': 'inactive', 'UnitFileState': 'disabled'}, 'APT remains closed')
out['apt'] = apt
for name in ('/etc/rmm-remote/helper-general.json', '/etc/rmm-remote/helper-full-maintenance.json',
'/etc/rmm-remote/full-maintenance-helper-proof.json', '/etc/systemd/system/rmm-full-maintenance-helper.service'):
path = Path(name); metadata = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_uid == 0
and not metadata.st_mode & 0o022 and metadata.st_nlink == 1, 'protected known control')
current, digest = hashed(path, 65536)
require(metadata_identity(current) == metadata_identity(metadata), 'same known control file')
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode,
metadata.st_size, metadata.st_mtime_ns, metadata.st_ctime_ns, digest]
for name in ('/var/lib/rmm-helper/consumption.sqlite', '/var/lib/rmm-helper/executor.lock',
'/var/lib/rmm-agent-remote/journal.sqlite', '/var/lib/rmm-agent-remote/consumption.sqlite'):
path = Path(name); metadata = path.lstat()
require(not path.is_symlink() and stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1, 'existing state identity')
out['files'][name] = [metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid, metadata.st_mode]
return out
require(os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed Cloud Linux root contract fixtures')
ident = str(uuid.UUID(p['id'])); require(ident == p['id'], 'canonical original case')
folder = Path('/var/tmp') / ('rmm-time-source-abstract-units-linux-' + ident)
if p['action'] == 'read':
metadata = folder.lstat()
require(stat.S_ISDIR(metadata.st_mode) and not folder.is_symlink() and metadata.st_uid == 0
and stat.S_IMODE(metadata.st_mode) == 0o700, 'own original case only')
result = folder / 'result.json'
return {'read_only': True, 'id': ident, 'entered': (folder / 'entered.json').exists(),
'result': json.loads(result.read_bytes()) if result.exists() else None, 'current_witness': witness()}
require(p['action'] == 'execute', 'one fixed time contract action')
os.umask(0o077); folder.mkdir(mode=0o700)
create(folder / 'intent.json', enc({key: value for key, value in p.items() if key != 'binary_b64'}))
require(len(p['binary_b64']) == 1529784, 'bounded binary transfer')
raw = base64.b64decode(p['binary_b64'], validate=True)
require(len(raw) == 1147336 and hashlib.sha256(raw).hexdigest() == p['binary_sha256'], 'fixed six-unit binary')
binary = folder / 'time-contract-tests'; create(binary, raw, 0o700)
before = witness(); create(folder / 'before.json', enc(before))
command = ['/usr/bin/setpriv', '--reuid=0', '--regid=0', '--clear-groups', '--no-new-privs', str(binary)]
code, stdout, stderr = run(command + ['--list', '--format', 'terse'])
create(folder / 'list.stdout', stdout); create(folder / 'list.stderr', stderr)
require(code == 0 and stderr == b'', 'native list succeeded')
lines = stdout.decode().splitlines()
require(len(lines) == 6 and sorted(line[:-6] for line in lines if line.endswith(': test')) == p['tests'], 'exact six tests before any run')
create(folder / 'entered.json', enc({'id': ident, 'run_once': True, 'time_ns': time.time_ns()}))
code, stdout, stderr = run(command + ['--test-threads=1', '--nocapture'])
create(folder / 'run.stdout', stdout); create(folder / 'run.stderr', stderr)
after = witness(); create(folder / 'after.json', enc(after))
require(before == after and code == 0 and stderr == b''
and b'6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out' in stdout
and all((b'test ' + name.encode() + b' ... ok') in stdout for name in p['tests']), 'six native units and retained target state')
receipt = dict(id=ident, profile=p['profile'], passed=6, ignored=0, filtered=0, execution_uid=0, tests=p['tests'],
before=before, after=after, binary_sha256=p['binary_sha256'], source_receipt_sha256=p['receipt_sha256'],
source_manifest_sha256=p['manifest_sha256'], stdout_sha256=hashlib.sha256(stdout).hexdigest(),
no_rmm_jobs=True, no_apply=True, no_service_control=True, no_actual_source_query=True)
create(folder / 'result.json', enc(receipt)); return receipt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('prepare', 'execute', 'read')); parser.add_argument('--case')
args = parser.parse_args(); os.umask(0o077)
STATE.mkdir(mode=0o700, parents=True, exist_ok=True); support.private(STATE, True)
if args.action == 'prepare':
support.require(args.case is None, 'prepare one new local case')
receipt_path = QUALIFICATION / 'receipt.json'; support.private(receipt_path)
support.require(sha(receipt_path.read_bytes()) == RECEIPT_SHA, 'fixed source qualification receipt')
receipt = support.load(receipt_path); original = support.load(QUALIFICATION / 'inputs.json')['source_files']
support.require(sha((QUALIFICATION / 'inputs.json').read_bytes()) == INPUTS_SHA
and receipt['inputs_sha256'] == INPUTS_SHA and len(original) == 14
and receipt['result'] == 'LOCAL_RELEASE_PROVIDER6_ABSTRACT_TRANSPORT_PASS' and receipt['tests'] == 6
and receipt['test_names'] == TESTS
and receipt['native_source_sha256'] == '8d13ef64f1b7ce0991f3d52a8a42d7b096e9020a57d4ca21a16409a4492e3a39'
and receipt['codec_sha256'] == '807cac064b00760d9131dc2a44d01ad9770a3660f4acd5f8d2948bb0f9234d08'
and receipt['skips'] == 0 and receipt['filters'] == 0, 'reviewed six-test qualification')
ident = str(uuid.uuid4()); folder = STATE / ident; folder.mkdir(mode=0o700)
copy_exact(receipt_path, folder / 'receipt.json', RECEIPT_SHA, receipt_path.stat().st_size)
copy_exact(QUALIFICATION / 'inputs.json', folder / 'inputs.json', INPUTS_SHA, (QUALIFICATION / 'inputs.json').stat().st_size)
paths = set()
for item in original:
path = Path(item['path'])
support.require(not path.is_absolute() and '..' not in path.parts and str(path) not in paths, 'unique fixed frozen input')
paths.add(str(path)); copy_exact(QUALIFICATION / 'source' / path, folder / 'source' / path, item['sha256'], item['bytes'])
binary = QUALIFICATION / 'qualified-provider-tests'
support.require(receipt['artifacts'][0] == dict(path='qualified-provider-tests', bytes=BINARY_BYTES, sha256=BINARY_SHA), 'fixed original linked artifact')
copy_exact(binary, folder / 'time-contract-tests', BINARY_SHA, BINARY_BYTES)
transports = {path: sha((ROOT / path).read_bytes()) for path in ('deploy/windows_msi_runtime_acceptance.py', 'deploy/vm_access_check.py')}
save_local(folder / 'manifest.json', dict(id=ident, profile=PROFILE, runner_sha256=sha(Path(__file__).read_bytes()),
receipt_sha256=RECEIPT_SHA, binary_sha256=BINARY_SHA, binary_bytes=BINARY_BYTES,
source_files=original, tests=TESTS, transport_sources=transports))
verify_case(folder)
print(json.dumps({'id': ident, 'prepared_locally': True})); return
support.require(args.case is not None, 'original --case required')
ident = str(uuid.UUID(args.case)); support.require(ident == args.case, 'same canonical original case')
folder = STATE / ident; support.private(folder, True); verify_case(folder)
payload = dict(id=ident, action=args.action, profile=PROFILE, tests=TESTS, binary_sha256=BINARY_SHA,
receipt_sha256=RECEIPT_SHA, manifest_sha256=sha((folder / 'manifest.json').read_bytes()),
agent_sha256=AGENT_SHA, helper_sha256=HELPER_SHA)
if args.action == 'execute':
save_local(folder / 'execute-entered.json', {'once': True, 'no_retry': True})
payload['binary_b64'] = base64.b64encode((folder / 'time-contract-tests').read_bytes()).decode()
code = 'import json\n' + inspect.getsource(remote) + '\nprint(json.dumps(remote(' + repr(payload) + ')))\n'
response = support.transport(support.access_settings(ACCESS_ROOT, 'linux'), 'python3 -', code.encode(), folder)
save_local(folder / (args.action + '-' + str(uuid.uuid4()) + '.json'), response)
if args.action == 'read' and response['result'] is not None:
result = response['result']
support.require(result['id'] == ident and result['profile'] == PROFILE and result['tests'] == TESTS
and result['passed'] == 6 and result['ignored'] == 0 and result['filtered'] == 0
and result['binary_sha256'] == BINARY_SHA and result['source_receipt_sha256'] == RECEIPT_SHA
and result['no_actual_source_query'] is True
and result['source_manifest_sha256'] == sha((folder / 'manifest.json').read_bytes())
and response['current_witness'] == response['result']['after'], 'same-case retained native result')
print(json.dumps({'id': ident, 'action': args.action, 'passed': response.get('passed'),
'complete': response.get('result') is not None if args.action == 'read' else True, 'read_only': args.action == 'read'}))
if __name__ == '__main__':
main()
+111
View File
@@ -0,0 +1,111 @@
# Native Chrony client transport: abstract AF_UNIX
The native Linux source now binds one CSPRNG UUIDv4 name in the Linux abstract
AF_UNIX namespace. The leading NUL and exact sockaddr length select a kernel
name, without a trailing NUL or filesystem client socket. There is one bind
attempt. A collision fails the observation; the provider never adopts a name,
generates a replacement name after failure, or retries the request.
The root-protected `/run/rmm-time-source/clients` directory remains mandatory,
with its existing exact root/group/mode checks, held directory descriptor,
exclusive nonblocking flock and empty-directory precondition. Historical named
socket leftovers therefore still block the instance. The provider never deletes
or adopts them. Its own abstract address is checked with getsockname. Successful
observation explicitly consumes and closes the socket descriptor once before
returning quality; a close or verification error cannot return a qualified
sample. Drop closes remaining owned descriptors without an unlink or a close
retry. The source remains poisoned after a failed observation.
An abstract name grants no filesystem DAC authority. A different process could
reserve a guessed name first and deny bind, or cause denial of service. That
cannot create positive source quality: the kernel excludes a second bind, and
the source still connects only to the fixed protected Chrony pathname. The
pinned daemon PID, birth, image, UID/GID, held process identity, protected server
socket identity, exact single SCM_CREDENTIALS record, reply sequence and fixed
Tracking packet checks are unchanged. The monotonic/boottime/UTC brackets,
kernel-state, error, reference-age and signed-time contracts are unchanged.
The provider exposes no configurable endpoint, clock setter, signer, retry or
network transport.
The original named-client provider SHA
`3fd9c7a969a583abf97e29165135a8c1044db5c951ad8bd4dbfee3ee77e7ccdc`
and the original 5b build/failed GROUP, DAC and peer probe records remain
historical evidence. They are not overwritten or reclassified. Root's separate
abstract-connect-only diagnosis, receipt
`9bcdaa00b86346b85d73d5bb9d4e491ecd82ed108ca8ec8a0495f7ec19770d56`,
proved connect under the same two-capability profile without sending a
datagram. It did not produce a native quality sample. This transport change
requires its own published source build and native qualification before any
broker quality gate may open. It changes no AppArmor rule, ACL, capability,
Chrony service, public pin, signer key or RMM job.
Subsequent evidence blocks treating this implementation as a working Chrony
transport. Root's separate one-request diagnosis received no reply (receipt
`f82eef4fc7d8f7cab7971a835a68eef855f166c32cb2feaac191551188351881`).
The upstream Chrony 4.8/4.9 [socket.c](https://gitlab.com/chrony/chrony/-/raw/4.9/socket.c)
stores an AF_UNIX sender as `remote_addr.path`, then reconstructs the reply
address using `strlen` in `set_unix_sockaddr`. An abstract sender's leading NUL
therefore loses its random name. This source-level incompatibility explains the
observed connect/send success without a reply, subject to checking the installed
Chrony package's exact source. The local guards below prove kernel socket
semantics, not Chrony interoperability. No ARM quality acceptance or broker
installation may follow from these local results.
The local six-test qualification uses a frozen three-crate workspace, the held
original offline 70-package lock/recipe and current codec807 source. Two new
guards verify exact abstract sockaddr encoding and actual exclusive kernel bind
with release on close while an unrelated name stays reserved. The existing
clock-bracket and Tracking-parser guards remain; the obsolete filesystem-client
cleanup fixture is replaced by the retained server-socket protection guard.
Local tests do not call NativeTimeSource.open/sample, contact Chrony, or prove
ARM64 or real-server source quality. The existing ecb prepare flow can package
the newly published source tip after review; no handmade original manifest is
used.
Local qualification `945ec634-f787-4496-b019-28f03949f58f` actually passed six
default release lib tests (zero skipped/filtered), clippy with warnings denied,
rustfmt checking and the offline release operator-probe build. The release test
ELF is x86-64, 1,147,336 bytes, SHA256
`de9591c30f71d5a46d38cdb799051a22cb17617f2089bce2f12b9864c395462d`.
Its frozen receipt is
`082666f3d9c07ebda4e935d5a67d16d6a5d7b62963044a6c638f17ae0bc93d09`;
the provider source is
`8d13ef64f1b7ce0991f3d52a8a42d7b096e9020a57d4ca21a16409a4492e3a39`.
`deploy/time_source_abstract_linux_acceptance.py` provides only `prepare`, one
`execute`, and original-case `read`. It copies that exact frozen ELF and all
fourteen recipe/source inputs; it does not rebuild from a moving worktree. The
remote runner first requires the exact full six-test list, then runs the binary
without filters/skips. An intent precedes execution; local and remote case
creation reject repeats. Before/after witnesses bind the existing three RMM
service generations, protected controls, state-file identities and closed APT
service. Timeout cleanup targets only the held unreaped child group. It performs
no RMM job or native source query. After a lost reply, only the original `read`
is permitted. Local prepare of case
`b5e4e4cc-5bb7-441a-8c53-1fc2281e17e8` succeeded; target `execute` and `read`
remain unexecuted by this author and require Root's separate action.
## Actual Cloud-Linux fixture result; production candidate rejected
Root actually executed the six frozen guards in original case
`b5e4e4cc-5bb7-441a-8c53-1fc2281e17e8`:6PASS/0ignored/filtered,
receipt `fe989d8ec4d54d7416de2cb6301d6b87b897f4bfa33d1d03403e0968d83eec67`.
Separate original-case read receipt
`a7bdc39d3d448efbdf2711958ed2dea2aa74bb8b9ff0c7a8d970c414ad785a2a`
confirmed retained results and existing runtime witnesses. Independent source
review found no transport trust/lifecycle bypass. These are kernel fixture
results, not a successful Chrony integration.
A separate fixed read-only Tracking request actually sent exactly one104Byte
request through an exclusive abstract socket and received no reply within its
bound. Receipt `f82eef4fc7d8f7cab7971a835a68eef855f166c32cb2feaac191551188351881`.
Chrony4.8/4.9 source reconstructs the return Unix address as a C string; an
abstract name starts with NUL and is lost. This proves that the candidate
cannot provide the required reply transport with this implementation. No
additional AppArmor denial was observed in the filtered kernel audit.
The candidate is rejected for deployment. Its exact source and frozen six-test
proof are preserved as evaluation history. Production NativeTimeSource must
retain the prior named transport until a separately qualified compatible fix
is ready. No ARM64 build, signer, key, quality authority, client configuration
or RMM job was activated from this candidate.