Record real clock bootstrap failures and preserve isolated operators
Rust development slice / linux (push) Failing after 6s
Rust development slice / linux (push) Failing after 6s
This commit is contained in:
@@ -0,0 +1,665 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated time-source sourcepack and finite operator phases; no SSH/deploy/key setup.
|
||||
|
||||
Host phases are deliberately NOT invoked by prepare. Run them only through the
|
||||
operator's independently checked server transport. An uncertain phase is read,
|
||||
never repeated. This first slice does not provision pins, signer, or services.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import selectors
|
||||
import signal
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import tarfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROFILE = 'rmm.server-time-source.operator.v1'
|
||||
CRATES = ('time-attestation', 'time-source-linux', 'time-broker-linux')
|
||||
PACKAGES = tuple('rmm-' + name for name in CRATES)
|
||||
BUILDER = 'rust:1.99.1-bookworm'
|
||||
LOCAL_BUILDER = 'sha256:9a76ad3744ebfdddae96ca10001ce8291c1b332fb54c8df5eea0e8e999ac6fc6'
|
||||
RUNTIME = 'sha256:6f8383f7c762ac77ed1013c94eeafa2b76838c00aec358a375f5847645ea87ec'
|
||||
HOST_ROOT = Path('/var/lib/rmm-time-source-bootstrap')
|
||||
PROBE = b'''// Generated operator-only source-quality probe; no signer or caller context.
|
||||
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 sample = source.sample()?;
|
||||
println!("{}", serde_json::json!({
|
||||
"profile": "rmm.native-source-quality.once.v1",
|
||||
"clock_authority": false, "signed_attestation": false,
|
||||
"captured_utc_ns": sample.captured_utc_ns(),
|
||||
"server_error_ns": sample.server_error_ns(),
|
||||
"source_sync_age_ns": sample.source_sync_age_ns(),
|
||||
"server_boot_id": sample.server_boot_id(),
|
||||
"captured_monotonic_ns": sample.captured_monotonic_ns(),
|
||||
"sampled_boottime_ns": sample.sampled_boottime_ns(),
|
||||
"kernel_state": sample.kernel_state()
|
||||
}));
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() { eprintln!("TIME_SOURCE_OPERATOR_PROBE_DENIED"); std::process::exit(1); }
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def require(ok, reason):
|
||||
if not ok:
|
||||
raise RuntimeError(reason)
|
||||
|
||||
|
||||
def digest(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def encoded(value):
|
||||
return (json.dumps(value, sort_keys=True, separators=(',', ':')) + '\n').encode()
|
||||
|
||||
|
||||
def identifier(value):
|
||||
require(str(uuid.UUID(value)) == value and uuid.UUID(value).version == 4, 'canonical UUIDv4 case')
|
||||
return value
|
||||
|
||||
|
||||
def exclusive(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_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def regular(path, limit=16 * 1024 * 1024, single_link=True):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
before = os.fstat(stream.fileno())
|
||||
require(stat.S_ISREG(before.st_mode) and (not single_link or before.st_nlink == 1) and before.st_size <= limit,
|
||||
'bounded single-link regular file')
|
||||
raw = stream.read(limit + 1)
|
||||
after = os.fstat(stream.fileno())
|
||||
stable = lambda item: (item.st_dev, item.st_ino, item.st_uid, item.st_gid, item.st_mode,
|
||||
item.st_nlink, item.st_size, item.st_mtime_ns, item.st_ctime_ns)
|
||||
require(len(raw) <= limit and stable(before) == stable(after), 'stable bounded input')
|
||||
return raw
|
||||
|
||||
|
||||
def run(args, timeout=15, limit=1024 * 1024):
|
||||
# Fixed commands only; no shell, environment/configuration interpolation.
|
||||
result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, timeout=timeout, check=False)
|
||||
require(len(result.stdout) <= limit and len(result.stderr) <= limit, 'bounded command output')
|
||||
require(result.returncode == 0, 'fixed command failed: ' + args[0])
|
||||
return result.stdout
|
||||
|
||||
|
||||
def package_identity(package):
|
||||
return tuple(package.get(key) for key in ('name', 'version', 'source', 'checksum'))
|
||||
|
||||
|
||||
def lock_package(block):
|
||||
"""Fail-closed reader for Cargo's canonical lock-v4 package blocks, not TOML in general."""
|
||||
value, dependencies, inside = {}, [], False
|
||||
for line in block.strip().splitlines():
|
||||
if inside:
|
||||
if line == ']':
|
||||
inside = False
|
||||
else:
|
||||
require(line.startswith(' "') and line.endswith('",'), 'canonical lock dependency line')
|
||||
dependencies.append(json.loads(line.strip()[:-1]))
|
||||
elif line == 'dependencies = [':
|
||||
require('dependencies' not in value, 'unique dependency array')
|
||||
value['dependencies'] = dependencies
|
||||
inside = True
|
||||
else:
|
||||
match = re.fullmatch(r'(name|version|source|checksum) = ("[^"\\]*")', line)
|
||||
require(match and match[1] not in value, 'canonical unique lock package field')
|
||||
value[match[1]] = json.loads(match[2])
|
||||
require(not inside and 'name' in value and 'version' in value, 'complete lock package')
|
||||
if 'source' in value:
|
||||
require(value['source'] == 'registry+https://github.com/rust-lang/crates.io-index' and
|
||||
re.fullmatch('[0-9a-f]{64}', value.get('checksum', '')), 'locked crates.io checksum only')
|
||||
return value
|
||||
|
||||
|
||||
def subset_lock(raw):
|
||||
"""Preserve exact original lock blocks, selecting their dependency closure."""
|
||||
blocks = raw.decode().split('[[package]]')
|
||||
require(blocks[0] == '# This file is automatically @generated by Cargo.\n'
|
||||
'# It is not intended for manual editing.\nversion = 4\n\n', 'canonical Cargo lock v4 header')
|
||||
packages = [lock_package(block) for block in blocks[1:]]
|
||||
by_name = {}
|
||||
for item in packages:
|
||||
by_name.setdefault(item['name'], []).append(item)
|
||||
held = {}
|
||||
|
||||
def visit(item):
|
||||
identity = package_identity(item)
|
||||
if identity in held:
|
||||
return
|
||||
held[identity] = item
|
||||
for dependency in item.get('dependencies', []):
|
||||
parts = dependency.split(' ')
|
||||
matches = by_name[parts[0]]
|
||||
if len(parts) > 1:
|
||||
matches = [value for value in matches if value['version'] == parts[1]]
|
||||
if len(parts) > 2:
|
||||
matches = [value for value in matches if '(' + value.get('source', '') + ')' == parts[2]]
|
||||
require(len(matches) == 1, 'unambiguous locked dependency')
|
||||
visit(matches[0])
|
||||
|
||||
for name in PACKAGES:
|
||||
matches = by_name[name]
|
||||
require(len(matches) == 1 and 'source' not in matches[0], 'exact workspace package')
|
||||
visit(matches[0])
|
||||
selected = [block for block in blocks[1:]
|
||||
if package_identity(lock_package(block)) in held]
|
||||
output = (blocks[0] + ''.join('[[package]]' + block for block in selected)).encode()
|
||||
require({package_identity(lock_package(p)) for p in output.decode().split('[[package]]')[1:]} == set(held),
|
||||
'exact lock closure, no version/checksum changes')
|
||||
return output
|
||||
|
||||
|
||||
def workspace_recipe(root_raw):
|
||||
"""Reuse original workspace values verbatim; only members/dependency set shrink."""
|
||||
deps = ('anyhow', 'hex', 'rand', 'serde', 'serde_json', 'sha2', 'uuid')
|
||||
lines = root_raw.decode().splitlines()
|
||||
start = lines.index('[workspace.package]')
|
||||
end = lines.index('[workspace.dependencies]')
|
||||
package = '\n'.join(lines[start:end]).strip()
|
||||
dependency_lines = []
|
||||
for name in deps:
|
||||
selected = [line for line in lines[end + 1:] if line.startswith(name + ' = ')]
|
||||
require(len(selected) == 1, 'single original workspace dependency')
|
||||
dependency_lines.extend(selected)
|
||||
recipe = ('[workspace]\nresolver = "2"\nmembers = ' +
|
||||
json.dumps(['crates/' + name for name in CRATES]) + '\n\n' + package +
|
||||
'\n\n[workspace.dependencies]\n' + '\n'.join(dependency_lines) + '\n').encode()
|
||||
return recipe
|
||||
|
||||
|
||||
def compare_lock(original, generated):
|
||||
original_blocks = original.decode().split('[[package]]')
|
||||
generated_blocks = generated.decode().split('[[package]]')
|
||||
require(original_blocks[0] == generated_blocks[0], 'same canonical lock version')
|
||||
known = {package_identity(lock_package(block)) for block in original_blocks[1:]}
|
||||
selected = [lock_package(block) for block in generated_blocks[1:]]
|
||||
require(len(selected) == len({package_identity(item) for item in selected}) and
|
||||
all(package_identity(item) in known for item in selected),
|
||||
'every generated package version/source/checksum exists in public original lock')
|
||||
require({item['name'] for item in selected if 'source' not in item} == set(PACKAGES),
|
||||
'only three original workspace packages')
|
||||
return len(selected)
|
||||
|
||||
|
||||
def generate_lock(case, payload, original):
|
||||
workspace = case / 'lock-workspace'
|
||||
workspace.mkdir(mode=0o700)
|
||||
for name, raw in payload.items():
|
||||
path = workspace / name
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
exclusive(path, raw)
|
||||
args = ['docker', 'run', '--rm', '--pull=never', '--network=none', '--read-only',
|
||||
'--tmpfs=/tmp:rw,nosuid,nodev,size=64m', '--cap-drop=ALL',
|
||||
'--security-opt=no-new-privileges', '--user', f'{os.getuid()}:{os.getgid()}',
|
||||
'-v', str(workspace) + ':/src:rw', '--entrypoint=cargo', LOCAL_BUILDER,
|
||||
'generate-lockfile', '--manifest-path', '/src/Cargo.toml', '--offline']
|
||||
result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, timeout=120, check=False)
|
||||
require(len(result.stdout) <= 1024 * 1024, 'bounded local Cargo lock generation output')
|
||||
exclusive(case / 'lock-generation.log', result.stdout)
|
||||
require(result.returncode == 0, 'local offline lock generation failed; retained original case log')
|
||||
os.chmod(workspace / 'Cargo.lock', 0o600)
|
||||
generated = regular(workspace / 'Cargo.lock')
|
||||
count = compare_lock(original, generated)
|
||||
# Cargo was allowed to alter only the generated lock file in this private recipe.
|
||||
for name, raw in payload.items():
|
||||
if name != 'Cargo.lock':
|
||||
require(regular(workspace / name) == raw, 'original copied source unchanged by lock generation')
|
||||
return generated, {'builder_image': LOCAL_BUILDER, 'offline': True,
|
||||
'package_count': count, 'log_sha256': digest(result.stdout)}
|
||||
|
||||
|
||||
def prepare(commit):
|
||||
require(re.fullmatch('[0-9a-f]{40}', commit) is not None, 'full public source commit')
|
||||
public = run(['git', '-C', str(ROOT), 'for-each-ref', '--format=%(objectname)', 'refs/remotes/origin/']).decode().splitlines()
|
||||
require(commit in public, 'checkpoint must be an already fetched origin branch tip')
|
||||
names = run(['git', '-C', str(ROOT), 'ls-tree', '-r', '--name-only', commit]).decode().splitlines()
|
||||
inputs = ['Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml']
|
||||
inputs += [name for name in names if any(name == f'crates/{crate}/Cargo.toml' or
|
||||
(name.startswith(f'crates/{crate}/src/') and name.endswith('.rs')) for crate in CRATES)]
|
||||
require(len(inputs) >= 12 and len(inputs) <= 24, 'bounded complete three-crate source set')
|
||||
source = {}
|
||||
for name in sorted(inputs):
|
||||
raw = run(['git', '-C', str(ROOT), 'show', commit + ':' + name])
|
||||
require(regular(ROOT / name) == raw, 'working input differs from public checkpoint: ' + name)
|
||||
source[name] = raw
|
||||
payload = dict(source)
|
||||
payload['Cargo.toml'] = workspace_recipe(source['Cargo.toml'])
|
||||
payload['Cargo.lock'] = subset_lock(source['Cargo.lock'])
|
||||
payload['crates/time-source-linux/examples/operator_probe.rs'] = PROBE
|
||||
state = ROOT / 'devstate/server-time-source-bootstrap'
|
||||
state.mkdir(parents=True, mode=0o700, exist_ok=True)
|
||||
require(state.stat().st_uid == os.getuid() and stat.S_IMODE(state.stat().st_mode) == 0o700,
|
||||
'private local case root')
|
||||
case = state / str(uuid.uuid4())
|
||||
case.mkdir(mode=0o700)
|
||||
payload['Cargo.lock'], lock_proof = generate_lock(case, payload, source['Cargo.lock'])
|
||||
# Provenance originals are not compiled, but their exact bytes travel with the pack.
|
||||
for name in ('Cargo.toml', 'Cargo.lock'):
|
||||
payload['provenance/' + name] = source[name]
|
||||
manifest = {'profile': PROFILE, 'public_commit': commit, 'builder': BUILDER,
|
||||
'operator_sha256': digest(Path(__file__).read_bytes()),
|
||||
'lock_generation': lock_proof,
|
||||
'source_files': [{'path': name, 'bytes': len(raw), 'sha256': digest(raw)}
|
||||
for name, raw in sorted(source.items())],
|
||||
'package_files': [{'path': name, 'bytes': len(raw), 'sha256': digest(raw)}
|
||||
for name, raw in sorted(payload.items())],
|
||||
'probe_only': True, 'provisioned': False}
|
||||
payload['manifest.json'] = encoded(manifest)
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode='w', format=tarfile.USTAR_FORMAT) as archive:
|
||||
for name, raw in sorted(payload.items()):
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size, item.mode, item.uid, item.gid, item.mtime = len(raw), 0o600, 0, 0, 0
|
||||
archive.addfile(item, io.BytesIO(raw))
|
||||
exclusive(case / 'source.tar', buffer.getvalue())
|
||||
exclusive(case / 'operator.py', Path(__file__).read_bytes())
|
||||
exclusive(case / 'manifest.json', encoded(manifest))
|
||||
receipt = {'case': case.name, 'source_tar_sha256': digest(buffer.getvalue()),
|
||||
'source_tar_bytes': len(buffer.getvalue()), 'manifest_sha256': digest(encoded(manifest)),
|
||||
'compiled': False, 'target_executed': False}
|
||||
exclusive(case / 'prepared.json', encoded(receipt))
|
||||
print(json.dumps({'path': str(case), **receipt}, sort_keys=True))
|
||||
|
||||
|
||||
def protected_dir(path, create=False):
|
||||
require(path.is_absolute(), 'absolute fixed operator path')
|
||||
current = Path('/')
|
||||
for part in path.parts[1:]:
|
||||
current /= part
|
||||
if create and not current.exists():
|
||||
current.mkdir(mode=0o700)
|
||||
info = current.lstat()
|
||||
require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and info.st_mode & 0o022 == 0,
|
||||
'root-owned protected directory ancestry')
|
||||
return path
|
||||
|
||||
|
||||
def host_case(value, create=False):
|
||||
require(os.geteuid() == 0 and os.uname().sysname == 'Linux' and os.uname().machine == 'aarch64',
|
||||
'root Linux ARM64 server only')
|
||||
protected_dir(HOST_ROOT, create=create)
|
||||
path = HOST_ROOT / identifier(value)
|
||||
if create:
|
||||
path.mkdir(mode=0o700)
|
||||
protected_dir(path)
|
||||
require(stat.S_IMODE(path.stat().st_mode) == 0o700, 'private operator case')
|
||||
return path
|
||||
|
||||
|
||||
def metadata(path):
|
||||
item = path.lstat()
|
||||
return {key: getattr(item, 'st_' + key) for key in ('dev', 'ino', 'uid', 'gid', 'mode', 'size', 'mtime_ns', 'ctime_ns')}
|
||||
|
||||
|
||||
def runtime_witness():
|
||||
names = ('gateway', 'api', 'postgres')
|
||||
result = {}
|
||||
for name in names:
|
||||
container = 'rust-discovery-server-' + name + '-1'
|
||||
# Never inspect Env, command arguments, health output, mounts or credentials.
|
||||
raw = run(['docker', 'inspect', '--format',
|
||||
'{{json .Image}} {{json .Config.User}} {{json .State.Running}} {{json .State.Pid}} {{json .State.StartedAt}} {{json .RestartCount}} {{json .NetworkSettings.Ports}}', container])
|
||||
# Multiple JSON values are deliberately decoded separately (spaces inside quoted dates/users are safe).
|
||||
decoder, values, text = json.JSONDecoder(), [], raw.decode().strip()
|
||||
while text:
|
||||
value, end = decoder.raw_decode(text)
|
||||
values.append(value)
|
||||
text = text[end:].lstrip()
|
||||
require(len(values) == 7 and values[2] is True and values[3] > 1, 'live expected runtime container')
|
||||
if name != 'postgres':
|
||||
require(values[0] == RUNTIME and values[1] == '10001:10001', 'fixed runtime image and user')
|
||||
for bindings in (values[6] or {}).values():
|
||||
require(bindings is None or (name != 'postgres' and all(x['HostIp'] == '127.0.0.1' for x in bindings)),
|
||||
'no public Docker port or PostgreSQL publication')
|
||||
result[name] = values
|
||||
return result
|
||||
|
||||
|
||||
def preflight():
|
||||
engine = run(['docker', 'version', '--format', '{{json .Server.Version}}']).decode().strip()
|
||||
image_values = json.loads(run(['docker', 'image', 'inspect', '--format',
|
||||
'[{{json .Id}},{{json .Architecture}},{{json .Os}}]', BUILDER]))
|
||||
image = dict(zip(('Id', 'Architecture', 'Os'), image_values, strict=True))
|
||||
# Inspect only public immutable image metadata, never Config/Env.
|
||||
require(image['Architecture'] == 'arm64' and image['Os'] == 'linux', 'cached ARM64 builder required')
|
||||
pid = int(run(['systemctl', 'show', 'chrony.service', '--property=MainPID', '--value']).strip())
|
||||
require(pid > 1, 'existing Chrony service PID')
|
||||
proc = Path('/proc') / str(pid)
|
||||
pidfd = os.pidfd_open(pid)
|
||||
try:
|
||||
status = regular(proc / 'status', 65536).decode()
|
||||
ids = {}
|
||||
for label in ('Uid', 'Gid'):
|
||||
match = re.search('^' + label + r':\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$', status, re.MULTILINE)
|
||||
require(match and len(set(match.groups())) == 1, 'fixed real/effective daemon IDs')
|
||||
ids[label.lower()] = int(match[1])
|
||||
birth = regular(proc / 'stat', 8192).decode().rsplit(')', 1)[1].split()[19]
|
||||
image_path = Path('/usr/sbin/chronyd')
|
||||
fixed = metadata(image_path)
|
||||
require(stat.S_ISREG(fixed['mode']) and fixed['uid'] == 0 and fixed['mode'] & 0o022 == 0,
|
||||
'protected Chrony executable')
|
||||
require(os.stat(proc / 'exe').st_ino == fixed['ino'] and os.stat(proc / 'exe').st_dev == fixed['dev'],
|
||||
'actual daemon fixed executable inode')
|
||||
image_hash = digest(regular(image_path))
|
||||
require(metadata(image_path) == fixed and
|
||||
regular(proc / 'stat', 8192).decode().rsplit(')', 1)[1].split()[19] == birth and
|
||||
int(run(['systemctl', 'show', 'chrony.service', '--property=MainPID', '--value']).strip()) == pid,
|
||||
'Chrony identity unchanged during probe')
|
||||
poll = __import__('select').poll()
|
||||
poll.register(pidfd, __import__('select').POLLIN)
|
||||
require(not poll.poll(0), 'Chrony process still alive')
|
||||
finally:
|
||||
os.close(pidfd)
|
||||
boot = regular(Path('/proc/sys/kernel/random/boot_id'), 128).decode().strip()
|
||||
require(str(uuid.UUID(boot)) == boot, 'kernel boot identity')
|
||||
return {'docker_engine_version': json.loads(engine),
|
||||
'builder': {key: image[key] for key in ('Id', 'Architecture', 'Os')},
|
||||
'runtime': runtime_witness(), 'boot_id': boot,
|
||||
'chrony_observation': {'schema_version': 1, 'daemon_pid': pid,
|
||||
'daemon_birth_ticks': int(birth), 'daemon_uid': ids['uid'], 'daemon_gid': ids['gid'],
|
||||
'daemon_image_sha256': image_hash},
|
||||
'chrony_image_metadata': fixed, 'pins_provisioned': False,
|
||||
'quality_sampled': False, 'registry_cache_verified': False}
|
||||
|
||||
|
||||
def unpack(case, expected):
|
||||
require(re.fullmatch('[0-9a-f]{64}', expected) is not None, 'exact operator-approved source hash')
|
||||
raw = regular(case / 'source.tar', 2 * 1024 * 1024)
|
||||
require(digest(raw) == expected, 'exact uploaded source archive')
|
||||
files = {}
|
||||
with tarfile.open(fileobj=io.BytesIO(raw), mode='r:') as archive:
|
||||
for member in archive.getmembers():
|
||||
require(member.isfile() and member.name not in files and member.size <= 1024 * 1024
|
||||
and not Path(member.name).is_absolute() and '..' not in Path(member.name).parts,
|
||||
'bounded regular unique archive entries')
|
||||
files[member.name] = archive.extractfile(member).read()
|
||||
require(len(files) <= 30 and 'manifest.json' in files, 'bounded source archive manifest')
|
||||
manifest = json.loads(files['manifest.json'])
|
||||
require(manifest['profile'] == PROFILE and manifest['builder'] == BUILDER and
|
||||
manifest['operator_sha256'] == digest(Path(__file__).read_bytes()), 'reviewed operator profile')
|
||||
require(set(files) == {'manifest.json'} | {x['path'] for x in manifest['package_files']}, 'exact manifest file set')
|
||||
originals = {x['path']: x for x in manifest['source_files']}
|
||||
for item in manifest['package_files']:
|
||||
require(len(files[item['path']]) == item['bytes'] and digest(files[item['path']]) == item['sha256'],
|
||||
'every source package hash and length')
|
||||
for name, item in originals.items():
|
||||
actual = files['provenance/' + name] if name in ('Cargo.toml', 'Cargo.lock') else files[name]
|
||||
require(len(actual) == item['bytes'] and digest(actual) == item['sha256'], 'unchanged original checkpoint input')
|
||||
require(files['Cargo.toml'] == workspace_recipe(files['provenance/Cargo.toml']) and
|
||||
compare_lock(files['provenance/Cargo.lock'], files['Cargo.lock']) == manifest['lock_generation']['package_count'] and
|
||||
manifest['lock_generation']['builder_image'] == LOCAL_BUILDER and
|
||||
manifest['lock_generation']['offline'] is True and
|
||||
files['crates/time-source-linux/examples/operator_probe.rs'] == PROBE,
|
||||
'exact generated recipe, lock closure, source-only probe')
|
||||
destination = case / 'workspace'
|
||||
destination.mkdir(mode=0o700)
|
||||
for name, value in sorted(files.items()):
|
||||
target = destination / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
exclusive(target, value)
|
||||
return {'source_tar_sha256': expected, 'manifest_sha256': digest(files['manifest.json']),
|
||||
'public_commit': manifest['public_commit'], 'package_files': manifest['package_files']}
|
||||
|
||||
|
||||
def verify_workspace(case):
|
||||
staged = json.loads(regular(case / 'stage' / 'result.json'))
|
||||
for item in staged['package_files']:
|
||||
raw = regular(case / 'workspace' / item['path'])
|
||||
require(digest(raw) == item['sha256'] and len(raw) == item['bytes'], 'original staged source bytes')
|
||||
return staged
|
||||
|
||||
|
||||
def long_command(args, log, timeout, cancel=None):
|
||||
fd = os.open(log, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
start_new_session=True)
|
||||
deadline, written = time.monotonic() + timeout, 0
|
||||
try:
|
||||
with selectors.DefaultSelector() as selector:
|
||||
selector.register(process.stdout, selectors.EVENT_READ)
|
||||
while selector.get_map():
|
||||
remaining = deadline - time.monotonic()
|
||||
require(remaining > 0, 'bounded command timeout; read original case only')
|
||||
events = selector.select(remaining)
|
||||
require(events, 'bounded command timeout; read original case only')
|
||||
raw = os.read(process.stdout.fileno(), 65536)
|
||||
if not raw:
|
||||
selector.unregister(process.stdout)
|
||||
break
|
||||
allowed = 8 * 1024 * 1024 - written
|
||||
stream.write(raw[:allowed])
|
||||
written += min(len(raw), allowed)
|
||||
require(len(raw) <= allowed, 'bounded command output exceeded; read original case only')
|
||||
remaining = deadline - time.monotonic()
|
||||
require(remaining > 0, 'bounded command timeout; read original case only')
|
||||
code = process.wait(timeout=remaining)
|
||||
except BaseException:
|
||||
# The leader is still our unreaped child: its process group cannot
|
||||
# have been recycled to an unrelated process.
|
||||
if process.returncode is None:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
process.wait()
|
||||
if cancel is not None:
|
||||
cancel()
|
||||
raise
|
||||
finally:
|
||||
process.stdout.close()
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
return code
|
||||
|
||||
|
||||
def cancel_owned_builder(cidfile, image_id, case_id):
|
||||
# No name-based/global docker kill. Missing/uncertain identity is reported;
|
||||
# the independent in-container 850s timeout remains the final bound.
|
||||
if not cidfile.exists():
|
||||
raise RuntimeError('no retained container ID; read original case, internal timeout remains')
|
||||
cid = regular(cidfile, 128).decode().strip()
|
||||
require(re.fullmatch('[0-9a-f]{64}', cid) is not None, 'exact own Docker container ID')
|
||||
inspected = subprocess.run(['docker', 'inspect', '--format',
|
||||
'[{{json .Id}},{{json .Image}},{{json .Name}},{{json (index .Config.Labels "rmm.time-source.case")}},{{json .State.Running}}]', cid],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=10, check=False)
|
||||
if inspected.returncode != 0:
|
||||
# --rm may already have removed our completed container. No fallback.
|
||||
return
|
||||
require(len(inspected.stdout) <= 4096, 'bounded own container metadata')
|
||||
identity = json.loads(inspected.stdout)
|
||||
require(identity[:4] == [cid, image_id, '/rmm-time-source-build-' + case_id, case_id],
|
||||
'exact retained own container/image/case identity before cancellation')
|
||||
if identity[4] is True:
|
||||
run(['docker', 'kill', '--signal=KILL', cid], timeout=10, limit=4096)
|
||||
|
||||
|
||||
def elf(path):
|
||||
raw = regular(path, 32 * 1024 * 1024)
|
||||
require(raw[:6] == b'\x7fELF\x02\x01' and struct.unpack('<H', raw[18:20])[0] == 183,
|
||||
'actual ELF64 little-endian AArch64 artifact')
|
||||
return {'bytes': len(raw), 'sha256': digest(raw), 'elf_machine': 183}
|
||||
|
||||
|
||||
def build(case, phase, fetch):
|
||||
staged = verify_workspace(case)
|
||||
original = json.loads(regular(case / 'preflight/result.json'))
|
||||
before = preflight()
|
||||
require(before['builder'] == original['builder'] and before['boot_id'] == original['boot_id'] and
|
||||
original['builder']['Architecture'] == 'arm64' and original['builder']['Os'] == 'linux' and
|
||||
re.fullmatch('sha256:[0-9a-f]{64}', original['builder']['Id']),
|
||||
'original preflight immutable builder and boot; no silent tag reimage')
|
||||
image_id = original['builder']['Id']
|
||||
target = phase / 'target'
|
||||
target.mkdir(mode=0o700)
|
||||
cidfile = phase / 'container.id'
|
||||
# All Cargo lock/cache writes belong to this fresh bounded home. Offline
|
||||
# may read the cached image registry; explicit fetch gets an empty registry.
|
||||
setup = 'set -eu; '
|
||||
if not fetch:
|
||||
setup += 'if test -d /usr/local/cargo/registry; then ln -s /usr/local/cargo/registry /cargo/registry; fi; '
|
||||
setup += 'exec cargo "$@"'
|
||||
args = ['docker', 'run', '--rm', '--pull=never', '--network', 'bridge' if fetch else 'none',
|
||||
'--read-only', '--cap-drop=ALL', '--security-opt=no-new-privileges', '--pids-limit=256',
|
||||
'--memory=2g', '--cpus=2', '--tmpfs=/tmp:rw,nosuid,nodev,size=256m',
|
||||
'--tmpfs=/cargo:rw,nosuid,nodev,size=512m,mode=0700', '-e', 'CARGO_HOME=/cargo',
|
||||
'-v', str(case / 'workspace') + ':/src:ro', '-v', str(target) + ':/out:rw',
|
||||
'--name=rmm-time-source-build-' + case.name,
|
||||
'--cidfile=' + str(cidfile),
|
||||
'--label=rmm.time-source.case=' + case.name,
|
||||
'-e', 'CARGO_TARGET_DIR=/out', '--entrypoint=/usr/bin/timeout', image_id,
|
||||
'--kill-after=3s', '850s', '/bin/sh', '-c', setup, 'rmm-fixed-cargo',
|
||||
'build', '--manifest-path', '/src/Cargo.toml', '--locked', '--release',
|
||||
'-p', 'rmm-time-broker-linux', '-p', 'rmm-time-source-linux', '--bins', '--examples']
|
||||
if not fetch:
|
||||
args.append('--offline')
|
||||
code = long_command(args, phase / 'build.log', 900,
|
||||
cancel=lambda: cancel_owned_builder(cidfile, image_id, case.name))
|
||||
after = preflight()
|
||||
require(before['runtime'] == after['runtime'] and before['boot_id'] == after['boot_id'],
|
||||
'RMM runtime metadata and boot preserved')
|
||||
verify_workspace(case)
|
||||
result = {'exit_code': code, 'registry_fetch_explicit': fetch, 'builder': before['builder'],
|
||||
'before': before, 'after': after, 'staged_manifest_sha256': staged['manifest_sha256'],
|
||||
'build_log_sha256': digest(regular(phase / 'build.log', 8 * 1024 * 1024)),
|
||||
'runtime_metadata_equal': True, 'native_source_quality_tested': False}
|
||||
if code == 0:
|
||||
# Cargo may hardlink release outputs to deps/. Copy exact immutable bytes
|
||||
# into fresh single-link root-owned artifacts before any probe execution.
|
||||
artifacts = phase / 'artifacts'
|
||||
artifacts.mkdir(mode=0o700)
|
||||
result['artifacts'] = {}
|
||||
for name in ('rmm-time-broker-linux', 'examples/operator_probe'):
|
||||
raw = regular(target / 'release' / name, 32 * 1024 * 1024, single_link=False)
|
||||
artifact = artifacts / Path(name).name
|
||||
exclusive(artifact, raw, mode=0o500)
|
||||
result['artifacts'][name] = elf(artifact)
|
||||
else:
|
||||
result['blocked'] = 'BUILD_FAILED_READ_LOG; offline cache is not assumed; no automatic retry/fetch'
|
||||
return result
|
||||
|
||||
|
||||
def probe(case, phase, expected):
|
||||
require(re.fullmatch('[0-9a-f]{64}', expected) is not None, 'operator-approved exact probe SHA')
|
||||
built = json.loads(regular(case / 'build' / 'result.json'))
|
||||
path = case / 'build/artifacts/operator_probe'
|
||||
artifact = elf(path)
|
||||
require(built['exit_code'] == 0 and artifact == built['artifacts']['examples/operator_probe']
|
||||
and artifact['sha256'] == expected, 'qualified original ARM64 source-only artifact')
|
||||
verify_workspace(case)
|
||||
# A previous provisioning action is a separate reviewed operation. Never synthesize pins here.
|
||||
protected_dir(Path('/etc/rmm-time-source'))
|
||||
pin = Path('/etc/rmm-time-source/chrony-pin.json')
|
||||
meta = metadata(pin)
|
||||
require(stat.S_ISREG(meta['mode']) and meta['uid'] == 0 and stat.S_IMODE(meta['mode']) == 0o600,
|
||||
'real protected Chrony pin required')
|
||||
protected_dir(Path('/run/rmm-time-source/clients'))
|
||||
before = preflight()
|
||||
args = ['systemd-run', '--quiet', '--wait', '--pipe', '--collect',
|
||||
'--unit=rmm-time-source-probe-' + case.name, '--property=Type=exec',
|
||||
'--property=User=root', '--property=Group=' + str(before['chrony_observation']['daemon_gid']),
|
||||
'--property=SupplementaryGroups=10001', '--property=NoNewPrivileges=yes',
|
||||
'--property=CapabilityBoundingSet=CAP_SYS_PTRACE', '--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(path)]
|
||||
code = long_command(args, phase / 'probe.log', 10)
|
||||
after = preflight()
|
||||
require(before['runtime'] == after['runtime'] and before['boot_id'] == after['boot_id'],
|
||||
'RMM runtime metadata and boot preserved')
|
||||
raw = regular(phase / 'probe.log', 16384)
|
||||
sample = None
|
||||
if code == 0:
|
||||
sample = json.loads(raw)
|
||||
require(sample['profile'] == 'rmm.native-source-quality.once.v1' and
|
||||
sample['clock_authority'] is False and sample['signed_attestation'] is False,
|
||||
'source-only single sample, no clock authority')
|
||||
return {'exit_code': code, 'artifact': artifact, 'before': before, 'after': after,
|
||||
'sample': sample, 'probe_log_sha256': digest(raw), 'runtime_metadata_equal': True,
|
||||
'signer_provisioned': False, 'broker_started': False, 'http_deployed': False}
|
||||
|
||||
|
||||
def host(args):
|
||||
case = host_case(args.case, create=args.command == 'host-preflight')
|
||||
if args.command == 'host-read':
|
||||
# No phase creation, Docker actions, signals or rerun. Read only original bounded case records.
|
||||
print(json.dumps({name: {'result': json.loads(regular(case / name / 'result.json'))
|
||||
if (case / name / 'result.json').exists() else None,
|
||||
'failure': json.loads(regular(case / name / 'failure.json'))
|
||||
if (case / name / 'failure.json').exists() else None,
|
||||
'intent_present': (case / name / 'intent.json').exists()}
|
||||
for name in ('preflight', 'stage', 'build', 'probe')}, sort_keys=True))
|
||||
return
|
||||
name = args.command.removeprefix('host-')
|
||||
phase = case / name
|
||||
phase.mkdir(mode=0o700) # An existing intent OR result never permits rerun.
|
||||
exclusive(phase / 'intent.json', encoded({'profile': PROFILE, 'case': case.name, 'phase': name,
|
||||
'operator_sha256': digest(Path(__file__).read_bytes()), 'started_unix_ns': time.time_ns()}))
|
||||
try:
|
||||
if name == 'preflight':
|
||||
result = preflight()
|
||||
elif name == 'stage':
|
||||
result = unpack(case, args.sha256)
|
||||
elif name == 'build':
|
||||
result = build(case, phase, args.registry_fetch)
|
||||
else:
|
||||
result = probe(case, phase, args.sha256)
|
||||
exclusive(phase / 'result.json', encoded(result))
|
||||
print(json.dumps({'case': case.name, 'phase': name, 'result': result}, sort_keys=True))
|
||||
except Exception as error:
|
||||
# Fixed controlled messages only; never write exception repr, paths from secrets, nested errors or env.
|
||||
exclusive(phase / 'failure.json', encoded({'failed': True, 'exception_type': type(error).__name__,
|
||||
'read_original_case_only': True}))
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
prepare_parser = commands.add_parser('prepare')
|
||||
prepare_parser.add_argument('--commit', required=True)
|
||||
for name in ('preflight', 'stage', 'build', 'probe', 'read'):
|
||||
command = commands.add_parser('host-' + name)
|
||||
command.add_argument('--case', required=True)
|
||||
if name in ('stage', 'probe'):
|
||||
command.add_argument('--sha256', required=True)
|
||||
if name == 'build':
|
||||
command.add_argument('--registry-fetch', action='store_true',
|
||||
help='explicit operator-authorized crates.io fetch using locked checksums; never OS updates')
|
||||
args = parser.parse_args()
|
||||
if args.command == 'prepare':
|
||||
prepare(args.commit)
|
||||
else:
|
||||
host(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,510 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fixed two-role raw Windows clock bootstrap; never an RMM job or calibration.
|
||||
|
||||
prepare is local only. Every mutation is create-once. After a lost reply use
|
||||
read on the original case; cleanup is separately explicit and stopped-only.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import system_pipe_upgrade as pipe
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
ACCESS_ROOT = ROOT.parent / 'rust-discovery'
|
||||
STATE = ROOT / 'devstate/windows-signed-clock-capture-native'
|
||||
QUALIFICATION = ROOT / 'devstate/windows-signed-clock/raw-capture-qualification-6bcd72a7-6de7-48e6-9e9b-3ad2cd3d9b09'
|
||||
RECEIPT_SHA = 'ba9ba8d88ed71952dd8dc803f2e38d5da72edeae392818cd320c6fd532ac7f4d'
|
||||
INPUTS_SHA = '2d21da4d137d2efd48cb2679fb791a9055839b042373d0f38c5af8d9ea8c5a8c'
|
||||
CAP_SHA = '91c75ba877764345b3267731f3880580d02a72df40420479e3c4b76d37064982'
|
||||
EXE_SHA = '601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'
|
||||
EXE_BYTES = 8566784
|
||||
NATIVE_CASE = ROOT / 'devstate/windows-raw-clock-native-linux/dcef489d-2a24-47cc-b3ca-6628545cdacf'
|
||||
LINUX_READ = NATIVE_CASE / 'read-80f83bff-183b-4697-80b2-9b96a8182e8d.json'
|
||||
LINUX_READ_SHA = '91a750e4de266f5effccbd418a680c1ba4f5e0aff5082489fc021922bdfcafa3'
|
||||
MAIN_CASE = ACCESS_ROOT / 'devstate/windows-client/system-pipe-upgrade/14fb176a-f653-4573-a8d7-6f9fe47a3020'
|
||||
MAIN_INTENT_SHA = '374adc97bec41bd798409f7c4f8c7716b085e20d2b6fb64b33f7ab675e6483e2'
|
||||
MAIN_RESULT_SHA = 'd5c4996821911a5bdac5014e9f985c56bbb592b803f2e33411dd28bb986b8eed'
|
||||
INDEX_SHAS = {'current-runtime.json': 'e49231e72aff7b001189b8507200c6c701f73e47f77c29194116cf1da41ca0c2',
|
||||
'current-components.json': '005317e652f50de3e1277be3bc42717318226208015e7c8011e1b73469cc7562'}
|
||||
ROOT_POLICY = 'cf15cbb68b590475df6def28e7dcffb7d88e0ca2d2555a06174fb654eeff05f4'
|
||||
PROFILE = 'rmm.windows.raw-clock.two-role-bootstrap.v1'
|
||||
STABLE = ('files', 'service', 'helper_service', 'agent_kernel', 'helper_kernel', 'helper_witness')
|
||||
JOURNAL = ('database_file_id', 'database_creation', 'identity_sha256', 'schema', 'core_counts')
|
||||
require = pipe.require
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def canonical(value):
|
||||
return json.dumps(value, ensure_ascii=True, separators=(',', ':'), sort_keys=True).encode()
|
||||
|
||||
|
||||
def private(path, directory=False):
|
||||
metadata = Path(path).lstat()
|
||||
require(metadata.st_uid == os.getuid() and stat.S_IMODE(metadata.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(metadata.st_mode) if directory else stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1), 'private own case')
|
||||
|
||||
|
||||
def load(path):
|
||||
private(path)
|
||||
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private evidence')
|
||||
return json.loads(Path(path).read_bytes(), object_pairs_hook=pipe.cb.contract.strict_object)
|
||||
|
||||
|
||||
def write(path, raw):
|
||||
private(path.parent, True)
|
||||
fd = os.open(path, 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(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def save(path, value):
|
||||
write(path, canonical(value))
|
||||
|
||||
|
||||
# Exact previously reviewed kernel-handle/account/image proof only. No original
|
||||
# replacement, stop/start, state or recovery functions are imported into SCRIPT.
|
||||
NATIVE_BASE = pipe.NATIVE.split("'@\nfunction FileIdentity", 1)[0]
|
||||
NATIVE = NATIVE_BASE + r'''
|
||||
public static class RmmCaptureControl {
|
||||
[DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern IntPtr OpenSCManager(string machine,string database,uint access);
|
||||
[DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern IntPtr CreateService(IntPtr manager,string name,string display,uint access,uint type,uint start,uint error,string command,string group,IntPtr tag,string dependencies,string account,string password);
|
||||
[DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern IntPtr OpenService(IntPtr manager,string name,uint access);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool CloseServiceHandle(IntPtr handle);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool ChangeServiceConfig2(IntPtr handle,uint level,ref uint value);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool StartService(IntPtr handle,uint count,IntPtr args);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool DeleteService(IntPtr handle);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool QueryServiceStatusEx(IntPtr handle,int level,out Status value,int size,out int needed);
|
||||
[DllImport("advapi32.dll",SetLastError=true)] static extern bool SetServiceObjectSecurity(IntPtr handle,uint info,IntPtr descriptor);
|
||||
[DllImport("advapi32.dll",SetLastError=true,CharSet=CharSet.Unicode)] static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string text,uint revision,out IntPtr descriptor,out uint size);
|
||||
[DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr value);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern IntPtr OpenProcess(uint access,bool inherit,int pid);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool TerminateProcess(RmmPipeNative.Held handle,uint code);
|
||||
[DllImport("kernel32.dll",SetLastError=true)] static extern bool GetExitCodeProcess(RmmPipeNative.Held handle,out uint code);
|
||||
[DllImport("kernel32.dll")] public static extern ulong GetTickCount64();
|
||||
[StructLayout(LayoutKind.Sequential)] public struct Status {public uint Type,State,Controls,Win32Exit,SpecificExit,Checkpoint,WaitHint,Pid,Flags;}
|
||||
public sealed class Service : SafeHandleZeroOrMinusOneIsInvalid {
|
||||
public Service(IntPtr value):base(true){SetHandle(value);}
|
||||
protected override bool ReleaseHandle(){return CloseServiceHandle(handle);}
|
||||
public Status Read(){Status s;int bytes;if(!QueryServiceStatusEx(handle,0,out s,Marshal.SizeOf(typeof(Status)),out bytes)||bytes!=Marshal.SizeOf(typeof(Status)))throw new Win32Exception();return s;}
|
||||
public void StartOnce(){if(!StartService(handle,0,IntPtr.Zero))throw new Win32Exception();}
|
||||
public void DeleteOnce(){if(!DeleteService(handle))throw new Win32Exception();}
|
||||
}
|
||||
static IntPtr Manager(uint access){IntPtr value=OpenSCManager(null,null,access);if(value==IntPtr.Zero)throw new Win32Exception();return value;}
|
||||
public static Service CreateOnce(string name,string command,string account){
|
||||
IntPtr manager=Manager(3);try{IntPtr value=CreateService(manager,name,name,0xf01ff,16,3,1,command,null,IntPtr.Zero,null,account,null);if(value==IntPtr.Zero)throw new Win32Exception();
|
||||
Service service=new Service(value);try{uint sid=1;if(!ChangeServiceConfig2(value,5,ref sid))throw new Win32Exception();IntPtr sd;uint size;if(!ConvertStringSecurityDescriptorToSecurityDescriptor("D:P(A;;GA;;;SY)(A;;GA;;;BA)",1,out sd,out size))throw new Win32Exception();try{if(!SetServiceObjectSecurity(value,4,sd))throw new Win32Exception();}finally{LocalFree(sd);}return service;}catch{service.Dispose();throw;}
|
||||
}finally{CloseServiceHandle(manager);}
|
||||
}
|
||||
public static Service OpenOwn(string name){IntPtr manager=Manager(1);try{IntPtr value=OpenService(manager,name,0x10015);if(value==IntPtr.Zero)throw new Win32Exception();return new Service(value);}finally{CloseServiceHandle(manager);}}
|
||||
public static RmmPipeNative.Held Hold(int pid){IntPtr value=OpenProcess(0x101001,false,pid);if(value==IntPtr.Zero)throw new Win32Exception();return new RmmPipeNative.Held(value);}
|
||||
public static void KillHeld(RmmPipeNative.Held process){if(!TerminateProcess(process,1460))throw new Win32Exception();}
|
||||
public static uint Exit(RmmPipeNative.Held process){uint code;if(!GetExitCodeProcess(process,out code))throw new Win32Exception();return code;}
|
||||
}
|
||||
'@
|
||||
'''
|
||||
|
||||
SCRIPT = r'''
|
||||
$ErrorActionPreference='Stop';$p=$global:RmmSignedClockCapturePayload
|
||||
if(!$p-or[guid]::ParseExact($p.id,'D').ToString()-cne$p.id-or$p.id-notmatch'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$'-or$p.profile-cne'rmm.windows.raw-clock.two-role-bootstrap.v1'-or$p.action-notin@('setup','start-local-service','start-system','read','cleanup-local-service','cleanup-system')-or$p.exe_sha256-cne'601c27a43fb67c662f926f9dc289a23a5c31c7e27f62901a77fc9ceaafaea7fb'-or$p.exe_bytes-ne8566784-or$p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed capture request'}
|
||||
if((($p.PSObject.Properties.Name|Sort-Object)-join',')-cne'action,exe_bytes,exe_sha256,id,manifest_sha256,profile,script_sha256'){throw 'Exact capture payload fields'}
|
||||
$base='C:\ProgramData\RustDiscoverySignedClockCapture';$case=Join-Path $base $p.id;$control=Join-Path $case 'control';$exe=Join-Path $case 'SignedClockCapture.exe';$boot='C:\ProgramData\RustDiscoveryBootstrap'
|
||||
$names=@('RmmSignedClockCaptureLocalService','RmmSignedClockCaptureSystem');$tags=@('local-service','system');$owners=@('S-1-5-19','S-1-5-18');$accounts=@('NT AUTHORITY\LocalService','LocalSystem');$sys='S-1-5-18';$admin='S-1-5-32-544'
|
||||
function HashBytes([byte[]]$raw){$h=[Security.Cryptography.SHA256]::Create();try{return([BitConverter]::ToString($h.ComputeHash($raw))).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}}
|
||||
function HashFile($path){return(Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()}
|
||||
function Check($path,[bool]$dir,[string[]]$readers=@(),[string[]]$writers=@()){
|
||||
$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular fixed fixture'};$parent=$i.Parent;if(!$dir){$parent=$i.Directory};while($null-ne$parent){if($parent.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Reparse ancestor'};$parent=$parent.Parent}
|
||||
$a=Get-Acl -LiteralPath $path;if(($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@($sys,$admin)-and!(!$dir-and$writers.Count-gt0-and$sids-and$writers[0]-ceq$sids[0]-and$a.GetOwner([Security.Principal.SecurityIdentifier]).Value-ceq'S-1-5-19'))-or($dir-and!$a.AreAccessRulesProtected)){throw 'Fixture owner/protection'}
|
||||
$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty fixture DACL'}
|
||||
foreach($r in $rules){$sid=$r.IdentityReference.Value;$rights=[int64]$r.FileSystemRights;if($r.AccessControlType-ne'Allow'-or($r.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Fixture ACE'};if($sid-in@($sys,$admin)){if($rights-ne2032127){throw 'Trusted fixture rights'}}elseif($sid-in$writers){if($rights-ne2032127){throw 'Own role rights'}}elseif($sid-in$readers){if($rights-ne131241-and$rights-ne1179817){throw 'Reader rights'}}else{throw 'Foreign fixture ACE'}}
|
||||
}
|
||||
function NewDir($path,[string[]]$readers=@(),[string[]]$writers=@()){
|
||||
if(Test-Path -LiteralPath $path){throw 'Create-only fixture directory'};$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)))
|
||||
foreach($sid in @($sys,$admin)+$writers){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))}
|
||||
foreach($sid in @($readers|Where-Object{$_-notin$writers})){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')))}
|
||||
[IO.Directory]::CreateDirectory($path,$a)|Out-Null;Check $path $true $readers $writers
|
||||
}
|
||||
function WriteNew($path,$value){$raw=[Text.Encoding]::ASCII.GetBytes(($value|ConvertTo-Json -Depth 24 -Compress));if($raw.Length-gt65536){throw 'Bounded own controller record'};$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$f.Write($raw,0,$raw.Length);$f.Flush($true)}finally{$f.Dispose()};$a=New-Object Security.AccessControl.FileSecurity;$a.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)');Set-Acl -LiteralPath $path -AclObject $a}
|
||||
function ReadJson($path,[string[]]$readers=@(),[string[]]$writers=@(),[int]$limit=65536){Check $path $false $readers $writers;if((Get-Item -LiteralPath $path).Length-gt$limit){throw 'Bounded own JSON'};return([IO.File]::ReadAllText($path,[Text.Encoding]::UTF8)|ConvertFrom-Json)}
|
||||
function Command([int]$n){return('"'+$exe+'" --service '+$p.id+' '+$tags[$n])}
|
||||
function Service([int]$n){
|
||||
$s=Get-CimInstance Win32_Service -Filter ("Name='"+$names[$n]+"'") -OperationTimeoutSec 5;if(!$s){return $null}
|
||||
if($s.PathName-cne(Command $n)-or$s.StartMode-cne'Manual'-or$s.ServiceType-cne'Own Process'-or$s.StartName-cne$accounts[$n]-or@((Get-Service -Name $names[$n]).ServicesDependedOn).Count-ne0){throw 'Exact own fixture SCM configuration'}
|
||||
if((Get-ItemPropertyValue -LiteralPath ('HKLM:\SYSTEM\CurrentControlSet\Services\'+$names[$n]) -Name ServiceSidType)-ne1){throw 'Own service SID type'}
|
||||
$text=(@(& 'C:\Windows\System32\sc.exe' sdshow $names[$n])-join"`n").Trim();if($LASTEXITCODE-ne0-or!$text-or$text.Length-gt8192){throw 'Bounded own SCM DACL'}
|
||||
$security=New-Object Security.AccessControl.RawSecurityDescriptor($text);if(!$security.DiscretionaryAcl-or!($security.ControlFlags-band[Security.AccessControl.ControlFlags]::DiscretionaryAclProtected)){throw 'Protected own SCM DACL'}
|
||||
foreach($ace in $security.DiscretionaryAcl){if($ace.AceQualifier-ne'AccessAllowed'-or$ace.SecurityIdentifier.Value-notin@($sys,$admin)){throw 'Own service controllers only'}}
|
||||
return [ordered]@{command=$s.PathName;account=$s.StartName;start=$s.StartMode;type=$s.ServiceType;sid_type=1;acl_sha256=(HashBytes ([Text.Encoding]::ASCII.GetBytes($text)))}
|
||||
}
|
||||
function Equal($a,$b){return(($a|ConvertTo-Json -Depth 24 -Compress)-ceq($b|ConvertTo-Json -Depth 24 -Compress))}
|
||||
function Original([int]$n){$made=ReadJson (Join-Path $control ($tags[$n]+'-created.json'));$s=Service $n;if(!$s-or!(Equal $s $made.service)){throw 'Same original fixture definition'};return $s}
|
||||
function ReadAll{
|
||||
$roles=[ordered]@{};for($n=0;$n-lt2;$n++){$output=Join-Path $case $tags[$n];Check $output $true $sids @($sids[$n]);$reports=[ordered]@{};foreach($leaf in @('intent','report','end')){$path=Join-Path $output ($leaf+'.json');$reports[$leaf]=$null;if(Test-Path -LiteralPath $path){$reports[$leaf]=ReadJson $path $sids @($sids[$n]) 16384}};$s=Service $n;$status=$null;if($s){$h=[RmmCaptureControl]::OpenOwn($names[$n]);try{$status=$h.Read()}finally{$h.Dispose()}};$markers=[ordered]@{};foreach($leaf in @('created','start-attempt','process','timeout-attempt','exit','outcome','delete-attempt','deleted')){$path=Join-Path $control ($tags[$n]+'-'+$leaf+'.json');$markers[$leaf]=$null;if(Test-Path -LiteralPath $path){$markers[$leaf]=ReadJson $path}};$reportHash=$null;if($null-ne$reports.report){$reportHash=HashFile (Join-Path $output 'report.json')};$roles[$tags[$n]]=@{service=$s;status=$status;markers=$markers;reports=$reports;raw_report_sha256=$reportHash}}
|
||||
return @{id=$p.id;read_only=($p.action-ceq'read');roles=$roles;calibrated=$false;clock_authority=$false;no_rmm_jobs=$true}
|
||||
}
|
||||
'''+NATIVE+r'''
|
||||
if($PSCommandPath-cne(Join-Path (Join-Path $boot $p.script_sha256) 'SignedClockCaptureAcceptance.ps1')-or(HashFile $PSCommandPath)-cne$p.script_sha256){throw 'Actual exact executing controller'}
|
||||
if($p.action-ceq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;read_only=$true;remote_case_absent=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
if($p.action-ceq'setup'){
|
||||
if((Test-Path -LiteralPath $base)-or(Service 0)-or(Service 1)){throw 'Existing capture namespace: original read only'}
|
||||
NewDir $base;NewDir $case;NewDir $control;WriteNew (Join-Path $control 'intent.json') $p;WriteNew (Join-Path $base 'active.json') @{id=$p.id;manifest_sha256=$p.manifest_sha256;script_sha256=$p.script_sha256;no_retry=$true}
|
||||
for($n=0;$n-lt2;$n++){WriteNew (Join-Path $control ($tags[$n]+'-create-attempt.json')) @{create_once=$true;command=(Command $n)};$account=$accounts[$n];if($n-eq1){$account=$null};$h=[RmmCaptureControl]::CreateOnce($names[$n],(Command $n),$account);$h.Dispose();WriteNew (Join-Path $control ($tags[$n]+'-created.json')) @{service=(Service $n);create_once=$true}}
|
||||
$sids=@();foreach($name in $names){$sids+=((New-Object Security.Principal.NTAccount('NT SERVICE',$name)).Translate([Security.Principal.SecurityIdentifier]).Value)}
|
||||
# Set exact explicit reader ACLs before putting any executable in this case.
|
||||
foreach($path in @($base,$case)){$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false);$a.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)));foreach($sid in @($sys,$admin)){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))};foreach($sid in $sids){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')))};Set-Acl -LiteralPath $path -AclObject $a;Check $path $true $sids}
|
||||
for($n=0;$n-lt2;$n++){NewDir (Join-Path $case $tags[$n]) $sids @($sids[$n])}
|
||||
$staged=Join-Path (Join-Path $boot $p.exe_sha256) 'SignedClockCapture.exe';if((Get-Item -LiteralPath $staged).Length-ne8566784-or(HashFile $staged)-cne$p.exe_sha256){throw 'Exact staged probe'}
|
||||
[IO.File]::Copy($staged,$exe,$false);$ea=New-Object Security.AccessControl.FileSecurity;$ea.SetAccessRuleProtection($true,$false);$ea.SetOwner((New-Object Security.Principal.SecurityIdentifier($admin)));foreach($sid in @($sys,$admin)){$ea.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))};foreach($sid in $sids){$ea.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'ReadAndExecute','Allow')))};Set-Acl -LiteralPath $exe -AclObject $ea;$f=[IO.File]::Open($exe,'Open','ReadWrite','Read');try{$f.Flush($true)}finally{$f.Dispose()};Check $exe $false $sids;if((HashFile $exe)-cne$p.exe_sha256){throw 'Exact own probe copy'}
|
||||
WriteNew (Join-Path $control 'setup-complete.json') @{id=$p.id;roles=$sids;exe_sha256=$p.exe_sha256};@{id=$p.id;setup=$true;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Compress;exit 0
|
||||
}
|
||||
if($p.action-ceq'read'-and!(Test-Path -LiteralPath (Join-Path $control 'setup-complete.json'))){$raw=@();foreach($name in $names){$v=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") -OperationTimeoutSec 5;$raw+=@{name=$name;present=[bool]$v;state=$(if($v){$v.State}else{$null});pid=$(if($v){[uint32]$v.ProcessId}else{0});definition_unverified=$true}};@{id=$p.id;read_only=$true;partial_setup=$true;own_services=$raw;calibrated=$false;clock_authority=$false}|ConvertTo-Json -Depth 8 -Compress;exit 0}
|
||||
$setup=ReadJson (Join-Path $control 'setup-complete.json');$sids=@($setup.roles);if($sids.Count-ne2-or@($sids|Where-Object{$_-notmatch'^S-1-5-80(-[0-9]+){5}$'}).Count-ne0-or$sids[0]-ceq$sids[1]){throw 'Original two fixture SIDs'}
|
||||
Check $base $true $sids;Check $case $true $sids;Check $control $true
|
||||
$i=ReadJson (Join-Path $control 'intent.json');foreach($field in @('id','profile','exe_sha256','exe_bytes','script_sha256','manifest_sha256')){if($i.$field-cne$p.$field){throw 'Original exact capture intent'}}
|
||||
$a=ReadJson (Join-Path $base 'active.json') $sids;if($a.id-cne$p.id-or$a.manifest_sha256-cne$p.manifest_sha256-or$a.script_sha256-cne$p.script_sha256){throw 'Same active capture case'}
|
||||
Check $exe $false $sids;if((Get-Item -LiteralPath $exe).Length-ne8566784-or(HashFile $exe)-cne$p.exe_sha256){throw 'Original immutable probe'}
|
||||
if($p.action-ceq'read'){ReadAll|ConvertTo-Json -Depth 32 -Compress;exit 0}
|
||||
$n=0;if($p.action-in@('start-system','cleanup-system')){$n=1};$tag=$tags[$n];$output=Join-Path $case $tag
|
||||
$null=Original $n
|
||||
if($p.action-in@('start-local-service','start-system')){
|
||||
if((Test-Path -LiteralPath (Join-Path $control 'local-service-delete-attempt.json'))-or(Test-Path -LiteralPath (Join-Path $control 'system-delete-attempt.json'))){throw 'Campaign cleanup began; no further starts'}
|
||||
if(Test-Path -LiteralPath (Join-Path $control ($tag+'-start-attempt.json'))){throw 'Start already attempted; read only'}
|
||||
if($n-eq1){$first=ReadJson (Join-Path $control 'local-service-outcome.json');if($first.success-ne$true){throw 'LocalService must complete first'}}
|
||||
$h=[RmmCaptureControl]::OpenOwn($names[$n]);$process=$null;$proof=$null;$timed=$false;$start=[RmmCaptureControl]::GetTickCount64()
|
||||
try{
|
||||
if($h.Read().State-ne1){throw 'Own service initially stopped'}
|
||||
WriteNew (Join-Path $control ($tag+'-start-attempt.json')) @{start_once=$true;service=(Original $n)}
|
||||
$h.StartOnce()
|
||||
do{
|
||||
$state=$h.Read()
|
||||
if($state.Pid-gt0-and$null-eq$process){$process=[RmmCaptureControl]::Hold([int]$state.Pid);$proof=[RmmPipeNative]::Proof($process,[int]$state.Pid,$owners[$n],$sids[$n],$exe);$cli=(Get-CimInstance Win32_Process -Filter ('ProcessId='+$state.Pid) -OperationTimeoutSec 5).CommandLine;if($cli-cne(Command $n)-or![RmmPipeNative]::Alive($process)-or$h.Read().Pid-ne$state.Pid){throw 'Exact own process CLI/generation'};WriteNew (Join-Path $control ($tag+'-process.json')) @{proof=$proof;command=$cli;image_sha256=$p.exe_sha256}}
|
||||
if($state.State-eq1){break}
|
||||
if([RmmCaptureControl]::GetTickCount64()-$start-ge40000){$timed=$true;break}
|
||||
if($null-ne$process){$null=[RmmPipeNative]::Exited($process,25)}else{Start-Sleep -Milliseconds 10}
|
||||
}while($true)
|
||||
if($timed){if($null-eq$process-or$null-eq$proof){throw 'Timeout without held process; manual original read only'};$fresh=[RmmPipeNative]::Proof($process,[int]$proof.pid,$owners[$n],$sids[$n],$exe);if($fresh.creation_filetime-cne$proof.creation_filetime-or$h.Read().Pid-ne$proof.pid-or(Original $n).command-cne(Command $n)){throw 'Timeout target changed; no termination'};$cli=(Get-CimInstance Win32_Process -Filter ('ProcessId='+$proof.pid) -OperationTimeoutSec 5).CommandLine;if($cli-cne(Command $n)){throw 'Timeout CLI changed'};WriteNew (Join-Path $control ($tag+'-timeout-attempt.json')) @{proof=$proof;terminate_own_handle_once=$true};[RmmCaptureControl]::KillHeld($process)}
|
||||
if($null-eq$process-or![RmmPipeNative]::Exited($process,5000)){throw 'Own process exit not bound'}
|
||||
$exit=[RmmCaptureControl]::Exit($process);$state=$h.Read();if($state.State-ne1){throw 'Own SCM stop not observed'};WriteNew (Join-Path $control ($tag+'-exit.json')) @{process=$proof;kernel_process_exited=$true;exit_code=$exit;timed_out=$timed;scm_exit=$state.Win32Exit;scm_specific_exit=$state.SpecificExit}
|
||||
$report=ReadJson (Join-Path $output 'report.json') $sids @($sids[$n]) 16384;$end=ReadJson (Join-Path $output 'end.json') $sids @($sids[$n]) 16384;$intent=ReadJson (Join-Path $output 'intent.json') $sids @($sids[$n]) 16384
|
||||
if($timed-or$exit-ne0-or$state.Win32Exit-ne0-or$state.SpecificExit-ne0-or$end.success-ne$true-or$report.pid-ne$proof.pid-or[string]$report.process_birth_filetime-cne$proof.creation_filetime-or$report.image_sha256-cne$p.exe_sha256-or$report.role-cne$tag-or$report.case_id-cne$p.id-or$intent.pid-ne$report.pid-or$intent.process_birth_filetime-ne$report.process_birth_filetime-or$end.case_id-cne$p.id-or$end.role-cne$tag-or$report.calibrated-ne$false-or$report.clock_authority-ne$false-or$report.capture.calibrated-ne$false-or$report.capture.clock_authority-ne$false-or$report.capture.sample_count-ne128-or@($report.capture.samples_100ns).Count-ne128-or$report.capture.elapsed_monotonic_ns-gt250000000-or$report.capture.elapsed_interrupt_ns-gt250000000-or$end.report_sha256-cne(HashFile (Join-Path $output 'report.json'))){throw 'Exact noncalibrating report/end/exit proof'}
|
||||
WriteNew (Join-Path $control ($tag+'-outcome.json')) @{success=$true;exit_code=$exit;process=$proof;scm_exit=$state.Win32Exit;scm_specific_exit=$state.SpecificExit;report_sha256=$end.report_sha256;calibrated=$false;clock_authority=$false}
|
||||
}finally{if($null-ne$process){$process.Dispose()};$h.Dispose()}
|
||||
ReadAll|ConvertTo-Json -Depth 32 -Compress;exit 0
|
||||
}
|
||||
if($p.action-in@('cleanup-local-service','cleanup-system')){
|
||||
if(Test-Path -LiteralPath (Join-Path $control ($tag+'-delete-attempt.json'))){throw 'Delete already attempted; read only'}
|
||||
if(Test-Path -LiteralPath (Join-Path $control ($tag+'-start-attempt.json'))){$exited=ReadJson (Join-Path $control ($tag+'-exit.json'));$originalProcess=ReadJson (Join-Path $control ($tag+'-process.json'));if($exited.kernel_process_exited-ne$true-or!(Equal $exited.process $originalProcess.proof)){throw 'Original started process exit not durably observed'}}
|
||||
$h=[RmmCaptureControl]::OpenOwn($names[$n]);try{if($h.Read().State-ne1){throw 'Cleanup only stopped original service'};$null=Original $n;WriteNew (Join-Path $control ($tag+'-delete-attempt.json')) @{delete_once=$true;service=(Original $n)};$h.DeleteOnce()}finally{$h.Dispose()}
|
||||
if(Service $n){throw 'Service absence not observed; read only'};WriteNew (Join-Path $control ($tag+'-deleted.json')) @{deleted=$true;service_absent=$true;id=$p.id}
|
||||
ReadAll|ConvertTo-Json -Depth 32 -Compress;exit 0
|
||||
}
|
||||
throw 'Fixed capture phase only'
|
||||
'''
|
||||
|
||||
LAUNCH = r'''$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if($p.script_sha256-notmatch'^[a-f0-9]{64}$'-or$p.id-notmatch'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$'-or$p.action-notin@('setup','start-local-service','start-system','read','cleanup-local-service','cleanup-system')){throw 'Fixed controller request'}
|
||||
$script='C:\ProgramData\RustDiscoveryBootstrap\'+$p.script_sha256+'\SignedClockCaptureAcceptance.ps1'
|
||||
if(!(Test-Path -LiteralPath $script)){
|
||||
if($p.action-cne'read'){throw 'Staged controller absent'}
|
||||
@{id=$p.id;read_only=$true;controller_absent=$true;remote_case_absent=!(Test-Path -LiteralPath ('C:\ProgramData\RustDiscoverySignedClockCapture\'+$p.id))}|ConvertTo-Json -Compress;exit 0
|
||||
}
|
||||
$i=Get-Item -LiteralPath $script -Force;if($i.PSIsContainer-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)-or$i.Length-gt65536-or(Get-FileHash -LiteralPath $script -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.script_sha256){throw 'Exact staged controller'}
|
||||
$a=Get-Acl -LiteralPath $script;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Controller owner'};foreach($r in $a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private controller DACL'}}
|
||||
$global:RmmSignedClockCapturePayload=$p
|
||||
& $script
|
||||
'''
|
||||
|
||||
|
||||
class CaptureAccess(pipe.Access):
|
||||
def stage_capture(self, path, name):
|
||||
require(name in ('SignedClockCapture.exe', 'SignedClockCaptureAcceptance.ps1'), 'two fixed capture artifacts only')
|
||||
path = Path(path)
|
||||
private(path)
|
||||
size = path.stat().st_size
|
||||
require(size == EXE_BYTES if name.endswith('.exe') else size <= 65536, 'fixed bounded capture transfer')
|
||||
digest = sha(path)
|
||||
prepare = pipe.u.transport.PREPARE_SCRIPT.replace('TransportAcceptance.ps1', name)
|
||||
observed = self.powershell(prepare, dict(sha256=digest))
|
||||
if not observed['already_uploaded']:
|
||||
# Credentials are read only by the actual operator phase. The
|
||||
# existing strict pinned ssh prefix is reused without modification.
|
||||
access = pipe.cb.contract.protected_json(self.root / 'credentials/windows-dev-access.json')
|
||||
prefix = access['ssh_prefix']
|
||||
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
|
||||
target = '/C:/ProgramData/RustDiscoveryBootstrap/' + digest + '/' + name
|
||||
result = subprocess.run(args, input=('put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(target) + '\n').encode(), capture_output=True, timeout=60)
|
||||
require(result.returncode == 0, 'fixed create-once capture transfer; lost reply read only')
|
||||
observed = self.powershell(prepare, dict(sha256=digest))
|
||||
require(observed['already_uploaded'] is True and observed['sha256'] == digest, 'exact immutable staged capture artifact')
|
||||
|
||||
|
||||
def dependencies():
|
||||
paths = set(pipe.dependencies()) | {'deploy/windows/system_pipe_upgrade.py'}
|
||||
return {path: sha(ROOT / path) for path in sorted(paths)}
|
||||
|
||||
|
||||
def original_main():
|
||||
for name, digest in INDEX_SHAS.items():
|
||||
path = ACCESS_ROOT / 'devstate/windows-client' / name
|
||||
require(sha(path) == digest, 'unchanged accepted Main component indices')
|
||||
require(sha(MAIN_CASE / 'intent.json') == MAIN_INTENT_SHA and sha(MAIN_CASE / 'result.json') == MAIN_RESULT_SHA, 'original accepted 14fb proof')
|
||||
intent = load(MAIN_CASE / 'intent.json')
|
||||
require(intent['script_sha256'] == pipe.raw_sha(pipe.SCRIPT.encode()), 'original 14fb read-only finish implementation')
|
||||
return intent
|
||||
|
||||
|
||||
def source_qualification():
|
||||
require(sha(QUALIFICATION / 'receipt.json') == RECEIPT_SHA and sha(QUALIFICATION / 'inputs.json') == INPUTS_SHA
|
||||
and sha(QUALIFICATION / 'readonly-capabilities.json') == CAP_SHA, 'original reviewed raw source qualification')
|
||||
inputs = load(QUALIFICATION / 'inputs.json')
|
||||
receipt = load(QUALIFICATION / 'receipt.json')
|
||||
require(len(inputs) == 190 and receipt['calibrated'] is False and receipt['clock_authority'] is False
|
||||
and receipt['module_sha256'] == 'd9dd843db7c17ac4c8f242c9f20063c2a7ce6ad11d3c75826516a22dc5e7685e'
|
||||
and receipt['example_sha256'] == '23f7c8d832bf9042fb89226729aa1cfe2a65ad33b76cda15cc69f8995d5834d0', 'reviewed exact non-authoritative probe')
|
||||
seen = set()
|
||||
for item in inputs:
|
||||
path = Path(item['path'])
|
||||
require(not path.is_absolute() and '..' not in path.parts and str(path) not in seen, 'unique frozen relative input')
|
||||
seen.add(str(path))
|
||||
file = QUALIFICATION / 'source' / path
|
||||
metadata = file.lstat()
|
||||
require(stat.S_ISREG(metadata.st_mode) and metadata.st_nlink == 1 and metadata.st_size == item['bytes']
|
||||
and metadata.st_size <= 2 * 1024 * 1024 and sha(file) == item['sha256'], 'original frozen source bytes')
|
||||
binary = QUALIFICATION / 'SignedClockCapture.exe'
|
||||
require(binary.stat().st_size == EXE_BYTES and sha(binary) == EXE_SHA, 'exact qualified AMD64 probe')
|
||||
native = load(LINUX_READ)
|
||||
require(sha(LINUX_READ) == LINUX_READ_SHA and native['read_only'] is True and native['entered'] is True
|
||||
and native['id'] == NATIVE_CASE.name, 'actual original Linux-first pass readback')
|
||||
result = native['result']
|
||||
require(result['passed'] == 5 and result['listed'] == 15 and result['filtered'] == 10 and result['ignored'] == 0
|
||||
and result['source_receipt_sha256'] == RECEIPT_SHA and result['source_manifest_sha256'] == sha(NATIVE_CASE / 'manifest.json')
|
||||
and result['before'] == result['after'] == native['current_witness'] and result['no_rmm_jobs'] is True
|
||||
and result['no_service_control'] is True and result['binary_sha256'] == 'dceee96d9e58d8b5c3606c724b4d390c2eea6472bf33d317e7a5a9102c0c5e06', 'actual five Linux guards and retained original state')
|
||||
native_manifest = load(NATIVE_CASE / 'manifest.json')
|
||||
require(native_manifest['source_files'] == inputs and native_manifest['receipt_sha256'] == RECEIPT_SHA, 'same Linux proof source generation')
|
||||
return inputs
|
||||
|
||||
|
||||
def prepare():
|
||||
original_main()
|
||||
inputs = source_qualification()
|
||||
STATE.mkdir(mode=0o700, parents=True, exist_ok=True); private(STATE, True)
|
||||
ident = str(uuid.uuid4())
|
||||
# One original campaign for this exact frozen source. An incomplete case
|
||||
# cannot be bypassed by asking prepare for another UUID.
|
||||
save(STATE / 'active-intent.json', dict(id=ident, runner_sha256=sha(__file__), no_retry=True))
|
||||
folder = STATE / ident; folder.mkdir(mode=0o700)
|
||||
for name in ('receipt.json', 'inputs.json', 'readonly-capabilities.json'):
|
||||
write(folder / name, (QUALIFICATION / name).read_bytes())
|
||||
for item in inputs:
|
||||
destination = folder / 'source' / item['path']
|
||||
destination.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
write(destination, (QUALIFICATION / 'source' / item['path']).read_bytes())
|
||||
write(folder / 'SignedClockCapture.exe', (QUALIFICATION / 'SignedClockCapture.exe').read_bytes())
|
||||
write(folder / 'SignedClockCaptureAcceptance.ps1', SCRIPT.encode())
|
||||
write(folder / 'linux-first-read.json', LINUX_READ.read_bytes())
|
||||
manifest = dict(id=ident, profile=PROFILE, runner_sha256=sha(__file__), dependencies=dependencies(),
|
||||
source_files=inputs, source_receipt_sha256=RECEIPT_SHA, readonly_capabilities_sha256=CAP_SHA,
|
||||
exe_sha256=EXE_SHA, exe_bytes=EXE_BYTES, script_sha256=hashlib.sha256(SCRIPT.encode()).hexdigest(),
|
||||
linux_first_read_sha256=LINUX_READ_SHA, main_indices=INDEX_SHAS, main_result_sha256=MAIN_RESULT_SHA,
|
||||
calibrated=False, clock_authority=False, target_executed=False)
|
||||
save(folder / 'manifest.json', manifest)
|
||||
print(json.dumps(dict(id=ident, prepared_locally=True, target_executed=False)))
|
||||
|
||||
|
||||
def case(ident):
|
||||
require(str(uuid.UUID(ident)) == ident and uuid.UUID(ident).version == 4, 'original canonical UUIDv4')
|
||||
folder = STATE / ident; private(folder, True)
|
||||
manifest = load(folder / 'manifest.json')
|
||||
require(manifest['id'] == ident and manifest['profile'] == PROFILE and manifest['runner_sha256'] == sha(__file__)
|
||||
and manifest['dependencies'] == dependencies() and load(STATE / 'active-intent.json')['id'] == ident, 'original source and active case only')
|
||||
require(sha(folder / 'SignedClockCapture.exe') == EXE_SHA and (folder / 'SignedClockCapture.exe').stat().st_size == EXE_BYTES
|
||||
and sha(folder / 'SignedClockCaptureAcceptance.ps1') == manifest['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest()
|
||||
and sha(folder / 'receipt.json') == RECEIPT_SHA and sha(folder / 'inputs.json') == INPUTS_SHA
|
||||
and sha(folder / 'readonly-capabilities.json') == CAP_SHA and sha(folder / 'linux-first-read.json') == LINUX_READ_SHA, 'same exact original sources/proofs/artifacts')
|
||||
require(manifest['source_files'] == load(folder / 'inputs.json') and len(manifest['source_files']) == 190, 'fixed original source manifest')
|
||||
for item in manifest['source_files']:
|
||||
relative = Path(item['path'])
|
||||
require(not relative.is_absolute() and '..' not in relative.parts, 'fixed relative source path')
|
||||
path = folder / 'source' / relative; private(path)
|
||||
require(path.stat().st_size == item['bytes'] and sha(path) == item['sha256'], 'original retained 190 input bytes')
|
||||
original_main()
|
||||
return folder, manifest
|
||||
|
||||
|
||||
def server_closed(access):
|
||||
observed = access.server_state()
|
||||
require(observed['counts'] == dict(windows=dict(jobs=0, outbox=0, permits=0, unresolved=0),
|
||||
linux=dict(jobs=31, outbox=31, permits=27, unresolved=0))
|
||||
and observed['flags']['root_policy_sha256'] == ROOT_POLICY, 'actual accepted current counts and closed Rootpolicy')
|
||||
return observed
|
||||
|
||||
|
||||
def native_witness(access):
|
||||
observed = pipe.remote(access, original_main(), 'finish')
|
||||
require(observed['read_only'] is True and observed['completed'] is True, 'only original existing 14fb finish reader')
|
||||
native = observed['native']
|
||||
require(native['private_key_read'] is False and all(value == 0 for value in native['journal']['core_counts'].values()), 'passive identity, no core job rows')
|
||||
return dict(stable={field: native[field] for field in STABLE}, journal={field: native['journal'][field] for field in JOURNAL},
|
||||
sequence=native['journal']['sequence'])
|
||||
|
||||
|
||||
def preserved(before, after):
|
||||
require(before['stable'] == after['stable'] and before['journal'] == after['journal']
|
||||
and after['sequence'] >= before['sequence'], 'all six native fields and journal identity/schema/core counts preserved')
|
||||
|
||||
|
||||
def baseline(access, folder):
|
||||
save(folder / 'baseline-attempt.json', dict(read_only=True))
|
||||
server = server_closed(access); native = native_witness(access)
|
||||
save(folder / 'baseline.json', dict(server=server, native=native, indices=INDEX_SHAS))
|
||||
print(json.dumps(dict(id=folder.name, baseline_read_only=True)))
|
||||
|
||||
|
||||
def payload(folder, manifest, phase):
|
||||
return dict(id=folder.name, profile=PROFILE, action=phase, exe_sha256=EXE_SHA, exe_bytes=EXE_BYTES,
|
||||
script_sha256=manifest['script_sha256'], manifest_sha256=sha(folder / 'manifest.json'))
|
||||
|
||||
|
||||
def validate_role(role, value, ident):
|
||||
require(role in ('local-service', 'system'), 'fixed role validation')
|
||||
report = value['reports']['report']; end = value['reports']['end']; intent = value['reports']['intent']
|
||||
outcome = value['markers']['outcome']; exited = value['markers']['exit']; process = value['markers']['process']
|
||||
require(report is not None and end is not None and outcome is not None and exited is not None and process is not None
|
||||
and outcome['success'] is True and end['success'] is True and exited['kernel_process_exited'] is True
|
||||
and exited['exit_code'] == 0 and exited['timed_out'] is False and exited['scm_exit'] == exited['scm_specific_exit'] == 0
|
||||
and report['role'] == end['role'] == role and report['case_id'] == end['case_id'] == intent['case_id'] == ident
|
||||
and value['raw_report_sha256'] == end['report_sha256'] == outcome['report_sha256'] and report['pid'] == intent['pid'] == process['proof']['pid']
|
||||
and str(report['process_birth_filetime']) == process['proof']['creation_filetime']
|
||||
and report['image_sha256'] == EXE_SHA and report['calibrated'] is report['clock_authority'] is False,
|
||||
'actual own role/process/end/exit proof')
|
||||
expected = 'S-1-5-19' if role == 'local-service' else 'S-1-5-18'
|
||||
require(report['token']['user_sid'] == process['proof']['owner_sid'] == expected
|
||||
and report['token']['service_sid_sha256'] == hashlib.sha256(process['proof']['service_sid'].encode()).hexdigest()
|
||||
and process['proof']['service_sid_enabled'] is True and process['proof']['kernel_handle_bound'] is True,
|
||||
'actual token and enabled own service SID')
|
||||
capture = report['capture']; rows = capture['samples_100ns']
|
||||
require(capture['schema_version'] == 1 and capture['calibrated'] is capture['clock_authority'] is False
|
||||
and capture['sample_count'] == len(rows) == 128 and capture['elapsed_monotonic_ns'] <= 250_000_000
|
||||
and capture['elapsed_interrupt_ns'] <= 250_000_000 and all(isinstance(row, list) and len(row) == 5
|
||||
and all(type(number) is int and 0 <= number < 2**64 for number in row) for row in rows), 'bounded numeric raw capture, never calibration')
|
||||
if value['service'] is None:
|
||||
require(value['markers']['delete-attempt'] is not None and value['markers']['deleted']['service_absent'] is True, 'original own cleanup and actual absence')
|
||||
else:
|
||||
require(value['status'] is not None and value['status']['State'] == 1 and value['status']['Pid'] == 0, 'own service stopped')
|
||||
|
||||
|
||||
def read(access, folder, manifest):
|
||||
read_id = str(uuid.uuid4())
|
||||
raw_path = folder / ('read-' + read_id + '.json')
|
||||
server_path = folder / ('read-server-' + read_id + '.json')
|
||||
native_path = folder / ('read-native-' + read_id + '.json')
|
||||
preservation_path = folder / ('read-preservation-' + read_id + '.json')
|
||||
receipt_path = folder / ('read-receipt-' + read_id + '.json')
|
||||
response = access.powershell(LAUNCH, payload(folder, manifest, 'read'), timeout=90)
|
||||
# Save/fsync the exact canonical raw read before creating any linked proof.
|
||||
save(raw_path, response)
|
||||
raw_link = dict(filename=raw_path.name, sha256=sha(raw_path))
|
||||
binding = dict(case_id=folder.name, read_id=read_id, raw_read_filename=raw_path.name,
|
||||
raw_read_sha256=raw_link['sha256'], runner_sha256=sha(__file__),
|
||||
controller_sha256=manifest['script_sha256'], read_only=True)
|
||||
completed = []
|
||||
for role, value in response.get('roles', {}).items():
|
||||
if value['markers']['outcome'] is not None:
|
||||
validate_role(role, value, folder.name)
|
||||
completed.append(role)
|
||||
old = load(folder / 'baseline.json')
|
||||
server = server_closed(access); native = native_witness(access)
|
||||
require(server == old['server'], 'current server gates unchanged')
|
||||
preserved(old['native'], native)
|
||||
# Each independently captured witness binds this exact same saved read.
|
||||
save(server_path, dict(binding, witness=server))
|
||||
save(native_path, dict(binding, witness=native))
|
||||
server_link = dict(filename=server_path.name, sha256=sha(server_path))
|
||||
native_link = dict(filename=native_path.name, sha256=sha(native_path))
|
||||
cleaned = sorted(role for role, value in response.get('roles', {}).items() if value['service'] is None and value['markers']['deleted'] is not None and value['markers']['deleted']['service_absent'] is True)
|
||||
save(preservation_path, dict(binding, server=server, native=native,
|
||||
server_witness=server_link, native_witness=native_link,
|
||||
completed_roles=sorted(completed), cleanup_verified_roles=cleaned,
|
||||
calibrated=False, clock_authority=False))
|
||||
preservation_link = dict(filename=preservation_path.name, sha256=sha(preservation_path))
|
||||
# Final create-only receipt is published only after A, both witnesses and B
|
||||
# have been persisted. Missing files never become a completed read receipt.
|
||||
save(receipt_path, dict(binding, schema_version=1, raw_read=raw_link,
|
||||
preservation=preservation_link, server_witness=server_link,
|
||||
native_witness=native_link, calibrated=False, clock_authority=False))
|
||||
print(json.dumps(dict(id=folder.name, read_only=True, completed_roles=sorted(completed),
|
||||
read_receipt_filename=receipt_path.name, read_receipt_sha256=sha(receipt_path))))
|
||||
|
||||
|
||||
def mutate(access, folder, manifest, phase):
|
||||
old = load(folder / 'baseline.json')
|
||||
require(server_closed(access) == old['server'], 'same closed server before action')
|
||||
preserved(old['native'], native_witness(access))
|
||||
if phase != 'setup':
|
||||
require((folder / 'setup-reply.json').exists(), 'one completed original setup')
|
||||
if phase.startswith('start-'):
|
||||
require(not any(folder.glob('cleanup-*-attempt.json')), 'cleanup already began; no new starts')
|
||||
save(folder / (phase + '-attempt.json'), dict(id=folder.name, once=True, no_retry=True))
|
||||
if phase == 'setup':
|
||||
access.stage_capture(folder / 'SignedClockCapture.exe', 'SignedClockCapture.exe')
|
||||
access.stage_capture(folder / 'SignedClockCaptureAcceptance.ps1', 'SignedClockCaptureAcceptance.ps1')
|
||||
observed = access.powershell(LAUNCH, payload(folder, manifest, phase), timeout=90)
|
||||
save(folder / (phase + '-reply.json'), observed)
|
||||
require(observed['id'] == folder.name and observed['calibrated'] is observed['clock_authority'] is False, 'original non-authoritative native response')
|
||||
if phase.startswith('start-'):
|
||||
validate_role(phase.removeprefix('start-'), observed['roles'][phase.removeprefix('start-')], folder.name)
|
||||
if phase.startswith('cleanup-'):
|
||||
role = phase.removeprefix('cleanup-')
|
||||
require(observed['roles'][role]['service'] is None and observed['roles'][role]['markers']['deleted']['service_absent'] is True,
|
||||
'exact own stopped service deleted once and absence observed')
|
||||
after_server = server_closed(access); after_native = native_witness(access)
|
||||
require(after_server == old['server'], 'current server policy/counts/hooks unchanged')
|
||||
preserved(old['native'], after_native)
|
||||
save(folder / (phase + '-preserved.json'), dict(server=after_server, native=after_native, no_rmm_jobs=True))
|
||||
print(json.dumps(dict(id=folder.name, phase=phase, preserved=True, calibrated=False, clock_authority=False)))
|
||||
|
||||
|
||||
def static_guards():
|
||||
require(SCRIPT.count('$h.StartOnce()') == SCRIPT.count('$h.DeleteOnce()') == SCRIPT.count('[RmmCaptureControl]::KillHeld($process)') == 1, 'single fixed own action primitives')
|
||||
require(all(token not in SCRIPT for token in ('RmmDiscoveryWindows', 'RmmDiscoverySystemHelper', 'device.key', 'Restart-Service', 'Restart-Computer', 'Stop-Computer', 'Set-Date', 'w32tm', 'Invoke-Expression', 'Bypass')), 'no RMM/W32Time/setter/general execution path')
|
||||
require('function FileIdentity' not in NATIVE and 'function ActualState' not in NATIVE and 'function Swap' not in NATIVE, 'only original read-only handle proof reused')
|
||||
require(len(SCRIPT.encode()) <= 65536 and len(base64.b64encode(LAUNCH.encode('utf-16le'))) + 2048 < 32767, 'bounded staged controller and launch command')
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
static_guards()
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('phase', choices=('prepare', 'baseline', 'setup', 'start-local-service', 'start-system', 'read', 'cleanup-local-service', 'cleanup-system'))
|
||||
parser.add_argument('--case')
|
||||
args = parser.parse_args()
|
||||
if args.phase == 'prepare':
|
||||
require(args.case is None, 'one new local campaign only'); prepare(); return
|
||||
require(args.case is not None, 'original case required')
|
||||
folder, manifest = case(args.case)
|
||||
access = CaptureAccess(ACCESS_ROOT)
|
||||
if args.phase == 'baseline':
|
||||
baseline(access, folder)
|
||||
elif args.phase == 'read':
|
||||
read(access, folder, manifest)
|
||||
else:
|
||||
mutate(access, folder, manifest, args.phase)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user