341 lines
27 KiB
Python
341 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""Pure C fixture contract guards only; actual Cloud Linux first, then Windows.
|
|
No installer artifact is a delivery role. Lost replies allow same-case readback only.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import datetime as dt
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shlex
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import uuid
|
|
import vm_access_check as access
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
STATE = ROOT / 'devstate/windows-exe-contract-guards'
|
|
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
|
PROFILE = 'windows-exe-pure-contract-guard-v1'
|
|
QUALIFICATION = ROOT / 'devstate/windows-exe-fixture/build-e85496e8-b6dd-4834-8c17-843ee5c5b3da/qualification.json'
|
|
QUALIFICATION_SHA = 'f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061'
|
|
GUARDS = {'linux': ('linux-precondition-guard', '5af37aa734e47dac480a2fe4d6039d4bf6708bb392f4b00320d1c7ab79fac439', 16128),
|
|
'windows': ('windows-precondition-guard.exe', '1929a20c041c96337a8e2665b7aad4ea8a46604ccddebcaab68242c7387b84cf', 15360)}
|
|
LINUX_REMOTE = '/var/lib/rmm-windows-exe-contract-guards'
|
|
|
|
def require(value, code):
|
|
if not value:
|
|
raise RuntimeError(code)
|
|
|
|
def sha(path):
|
|
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
|
|
def object_pairs(items):
|
|
value = {}
|
|
for key, item in items:
|
|
require(key not in value, 'duplicate JSON field')
|
|
value[key] = item
|
|
return value
|
|
|
|
def private(path, directory=False):
|
|
item = Path(path).lstat()
|
|
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
|
|
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
|
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
|
|
'private owned regular path')
|
|
|
|
def load(path):
|
|
private(path)
|
|
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
|
|
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
|
|
|
|
def save(path, value):
|
|
private(Path(path).parent, True)
|
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
|
|
|
|
def setup_state():
|
|
os.umask(0o077)
|
|
STATE.parent.mkdir(mode=0o700, exist_ok=True)
|
|
metadata = STATE.parent.lstat()
|
|
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
|
|
'owned non-world-writable devstate parent')
|
|
STATE.mkdir(mode=0o700, exist_ok=True)
|
|
private(STATE, True)
|
|
|
|
def scripts():
|
|
return dict(linux_case_sha256=hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
|
|
windows_script_sha256=hashlib.sha256(WINDOWS.encode()).hexdigest())
|
|
|
|
|
|
def sources():
|
|
require(sha(QUALIFICATION) == QUALIFICATION_SHA, 'original fixture qualification')
|
|
q = load(QUALIFICATION)
|
|
require(q['no_installer_run'] is True and q['no_upload'] is True and q['source_before_after_equal'] is True, 'fixture-only qualification')
|
|
result = dict(q['source_files'])
|
|
for name in ('deploy/windows_exe_guard_acceptance.py', 'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py'):
|
|
result[name] = sha(ROOT / name)
|
|
require(all(sha(ROOT / name) == digest for name, digest in result.items()), 'exact current source provenance')
|
|
return result
|
|
|
|
|
|
def build():
|
|
setup_state(); before = sources(); folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
|
|
q = load(QUALIFICATION); artifacts = {}
|
|
for platform, (name, digest, length) in GUARDS.items():
|
|
item = q['artifacts'][name]; original = QUALIFICATION.parent / name
|
|
require(item['sha256'] == digest and item['bytes'] == length and sha(original) == digest
|
|
and original.stat().st_size == length, 'only original pure guard bytes')
|
|
destination = folder / name
|
|
with destination.open('xb') as out:
|
|
out.write(original.read_bytes()); out.flush(); os.fsync(out.fileno())
|
|
destination.chmod(0o600)
|
|
artifacts[platform] = dict(path=str(destination), sha256=digest, bytes=length, role='pure_precondition_guard')
|
|
require(sources() == before, 'source before/after equality')
|
|
manifest = dict(schema_version=1, type='rmm.windows.exe-pure-guard-build', profile=PROFILE,
|
|
qualification_path=str(QUALIFICATION), qualification_sha256=QUALIFICATION_SHA,
|
|
runner_sha256=sha(__file__), scripts=scripts(), source_files=before, source_before_after_equal=True,
|
|
artifacts=artifacts, installer_delivery=False, native_execution=False)
|
|
save(folder / 'manifest.json', manifest)
|
|
print(json.dumps(dict(manifest_path=str(folder/'manifest.json'), manifest_sha256=sha(folder/'manifest.json'), native_execution=False)))
|
|
|
|
|
|
def verified(path):
|
|
private(path.parent, True); value = load(path)
|
|
require(value['schema_version'] == 1 and value['type'] == 'rmm.windows.exe-pure-guard-build' and value['profile'] == PROFILE
|
|
and value['qualification_path'] == str(QUALIFICATION) and value['qualification_sha256'] == QUALIFICATION_SHA
|
|
and value['runner_sha256'] == sha(__file__) and value['scripts'] == scripts() and value['source_files'] == sources()
|
|
and value['source_before_after_equal'] is True and value['installer_delivery'] is False
|
|
and value['native_execution'] is False and set(value['artifacts']) == {'linux','windows'}, 'original guard-only manifest')
|
|
for platform, (name, digest, length) in GUARDS.items():
|
|
item = value['artifacts'][platform]; candidate = path.parent / name
|
|
private(candidate)
|
|
require(item == dict(path=str(candidate), sha256=digest, bytes=length, role='pure_precondition_guard')
|
|
and sha(candidate) == digest and candidate.stat().st_size == length, 'exact fixed guard delivery role')
|
|
return value
|
|
|
|
|
|
def access_settings(root, platform):
|
|
"""Read strictly parsed existing access only when the parent executes native."""
|
|
require(root == ACCESS_ROOT and not root.is_symlink(), 'original Main access-root only; no copied credentials')
|
|
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
|
|
if platform == 'linux':
|
|
cfg = access.load_config(root / 'credentials/linux-vm.conf')
|
|
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
|
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
|
|
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
|
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
|
|
else:
|
|
cfg = access.load_config(root / 'credentials/server.conf')
|
|
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
|
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
|
|
credentials = root / 'credentials'; private(credentials, True)
|
|
record = load(credentials / 'windows-dev-access.json')
|
|
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
|
|
expires = dt.datetime.fromisoformat(record['expires_at'])
|
|
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
|
|
key = str(Path(cfg['ssh_key_path']).expanduser())
|
|
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
|
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
|
|
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
|
|
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
|
|
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
|
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
|
|
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
|
|
private(credentials / 'windows-dev.known_hosts')
|
|
return prefix
|
|
|
|
def transport(prefix, command_text, data, folder, timeout=60):
|
|
"""No stdout/stderr escapes the private case directory on transport failure."""
|
|
try:
|
|
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
|
|
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
|
|
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
|
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
|
|
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
|
|
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
|
|
return value
|
|
except subprocess.TimeoutExpired as error:
|
|
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
|
|
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
|
raise RuntimeError('native reply lost; read original case only') from None
|
|
|
|
def upload(prefix, item, destination, folder, kind):
|
|
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
|
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
|
|
if '-p' in args: args[args.index('-p')] = '-P'
|
|
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
|
|
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
|
|
try:
|
|
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
|
|
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
|
|
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
|
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
|
|
except subprocess.TimeoutExpired as error:
|
|
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
|
|
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
|
raise RuntimeError('artifact transfer incomplete; no retry') from None
|
|
|
|
def linux_rpc(prefix, payload, folder):
|
|
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
|
|
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
|
return transport(prefix, 'python3 -', code.encode(), folder, timeout=25)
|
|
|
|
|
|
def windows_rpc(prefix, payload, folder):
|
|
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
|
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
|
|
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder, timeout=25)
|
|
|
|
|
|
def linux_case(p):
|
|
import resource
|
|
import stat
|
|
ident = str(uuid.UUID(p['id']))
|
|
require(ident == p['id'] and p['action'] in ('prepare','run','read') and p['profile'] == 'windows-exe-pure-contract-guard-v1'
|
|
and p['artifact'] == dict(sha256='5af37aa734e47dac480a2fe4d6039d4bf6708bb392f4b00320d1c7ab79fac439', bytes=16128)
|
|
and os.geteuid() == 0 and os.uname().machine == 'x86_64', 'fixed pure Linux guard only')
|
|
root = Path('/var/lib/rmm-windows-exe-contract-guards'); case = root / ident
|
|
def safe(path, directory, executable=False):
|
|
item = path.lstat()
|
|
require(item.st_uid == 0 and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o500 if executable else 0o600)
|
|
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1), 'private guard scratch')
|
|
def write(path, value):
|
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
|
with os.fdopen(fd,'w') as out: json.dump(value,out); out.flush(); os.fsync(out.fileno())
|
|
os.umask(0o077)
|
|
if p['action'] == 'read' and not case.exists(): return dict(id=ident,status='remote_case_absent')
|
|
if p['action'] == 'prepare':
|
|
if not root.exists(): root.mkdir(mode=0o700)
|
|
safe(root,True); case.mkdir(mode=0o700); write(case/'intent.json',p); return dict(id=ident,prepared=True)
|
|
safe(root,True); safe(case,True); safe(case/'intent.json',False)
|
|
old=json.loads((case/'intent.json').read_bytes())
|
|
require({k:v for k,v in old.items() if k!='action'} == {k:v for k,v in p.items() if k!='action'}, 'original complete guard intent')
|
|
if p['action'] == 'read':
|
|
if not (case/'result.json').exists(): return dict(id=ident,status='started_without_result' if (case/'started.json').exists() else 'prepared_without_start')
|
|
safe(case/'result.json',False); require((case/'result.json').stat().st_size<=16384,'bounded guard receipt'); return json.loads((case/'result.json').read_bytes())
|
|
binary=case/'guard'; safe(binary,False)
|
|
require(binary.stat().st_size==p['artifact']['bytes'] and hashlib.sha256(binary.read_bytes()).hexdigest()==p['artifact']['sha256'],'exact pure guard bytes')
|
|
write(case/'started.json',dict(execute_once=True,manifest_sha256=p['manifest_sha256'])); binary.chmod(0o500)
|
|
temp=case/'tmp'; temp.mkdir(mode=0o700)
|
|
env={'PATH':'/usr/bin:/bin','LANG':'C','LC_ALL':'C','TMPDIR':str(temp)}
|
|
def limits():
|
|
resource.setrlimit(resource.RLIMIT_CORE,(0,0));resource.setrlimit(resource.RLIMIT_CPU,(3,3));resource.setrlimit(resource.RLIMIT_FSIZE,(4096,4096))
|
|
require(subprocess.run(['/usr/bin/unshare','--net','--','/usr/bin/true'],env=env,capture_output=True,timeout=3).returncode==0,'netns required')
|
|
with (case/'stdout.bin').open('xb') as out,(case/'stderr.bin').open('xb') as err:
|
|
timed=False
|
|
try: code=subprocess.run(['/usr/bin/unshare','--net','--',str(binary)],cwd=temp,env=env,stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=5,preexec_fn=limits).returncode
|
|
except subprocess.TimeoutExpired: timed=True;code=None
|
|
out.flush();err.flush();os.fsync(out.fileno());os.fsync(err.fileno())
|
|
raw=(case/'stdout.bin').read_bytes();errors=(case/'stderr.bin').read_bytes();require(len(raw)<=4096 and len(errors)<=4096,'bounded guard output')
|
|
value=dict(id=ident,platform='linux',profile=p['profile'],manifest_sha256=p['manifest_sha256'],runner_sha256=p['runner_sha256'],scripts=p['scripts'],
|
|
artifact=p['artifact'],exit_code=code,timed_out=timed,stdout_b64=base64.b64encode(raw).decode(),stderr_b64=base64.b64encode(errors).decode(),
|
|
network_namespace=True,environment_cleared=True,installer_executed=False,rmm_jobs=False,product_state_writes=False)
|
|
write(case/'result.json',value);return value
|
|
|
|
|
|
WINDOWS = r'''
|
|
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
|
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-exe-pure-contract-guard-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'-or$p.artifact.sha256-cne'1929a20c041c96337a8e2665b7aad4ea8a46604ccddebcaab68242c7387b84cf'-or$p.artifact.bytes-ne15360){throw 'Fixed pure Windows guard only'}
|
|
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-exe-contract-guards-'+$p.id)
|
|
function Assert-RmmGuardPath($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Guard path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private guard owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty guard ACL'};foreach($entry in $rules){if($entry.AccessControlType-ne'Allow'-or$entry.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($entry.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad guard ACL'}}}
|
|
function Write-RmmGuardNew($path,$value){$stream=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$bytes=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 12 -Compress));$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}finally{$stream.Dispose()}}
|
|
function Assert-RmmGuardIntent($old){foreach($field in @('id','profile','manifest_sha256','runner_sha256','linux_proof_sha256')){if($old.$field-cne$p.$field){throw 'Original guard binding'}};if($old.artifact.sha256-cne$p.artifact.sha256-or$old.artifact.bytes-ne$p.artifact.bytes-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original guard artifact/scripts'}}
|
|
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
|
|
Assert-RmmGuardPath $root $true
|
|
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Assert-RmmGuardPath $case $true;Write-RmmGuardNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
|
Assert-RmmGuardPath $case $true;$intent=Join-Path $case 'intent.json';Assert-RmmGuardPath $intent $false;Assert-RmmGuardIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
|
|
if($p.action-eq'read'){$report=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $report)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Assert-RmmGuardPath $report $false;if((Get-Item -LiteralPath $report).Length-gt16384){throw 'Report bound'};Get-Content -LiteralPath $report -Raw;exit 0}
|
|
$exe=Join-Path $case 'guard.exe';Assert-RmmGuardPath $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$p.artifact.sha256-or(Get-Item -LiteralPath $exe).Length-ne$p.artifact.bytes){throw 'Exact pure guard bytes'}
|
|
Write-RmmGuardNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $temp|Out-Null;Assert-RmmGuardPath $temp $true
|
|
$start=New-Object Diagnostics.ProcessStartInfo;$start.FileName=$exe;$start.Arguments='';$start.WorkingDirectory=$temp;$start.UseShellExecute=$false;$start.CreateNoWindow=$true;$start.RedirectStandardOutput=$true;$start.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$start.EnvironmentVariables.Clear();$start.EnvironmentVariables['SystemRoot']=$systemRoot;$start.EnvironmentVariables['WINDIR']=$systemRoot;$start.EnvironmentVariables['PATH']=$systemRoot+'\System32';$start.EnvironmentVariables['TEMP']=$temp;$start.EnvironmentVariables['TMP']=$temp
|
|
$child=New-Object Diagnostics.Process;$child.StartInfo=$start
|
|
try{if(!$child.Start()){throw 'Pure guard start'};$outputTask=$child.StandardOutput.ReadToEndAsync();$errorTask=$child.StandardError.ReadToEndAsync();$timed=$false;if(!$child.WaitForExit(5000)){$timed=$true;$child.Kill();if(!$child.WaitForExit(2000)){throw 'Guard process exit bound'}};if(!$outputTask.Wait(2000)-or!$errorTask.Wait(2000)){throw 'Guard output wait bound'};$stdout=$outputTask.Result;$stderr=$errorTask.Result;if($stdout.Length-gt4096-or$stderr.Length-gt4096){throw 'Guard output bound'};$exitCode=$child.ExitCode}finally{$child.Dispose()}
|
|
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;artifact=$p.artifact;linux_proof_sha256=$p.linux_proof_sha256;exit_code=$exitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($stdout));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($stderr));environment_cleared=$true;installer_executed=$false;rmm_jobs=$false;product_state_writes=$false;bootstrap_administrator_guard=$true;local_service_proof=$false};Write-RmmGuardNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 12 -Compress
|
|
'''
|
|
|
|
|
|
def check_result(manifest, platform, value, payload):
|
|
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
|
|
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
|
|
and value.get('scripts') == manifest['scripts'] and value.get('artifact') == payload['artifact']
|
|
and value.get('exit_code') == 0 and value.get('timed_out') is False and value.get('environment_cleared') is True
|
|
and all(value.get(flag) is False for flag in ('installer_executed','rmm_jobs','product_state_writes')),
|
|
'complete fixed guard Exit0 proof')
|
|
require(base64.b64decode(value['stdout_b64'], validate=True) == b''
|
|
and base64.b64decode(value['stderr_b64'], validate=True) == b'', 'pure assert guard has no output')
|
|
if platform == 'linux': require(value.get('network_namespace') is True, 'Linux network namespace')
|
|
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256']
|
|
and value.get('bootstrap_administrator_guard') is True and value.get('local_service_proof') is False, 'honest Linux-first Windows bootstrap scope')
|
|
|
|
|
|
def execute(path, platform, access_root, case_id=None):
|
|
setup_state(); path = path.absolute(); manifest = verified(path); prefix = access_settings(access_root, platform)
|
|
if case_id is None:
|
|
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
|
item = manifest['artifacts'][platform]
|
|
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'],
|
|
scripts=manifest['scripts'], artifact={key:item[key] for key in ('sha256','bytes')})
|
|
if platform == 'windows':
|
|
proof_path = path.parent/'linux-passed.json'; proof=load(proof_path)
|
|
require(proof['verified'] is True and proof['platform'] == 'linux' and proof['manifest_sha256'] == sha(path)
|
|
and proof['runner_sha256'] == manifest['runner_sha256'], 'same-manifest actual Linux guard FIRST')
|
|
linux_payload=dict(payload,id=proof['case_id'],artifact={key:manifest['artifacts']['linux'][key] for key in ('sha256','bytes')})
|
|
check_result(manifest,'linux',proof['native'],linux_payload)
|
|
payload['linux_proof_sha256']=sha(proof_path)
|
|
intent=dict(id=case_id,platform=platform,manifest_path=str(path),manifest_sha256=sha(path),runner_sha256=sha(__file__),
|
|
scripts=scripts(),access_root=str(access_root.absolute()),payload=payload)
|
|
save(folder/'intent.json',intent);save(folder/'started-local.json',dict(create_once=True,no_retry=True))
|
|
read_only=False
|
|
else:
|
|
require(str(uuid.UUID(case_id))==case_id,'canonical original case');folder=STATE/case_id;private(folder,True)
|
|
intent=load(folder/'intent.json');load(folder/'started-local.json')
|
|
require(intent['id']==case_id and intent['platform']==platform and intent['manifest_path']==str(path)
|
|
and intent['manifest_sha256']==sha(path) and intent['runner_sha256']==sha(__file__) and intent['scripts']==scripts()
|
|
and intent['access_root']==str(access_root.absolute()),'immutable original readback')
|
|
payload=intent['payload'];read_only=True
|
|
rpc=linux_rpc if platform=='linux' else windows_rpc
|
|
if not read_only:
|
|
prepared=rpc(prefix,dict(payload,action='prepare'),folder);save(folder/'prepared-remote.json',prepared)
|
|
require(prepared==dict(id=case_id,prepared=True),'new guard scratch case')
|
|
destination=LINUX_REMOTE+'/'+case_id+'/guard' if platform=='linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-exe-contract-guards-'+case_id+'/guard.exe'
|
|
upload(prefix,manifest['artifacts'][platform],destination,folder,'pure-guard')
|
|
value=rpc(prefix,dict(payload,action='read' if read_only else 'run'),folder)
|
|
save(folder/('readback-'+str(uuid.uuid4())+'.json'),value)
|
|
if value.get('status'):
|
|
require(read_only and value.get('id')==case_id and value['status'] in ('remote_case_absent','prepared_without_start','started_without_result'),'read-only incomplete case')
|
|
print(json.dumps(dict(verified=False,case_id=case_id,platform=platform,status=value['status'],retry_allowed=False)));return
|
|
check_result(manifest,platform,value,payload)
|
|
proof=dict(verified=True,case_id=case_id,platform=platform,manifest_sha256=sha(path),runner_sha256=manifest['runner_sha256'],native=value)
|
|
destination=path.parent/(platform+'-passed.json')
|
|
if destination.exists(): require(load(destination)==proof,'preserve original identical proof')
|
|
else: save(destination,proof)
|
|
print(json.dumps(dict(verified=True,platform=platform,case_id=case_id,proof_sha256=sha(destination),installer_executed=False)))
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action',choices=('build-local','linux','windows','readback-linux','readback-windows'))
|
|
parser.add_argument('--manifest',type=Path);parser.add_argument('--case');parser.add_argument('--access-root',type=Path)
|
|
parser.add_argument('--execute-native-guard',action='store_true');args=parser.parse_args()
|
|
if args.action=='build-local':
|
|
require(not(args.manifest or args.case or args.access_root or args.execute_native_guard),'local manifest only');build()
|
|
elif args.action.startswith('readback-'):
|
|
require(args.manifest and args.case and args.access_root and not args.execute_native_guard,'same-case readback only')
|
|
execute(args.manifest,args.action.removeprefix('readback-'),args.access_root,args.case)
|
|
else:
|
|
require(args.manifest and args.access_root and args.execute_native_guard and not args.case,'explicit new native pure guard run')
|
|
execute(args.manifest,args.action,args.access_root)
|
|
|
|
|
|
if __name__=='__main__':
|
|
try: main()
|
|
except Exception as error:
|
|
print(json.dumps(dict(error='PURE_EXE_CONTRACT_GUARD_INCOMPLETE',error_class=type(error).__name__,details_suppressed=True)))
|
|
raise SystemExit(2) from None
|