Trace native Chrony denial to the new peer namespace without opening quality gates
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local-only builder of a fixed diagnostic example, never a target operator."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import tarfile
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CASE = '5b358997-3abc-43db-945f-f41855b4e3c0'
|
||||
ARCHIVE = ROOT / 'devstate/server-time-source-bootstrap' / CASE / 'source.tar'
|
||||
ARCHIVE_SHA = '0da5ed0d52d3e621ef6a23cbc065f9d7c93e5683547e0a02ae3c8da8a83884a5'
|
||||
MANIFEST_SHA = 'bdf7839f832e2ea0cf230a0bd8a8fbff5d4a72d8fb7ba8208e0d252bad4b56ee'
|
||||
NATIVE_SHA = '3fd9c7a969a583abf97e29165135a8c1044db5c951ad8bd4dbfee3ee77e7ccdc'
|
||||
TRACKING_SHA = '7b042a24f38df53d3d553186d04bf6366c30fb77fe5c8ad66dfcf91290445297'
|
||||
EXAMPLE = 'crates/time-source-linux/examples/operator_error_probe.rs'
|
||||
PHASE = 'provider-error-diagnostic-v1'
|
||||
|
||||
PROBE = r'''// Standalone diagnostic only: no free error text, caller context or authority.
|
||||
use std::{collections::BTreeSet, fmt::{self, Write as _}};
|
||||
|
||||
const KNOWN_TAGS: &[&str] = &[
|
||||
__KNOWN_TAGS__
|
||||
];
|
||||
|
||||
struct TagSink {
|
||||
token: [u8; 96],
|
||||
used: usize,
|
||||
long_token: bool,
|
||||
remaining: usize,
|
||||
tags: BTreeSet<&'static str>,
|
||||
truncated: bool,
|
||||
}
|
||||
impl TagSink {
|
||||
fn new() -> Self {
|
||||
Self { token: [0; 96], used: 0, long_token: false, remaining: 4096,
|
||||
tags: BTreeSet::new(), truncated: false }
|
||||
}
|
||||
fn end_token(&mut self) {
|
||||
if !self.long_token && let Ok(token) = std::str::from_utf8(&self.token[..self.used])
|
||||
&& let Ok(index) = KNOWN_TAGS.binary_search(&token)
|
||||
{
|
||||
if self.tags.len() < 16 || self.tags.contains(KNOWN_TAGS[index]) {
|
||||
self.tags.insert(KNOWN_TAGS[index]);
|
||||
} else { self.truncated = true; }
|
||||
}
|
||||
self.used = 0;
|
||||
self.long_token = false;
|
||||
}
|
||||
}
|
||||
impl fmt::Write for TagSink {
|
||||
fn write_str(&mut self, text: &str) -> fmt::Result {
|
||||
for byte in text.bytes() {
|
||||
if self.remaining == 0 {
|
||||
// Discard an incomplete token: a truncated prefix is no tag.
|
||||
self.used = 0;
|
||||
self.long_token = true;
|
||||
self.truncated = true;
|
||||
return Err(fmt::Error);
|
||||
}
|
||||
self.remaining -= 1;
|
||||
if byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_' {
|
||||
if self.used < self.token.len() && !self.long_token {
|
||||
self.token[self.used] = byte;
|
||||
self.used += 1;
|
||||
} else { self.long_token = true; }
|
||||
} else { self.end_token(); }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if std::env::args_os().len() != 1 { std::process::exit(2); }
|
||||
let result = (|| -> anyhow::Result<()> {
|
||||
let mut source = rmm_time_source_linux::NativeTimeSource::open()?;
|
||||
let _ = source.sample()?;
|
||||
Ok(())
|
||||
})();
|
||||
let succeeded = result.is_ok();
|
||||
let mut sink = TagSink::new();
|
||||
let mut codes = BTreeSet::new();
|
||||
let mut count = 0u8;
|
||||
if let Err(error) = result {
|
||||
for (index, cause) in error.chain().take(17).enumerate() {
|
||||
if index == 16 { sink.truncated = true; break; }
|
||||
count += 1;
|
||||
if let Some(code) = cause.downcast_ref::<std::io::Error>().and_then(|e| e.raw_os_error()) {
|
||||
if codes.len() < 8 || codes.contains(&code) { codes.insert(code); }
|
||||
else { sink.truncated = true; }
|
||||
}
|
||||
// Display is consumed only by this bounded filtering sink. Never
|
||||
// make, retain, print or serialize a free-form error string.
|
||||
let _ = write!(&mut sink, "{cause}");
|
||||
sink.end_token();
|
||||
}
|
||||
}
|
||||
println!("{}", serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"profile": "rmm.native-source-error.once.v1",
|
||||
"provider_call_succeeded": succeeded,
|
||||
"known_error_tags": sink.tags.into_iter().collect::<Vec<_>>(),
|
||||
"os_error_codes": codes.into_iter().collect::<Vec<_>>(),
|
||||
"cause_count": count,
|
||||
"truncated": sink.truncated,
|
||||
"clock_authority": false,
|
||||
"source_quality_qualified": false,
|
||||
"signed_attestation": false
|
||||
}));
|
||||
if !succeeded { std::process::exit(1); }
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def require(ok, reason):
|
||||
if not ok:
|
||||
raise RuntimeError(reason)
|
||||
|
||||
|
||||
def encoded(value):
|
||||
return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True) + '\n').encode('ascii')
|
||||
|
||||
|
||||
def build_source():
|
||||
info = ARCHIVE.lstat()
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_uid == os.getuid()
|
||||
and stat.S_IMODE(info.st_mode) == 0o600 and info.st_size == 225280, 'private_original_archive')
|
||||
raw = ARCHIVE.read_bytes()
|
||||
require(sha(raw) == ARCHIVE_SHA, 'exact_original_source_archive')
|
||||
with tarfile.open(fileobj=io.BytesIO(raw), mode='r:') as archive:
|
||||
manifest_raw = archive.extractfile('manifest.json').read()
|
||||
require(sha(manifest_raw) == MANIFEST_SHA, 'original_manifest_bytes')
|
||||
manifest = json.loads(manifest_raw)
|
||||
sources = {}
|
||||
for item in manifest['package_files']:
|
||||
data = archive.extractfile(item['path']).read()
|
||||
require(len(data) == item['bytes'] and sha(data) == item['sha256'], 'unchanged_original_package')
|
||||
sources[item['path']] = data
|
||||
require(sha(sources['crates/time-source-linux/src/native.rs']) == NATIVE_SHA and
|
||||
sha(sources['crates/time-source-linux/src/tracking.rs']) == TRACKING_SHA,
|
||||
'exact_unchanged_provider_and_tracking_sources')
|
||||
tags = set()
|
||||
for name in ('native', 'tracking', 'lib'):
|
||||
tags.update(re.findall(rb'"((?:TIME|CHRONY)_[A-Z0-9_]+)', sources[f'crates/time-source-linux/src/{name}.rs']))
|
||||
require(1 <= len(tags) <= 128 and all(len(tag) <= 96 for tag in tags)
|
||||
and any(tag.startswith(b'CHRONY_') for tag in tags), 'closed_original_error_tag_enum')
|
||||
table = '\n'.join(' "' + tag.decode('ascii') + '",' for tag in sorted(tags))
|
||||
example = PROBE.replace('__KNOWN_TAGS__', table).encode('ascii')
|
||||
require(len(example) <= 16384 and '__KNOWN_TAGS__' not in example.decode(), 'bounded_fixed_example')
|
||||
return example, [tag.decode('ascii') for tag in sorted(tags)]
|
||||
|
||||
|
||||
def prepare():
|
||||
example, tags = build_source()
|
||||
os.umask(0o077)
|
||||
folder = ROOT / 'devstate/server-time-source-error-probe' / str(uuid.uuid4())
|
||||
folder.mkdir(parents=True, mode=0o700)
|
||||
def write(name, data):
|
||||
with (folder / name).open('xb') as stream:
|
||||
stream.write(data); stream.flush(); os.fsync(stream.fileno())
|
||||
write('operator_error_probe.rs', example)
|
||||
manifest = dict(profile='rmm.server-time-source.error-probe-source.v1', original_case=CASE,
|
||||
own_target_phase=PHASE, original_source_tar_sha256=ARCHIVE_SHA, original_manifest_sha256=MANIFEST_SHA,
|
||||
unchanged_native_sha256=NATIVE_SHA, unchanged_tracking_sha256=TRACKING_SHA,
|
||||
generator_sha256=sha(Path(__file__).read_bytes()), example_path=EXAMPLE,
|
||||
example_sha256=sha(example), example_bytes=len(example), known_error_tags=tags,
|
||||
max_causes=16, max_tags=16, max_io_error_codes=8, max_formatted_input_bytes=4096,
|
||||
free_error_text=False, clock_authority=False, source_quality_qualified=False,
|
||||
target_executed=False, build_executed=False)
|
||||
write('manifest.json', encoded(manifest))
|
||||
fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try: os.fsync(fd)
|
||||
finally: os.close(fd)
|
||||
print(json.dumps(dict(path=str(folder), **manifest), sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command', choices=('prepare',))
|
||||
parser.parse_args()
|
||||
prepare()
|
||||
@@ -0,0 +1,294 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One fixed source-quality acceptance after independently observed DAC denial.
|
||||
|
||||
No transport, provisioning, original-phase retry, keys or broker installation.
|
||||
Run only as the root operator with python3 -I; uncertain execution is read only.
|
||||
"""
|
||||
import argparse
|
||||
import grp
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
CASE = '5b358997-3abc-43db-945f-f41855b4e3c0'
|
||||
PHASE = 'probe-dac-acceptance-v1'
|
||||
PROFILE = 'rmm.server-time-source.dac-acceptance.v1'
|
||||
PIN_CONTROLLER_SHA = 'fac85dd0399009af36f625232daa5b67ab7fda391dbf95229d4237c307b142ca'
|
||||
PIN_CONTROLLER = Path('/var/lib/rmm-time-source-operators') / PIN_CONTROLLER_SHA / 'pin_bootstrap.py'
|
||||
PIN_RESULT_SHA = 'd0a9ac7b46bdf4247c420f01d959c41d6620f7081c40629016d6866828884c4b'
|
||||
PUBLIC_PIN_SHA = '203f63f150026d345614ca53e641f248397166fbdeb1f28318fc5d7763317e0a'
|
||||
GROUP_RECEIPT_SHA = '4977876b935bed8903ce4c880a0d9c77c49cd2c7110551fbf854baeccbe64ea7'
|
||||
OLD_GROUP_PHASE = 'probe-group-acceptance-v1'
|
||||
OLD_GROUP_CONTROLLER_SHA = 'd04989ccf6d3e7b379a1b02f5fd3ce2545a3563fbce1368f33102f58a36f2dcf'
|
||||
OLD_GROUP_RESULT_SHA = '96b714e2e43aa13073317c310b213863a02f26dbf2e6c975dc0801ef621eccd5'
|
||||
OLD_GROUP_LOG_SHA = 'f80644630b09f50fdc731418dbe4f17fff32622910b3efd346a0369b75e985ef'
|
||||
OLD_GROUP_RECEIPT_SHA = '6923cc1893619f67ae8677b84f9cfea6d0edd554120e9139d843115e52aa7643'
|
||||
DAC_DIAGNOSTIC_RECEIPT_SHA = 'd999e5260cab3457a7a66603fdb0288615443628e5a28f31df9c1cecd3401ef5'
|
||||
ARTIFACT = dict(bytes=848632, sha256='216b4d6a0f29ef47576f5ccc469954623141e55d7b43bd73175c1d956363bbbd', elf_machine=183)
|
||||
BASE = Path('/var/lib/rmm-time-source-bootstrap') / CASE
|
||||
IMAGE = BASE / 'build/artifacts/operator_probe'
|
||||
OLD_UNIT = 'rmm-time-source-probe-' + CASE + '.service'
|
||||
UNIT = 'rmm-time-source-probe-dac-acceptance-' + CASE + '.service'
|
||||
SAMPLE_KEYS = {'profile', 'clock_authority', 'signed_attestation', 'captured_utc_ns',
|
||||
'server_error_ns', 'source_sync_age_ns', 'server_boot_id',
|
||||
'captured_monotonic_ns', 'sampled_boottime_ns', 'kernel_state'}
|
||||
|
||||
|
||||
def require(ok, reason):
|
||||
if not ok:
|
||||
raise RuntimeError(reason)
|
||||
|
||||
|
||||
def sha(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def load_pin_controller():
|
||||
# Bootstrap the already reviewed reader without following import paths or
|
||||
# executing a second, unchecked pathname read. All ancestors stay root-only writable.
|
||||
parent = os.open('/', os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
for part in PIN_CONTROLLER.parent.parts[1:]:
|
||||
info = os.fstat(parent)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_ancestry')
|
||||
child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
|
||||
os.close(parent)
|
||||
parent = child
|
||||
info = os.fstat(parent)
|
||||
require(info.st_uid == 0 and info.st_mode & 0o022 == 0, 'protected_controller_directory')
|
||||
fd = os.open(PIN_CONTROLLER.name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=parent)
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(before.st_mode) and before.st_uid == before.st_gid == 0 and
|
||||
before.st_nlink == 1 and stat.S_IMODE(before.st_mode) == 0o600 and
|
||||
before.st_size <= 128 * 1024, 'fixed_root_controller_file')
|
||||
raw = stream.read(128 * 1024 + 1)
|
||||
stable = lambda item: tuple(getattr(item, 'st_' + key) for key in
|
||||
('dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'mtime_ns', 'ctime_ns'))
|
||||
require(stable(before) == stable(os.fstat(stream.fileno())) ==
|
||||
stable(os.stat(PIN_CONTROLLER.name, dir_fd=parent, follow_symlinks=False)) and
|
||||
len(raw) == before.st_size and
|
||||
sha(raw) == PIN_CONTROLLER_SHA, 'exact_reviewed_pin_controller')
|
||||
finally:
|
||||
os.close(parent)
|
||||
module = importlib.util.module_from_spec(importlib.util.spec_from_loader('rmm_fixed_pin_reader', loader=None))
|
||||
module.__file__ = str(PIN_CONTROLLER)
|
||||
exec(compile(raw, str(PIN_CONTROLLER), 'exec'), module.__dict__)
|
||||
held = module.read_file(PIN_CONTROLLER, 128 * 1024)
|
||||
require(held[0] == raw, 'same_loaded_controller_bytes')
|
||||
return module, lambda: require(module.read_file(PIN_CONTROLLER, 128 * 1024) == held,
|
||||
'pin_controller_unchanged')
|
||||
|
||||
|
||||
def group_before_exec(old, log, rows, groups):
|
||||
require(type(old.get('exit_code')) is int and old['exit_code'] == 216 and log == b'' and
|
||||
old.get('sample') is None, 'original_216_empty_log_no_sample')
|
||||
require(groups == [{'gid': 989, 'name': '_chrony', 'present': True},
|
||||
{'gid': 10001, 'present': False}], 'actual_original_nss_group_condition')
|
||||
messages = [row.get('MESSAGE') for row in rows]
|
||||
require(any(type(text) is str and 'Failed to determine supplementary groups' in text for text in messages)
|
||||
and any(type(text) is str and 'Failed at step GROUP spawning ' + str(IMAGE) in text for text in messages)
|
||||
and any(str(row.get('EXIT_STATUS')) == '216' and row.get('EXIT_CODE') == 'exited' for row in rows),
|
||||
'original_unit_journal_confirms_pre_exec_group_failure')
|
||||
|
||||
|
||||
def failed_group_origin(value, log):
|
||||
require(value.get('original_case') == CASE and value.get('phase') == OLD_GROUP_PHASE and
|
||||
value.get('profile') == 'rmm.server-time-source.group-acceptance.v1' and
|
||||
value.get('controller_sha256') == OLD_GROUP_CONTROLLER_SHA and value.get('artifact') == ARTIFACT and
|
||||
type(value.get('exit_code')) is int and value['exit_code'] == 1 and value.get('sample') is None and
|
||||
value.get('source_quality_qualified') is False and value.get('clock_authority') is False and
|
||||
value.get('signed_attestation') is False and value.get('probe_log_sha256') == sha(log) == OLD_GROUP_LOG_SHA,
|
||||
'actual_prior_group_probe_remains_failed_without_source_quality')
|
||||
|
||||
|
||||
def sample_quality(sample, boot):
|
||||
require(type(sample) is dict and set(sample) == SAMPLE_KEYS and
|
||||
sample['profile'] == 'rmm.native-source-quality.once.v1' and
|
||||
sample['clock_authority'] is False and sample['signed_attestation'] is False and
|
||||
sample['server_boot_id'] == boot and str(uuid.UUID(boot)) == boot,
|
||||
'exact_non_authoritative_native_sample_schema_and_boot')
|
||||
for key, upper in (('captured_utc_ns', 2**63 - 1), ('server_error_ns', 500_000_000),
|
||||
('source_sync_age_ns', 3_600_000_000_000), ('captured_monotonic_ns', 2**64 - 1),
|
||||
('sampled_boottime_ns', 2**64 - 1), ('kernel_state', 4)):
|
||||
require(type(sample[key]) is int and 0 <= sample[key] <= upper, 'bounded_numeric_quality_sample')
|
||||
require(sample['captured_utc_ns'] > 0 and sample['captured_monotonic_ns'] > 0 and
|
||||
sample['sampled_boottime_ns'] >= sample['captured_monotonic_ns'], 'positive_native_time_domains')
|
||||
|
||||
|
||||
def probe_args():
|
||||
return ['systemd-run', '--quiet', '--wait', '--pipe', '--collect', '--unit=' + UNIT,
|
||||
'--property=Type=exec', '--property=User=root', '--property=Group=989',
|
||||
'--property=SupplementaryGroups=', '--property=NoNewPrivileges=yes',
|
||||
'--property=CapabilityBoundingSet=CAP_SYS_PTRACE CAP_DAC_OVERRIDE', '--property=AmbientCapabilities=',
|
||||
'--property=ProtectSystem=strict', '--property=ProtectHome=yes', '--property=PrivateTmp=yes',
|
||||
'--property=PrivateDevices=yes', '--property=RestrictAddressFamilies=AF_UNIX',
|
||||
'--property=IPAddressDeny=any',
|
||||
'--property=SystemCallFilter=~@debug ptrace process_vm_readv process_vm_writev',
|
||||
'--property=RuntimeMaxSec=3s', '--property=ReadWritePaths=/run/rmm-time-source/clients', str(IMAGE)]
|
||||
|
||||
|
||||
def host_read(pin):
|
||||
# No operator import, subprocess, NSS lookup, sockets, preflight or sample.
|
||||
records = {}
|
||||
for leaf in ('intent.json', 'before.json', 'group-before-exec.json', 'execution.json',
|
||||
'after.json', 'result.json', 'failure.json', 'probe.log'):
|
||||
try:
|
||||
raw, proof = pin.read_file(BASE / PHASE / leaf, 16384)
|
||||
records[leaf] = {'sha256': sha(raw), 'metadata': proof,
|
||||
'record': raw.decode('ascii') if leaf == 'probe.log' else pin.parsed(raw)}
|
||||
except FileNotFoundError:
|
||||
records[leaf] = None
|
||||
print(pin.encoded(dict(original_case=CASE, phase=PHASE, read_only=True, records=records)).decode('ascii'), end='')
|
||||
|
||||
|
||||
def host_probe(pin, pin_guard):
|
||||
case_fd = pin.directory(BASE)
|
||||
phase_fd = -1
|
||||
try:
|
||||
pin.absence(case_fd, PHASE)
|
||||
operator, operator_guard = pin.load_operator()
|
||||
original = pin.Original(BASE, operator, operator_guard)
|
||||
require(original.artifacts['examples/operator_probe'][:2] == (IMAGE, ARTIFACT), 'fixed_original_native_artifact')
|
||||
pin_raw, pin_proof = pin.read_file(BASE / 'pin/result.json')
|
||||
require(sha(pin_raw) == PIN_RESULT_SHA, 'actual_original_pin_result')
|
||||
pin_result = pin.parsed(pin_raw)
|
||||
old_raw, old_proof = pin.read_file(BASE / 'probe/result.json')
|
||||
old_log, old_log_proof = pin.read_file(BASE / 'probe/probe.log', 16384)
|
||||
old = pin.parsed(old_raw)
|
||||
require(old.get('artifact') == ARTIFACT and old.get('probe_log_sha256') == sha(old_log),
|
||||
'original_failed_probe_artifact_and_log')
|
||||
|
||||
group_records = {}
|
||||
for leaf in ('result.json', 'probe.log', 'before.json', 'after.json'):
|
||||
group_records[leaf] = pin.read_file(BASE / OLD_GROUP_PHASE / leaf, 16384)
|
||||
group_raw = group_records['result.json'][0]
|
||||
require(sha(group_raw) == OLD_GROUP_RESULT_SHA, 'exact_actual_failed_group_probe_result')
|
||||
previous_group = pin.parsed(group_raw)
|
||||
failed_group_origin(previous_group, group_records['probe.log'][0])
|
||||
require(previous_group['original_probe_result_sha256'] == sha(old_raw) and
|
||||
previous_group['public_pin_sha256'] == PUBLIC_PIN_SHA and
|
||||
previous_group['source_tar_sha256'] == original.source_sha and
|
||||
previous_group['manifest_sha256'] == original.manifest_sha, 'same_original_group_failure_context')
|
||||
for name in ('before', 'after'):
|
||||
require(previous_group[name + '_witness'] == dict(filename=name + '.json',
|
||||
sha256=sha(group_records[name + '.json'][0])), 'actual_prior_group_witness_links')
|
||||
|
||||
def fresh():
|
||||
pin_guard()
|
||||
actual_pin = original.fresh()
|
||||
for leaf, retained in group_records.items():
|
||||
require(pin.read_file(BASE / OLD_GROUP_PHASE / leaf, 16384) == retained,
|
||||
'original_failed_group_records_unchanged')
|
||||
require(pin.read_file(BASE / 'pin/result.json') == (pin_raw, pin_proof) and
|
||||
pin.read_file(BASE / 'probe/result.json') == (old_raw, old_proof) and
|
||||
pin.read_file(BASE / 'probe/probe.log', 16384) == (old_log, old_log_proof),
|
||||
'original_pin_and_failed_probe_records_unchanged')
|
||||
raw, proof = pin.read_file(pin.ETC / 'chrony-pin.json', 8192)
|
||||
require(sha(raw) == PUBLIC_PIN_SHA == pin_result['public_pin_sha256'] and
|
||||
raw == pin.encoded(actual_pin) and proof == pin_result['public_pin_metadata'],
|
||||
'actual_unchanged_public_pin_and_original_metadata')
|
||||
dirs = {}
|
||||
for path in (pin.ETC, pin.RUN, pin.RUN / 'clients'):
|
||||
fd = pin.directory(path)
|
||||
try:
|
||||
current = pin.stable_directory(os.fstat(fd))
|
||||
finally:
|
||||
os.close(fd)
|
||||
recorded = pin_result['targets'][str(path)]
|
||||
require(current == {key: recorded[key] for key in current}, 'original_runtime_directory_identity')
|
||||
dirs[str(path)] = current
|
||||
return dict(observation=original.expected, public_pin_sha256=PUBLIC_PIN_SHA,
|
||||
public_pin_metadata=proof, target_directories=dirs)
|
||||
|
||||
before = fresh()
|
||||
os.mkdir(PHASE, mode=0o700, dir_fd=case_fd)
|
||||
os.fsync(case_fd)
|
||||
phase_fd = os.open(PHASE, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=case_fd)
|
||||
own_raw, _ = pin.read_file(Path(__file__).absolute(), 128 * 1024)
|
||||
binding = dict(profile=PROFILE, original_case=CASE, phase=PHASE, unit=UNIT,
|
||||
controller_sha256=sha(own_raw), operator_sha256=pin.OPERATOR_SHA,
|
||||
pin_controller_sha256=PIN_CONTROLLER_SHA, public_pin_sha256=PUBLIC_PIN_SHA,
|
||||
source_tar_sha256=original.source_sha, manifest_sha256=original.manifest_sha,
|
||||
artifact=ARTIFACT, original_group_receipt_sha256=GROUP_RECEIPT_SHA,
|
||||
original_probe_result_sha256=sha(old_raw), pin_result_sha256=PIN_RESULT_SHA,
|
||||
original_group_acceptance_controller_sha256=OLD_GROUP_CONTROLLER_SHA,
|
||||
original_group_acceptance_result_sha256=OLD_GROUP_RESULT_SHA,
|
||||
original_group_acceptance_log_sha256=OLD_GROUP_LOG_SHA,
|
||||
original_group_acceptance_receipt_sha256=OLD_GROUP_RECEIPT_SHA,
|
||||
original_dac_diagnostic_receipt_sha256=DAC_DIAGNOSTIC_RECEIPT_SHA)
|
||||
pin.exclusive(phase_fd, 'intent.json', pin.encoded(dict(binding, once=True, no_retry=True)))
|
||||
groups = []
|
||||
for gid in (989, 10001):
|
||||
try:
|
||||
group = grp.getgrgid(gid)
|
||||
groups.append(dict(gid=gid, name=group.gr_name, present=True))
|
||||
except KeyError:
|
||||
groups.append(dict(gid=gid, present=False))
|
||||
boot = original.expected['boot_id']
|
||||
rows_raw = operator.run(['journalctl', '--unit=' + OLD_UNIT, '--boot=' + uuid.UUID(boot).hex,
|
||||
'--no-pager', '-n', '12', '-o', 'json'], timeout=10, limit=65536)
|
||||
rows = [pin.parsed(row) for row in rows_raw.splitlines()]
|
||||
group_before_exec(old, old_log, rows, groups)
|
||||
pin.exclusive(phase_fd, 'group-before-exec.json', pin.encoded(dict(
|
||||
unit=OLD_UNIT, boot_id=boot, original_receipt_sha256=GROUP_RECEIPT_SHA,
|
||||
original_probe_result_sha256=sha(old_raw), group_resolution=groups,
|
||||
journal_sha256=sha(rows_raw), pre_exec_group_failure=True)))
|
||||
pin.exclusive(phase_fd, 'before.json', pin.encoded(dict(binding, witness=before)))
|
||||
fresh() # Last source/runtime/pin guard before the single executable action.
|
||||
code = operator.long_command(probe_args(), BASE / PHASE / 'probe.log', 10)
|
||||
log_raw, _ = pin.read_file(BASE / PHASE / 'probe.log', 16384)
|
||||
execution = dict(binding, exit_code=code, probe_log_sha256=sha(log_raw))
|
||||
pin.exclusive(phase_fd, 'execution.json', pin.encoded(execution))
|
||||
after = fresh()
|
||||
require(before == after, 'all_original_runtime_boot_pin_source_witnesses_preserved')
|
||||
pin.exclusive(phase_fd, 'after.json', pin.encoded(dict(binding, witness=after)))
|
||||
sample = pin.parsed(log_raw) if code == 0 else None
|
||||
if code == 0:
|
||||
sample_quality(sample, boot)
|
||||
links = {}
|
||||
for name in ('before', 'after'):
|
||||
raw, _ = pin.read_file(BASE / PHASE / (name + '.json'), 16384)
|
||||
links[name + '_witness'] = dict(filename=name + '.json', sha256=sha(raw))
|
||||
result = dict(binding, **links, exit_code=code, sample=sample, probe_log_sha256=sha(log_raw),
|
||||
source_quality_qualified=code == 0, runtime_boot_pin_source_preserved=True,
|
||||
clock_authority=False, signed_attestation=False, signer_created=False,
|
||||
broker_started=False, http_deployed=False)
|
||||
pin.exclusive(phase_fd, 'result.json', pin.encoded(result))
|
||||
print(pin.encoded(result).decode('ascii'), end='')
|
||||
except Exception as error:
|
||||
if phase_fd >= 0:
|
||||
pin.exclusive(phase_fd, 'failure.json', pin.encoded(dict(profile=PROFILE, original_case=CASE,
|
||||
failed=True, exception_type=type(error).__name__, read_original_phase_only=True)))
|
||||
raise
|
||||
finally:
|
||||
if phase_fd >= 0:
|
||||
os.close(phase_fd)
|
||||
os.close(case_fd)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('command', choices=('host-probe', 'host-read'))
|
||||
args = parser.parse_args()
|
||||
require(sys.flags.isolated == 1 and os.geteuid() == 0 and os.uname().sysname == 'Linux' and
|
||||
os.uname().machine == 'aarch64', 'isolated_root_linux_aarch64_only')
|
||||
os.umask(0o077)
|
||||
pin, guard = load_pin_controller()
|
||||
if args.command == 'host-read':
|
||||
host_read(pin)
|
||||
else:
|
||||
host_probe(pin, guard)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception:
|
||||
print(json.dumps(dict(failed=True, read_original_phase_only=True)), flush=True)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user