diff --git a/deploy/windows_exe_guard_acceptance.py b/deploy/windows_exe_guard_acceptance.py new file mode 100644 index 0000000..ca9dc96 --- /dev/null +++ b/deploy/windows_exe_guard_acceptance.py @@ -0,0 +1,340 @@ +#!/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 diff --git a/docs/windows-exe-contract-guards.md b/docs/windows-exe-contract-guards.md new file mode 100644 index 0000000..e514369 --- /dev/null +++ b/docs/windows-exe-contract-guards.md @@ -0,0 +1,69 @@ +# Reine EXE-Fixture-Vertragsguards + +Der getrennte Runner `deploy/windows_exe_guard_acceptance.py` liefert ausschließlich +`linux-precondition-guard` und `windows-precondition-guard.exe` aus der unveränderten +Fixture-Qualifikation `f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061`. +Diese C-Programme prüfen mit `assert` nur Zustandsmatrix und feste Argumente. Sie +enthalten keine Installer-, Registry-, Datei-, Netzwerk- oder Dienstoperationen. +Die beiden eigentlichen Installer und ihre Originaldateien sind keine Deliveryrollen. + +Das neue private Manifest liegt unter +`devstate/windows-exe-contract-guards/build-aa4e2eea-4063-433c-83b1-75105e7fcdb6/manifest.json` +mit SHA-256 `982096ec11d19d7a23901d2e2330152aa6ae8938ddb7aaac0d64a3633d1a4ac6`. +Es bindet beide Guardbytes, ursprüngliche Qualifikation, neun Fixture-/Normquellen, +Runner und vorhandene Zugangsparser. Die fünf Compilerquellen, ursprünglichen +Links und bisherigen Qualifikationsberichte bleiben erhalten. + +Lokal tatsächlich bestanden: Python-Syntax, PowerShell-AST einschließlich Prüfung +auf Funktionsnamen mit vorhandenen Aliasen, Guardrollen-/Manifestprüfung, +begrenzte Nachwartezeiten und simulierter Antwortverlust mit ausschließlich +anschließendem Readback. Der private lokale Guardbericht hat SHA-256 +`a9c3b0e2dfc5225b7ce4af7787cb8c138a878ac2d5b2fa3a6199d7820c69d997`. +Keine native VM-Ausführung, kein SSH-Zugriff und keine Installation wurden dafür +durchgeführt. Dies ist weder ein Produkt- noch ein LocalService-Nachweis. + +Die folgenden Befehle sind **geplant, nicht ausgeführt**. Zuerst auf der echten +Cloud-Linux-VM, danach mit dessen vollständigem Exit-0-Bericht auf Windows: + +```sh +python3 deploy/windows_exe_guard_acceptance.py linux \ + --manifest /home/kevin/Schreibtisch/Coding/rust-discovery-windows-exe-fixture/devstate/windows-exe-contract-guards/build-aa4e2eea-4063-433c-83b1-75105e7fcdb6/manifest.json \ + --access-root /home/kevin/Schreibtisch/Coding/rust-discovery \ + --execute-native-guard + +python3 deploy/windows_exe_guard_acceptance.py windows \ + --manifest /home/kevin/Schreibtisch/Coding/rust-discovery-windows-exe-fixture/devstate/windows-exe-contract-guards/build-aa4e2eea-4063-433c-83b1-75105e7fcdb6/manifest.json \ + --access-root /home/kevin/Schreibtisch/Coding/rust-discovery \ + --execute-native-guard +``` + +Jeder Aufruf erzeugt einen neuen privaten Fall. Der entfernte Startintent wird vor +Ausführung dauerhaft und exklusiv erstellt. Linux verwendet einen eigenen +Netzwerk-Namespace, geleerte Umgebung und begrenzte Laufzeit/Dateiausgaben. +Windows verwendet einen eigenen Scratchpfad, geleerte Umgebung und begrenzte +Prozess- und Ausgabewartezeiten. Erfolg verlangt Exit 0 ohne Timeout und ohne +Ausgabe. Es gibt keine Rust-Testliste und keine zusätzlichen Vertragsfälle. + +Nach verlorener Antwort ausschließlich `readback-linux` bzw. `readback-windows` +mit denselben Manifest-/Accessargumenten und `--case ORIGINAL-UUID` verwenden, +**ohne** `--execute-native-guard`. Fehlende oder teilweise Berichte erlauben weder +erneuten Upload noch erneuten Start. Der Mainpfad dient allein dem Lesen bereits +vorhandener streng geparster und hostschlüsselgebundener Bootstrapzugänge; +Quellen, Artefakte und Berichte bleiben im EXE-Worktree. + + +## Tatsächlicher Cloud-Linux-Guard + +Root führte nach eigenem Quellenreview den festen reinen C-Guard auf der +permanenten Cloud-Linux-VM aus: Exit0, kein stdout/stderr, kein Timeout. +Fall `17f3b424-09ac-4501-90a0-a044d5fd733a`, ManifestSHA256 +`982096ec11d19d7a23901d2e2330152aa6ae8938ddb7aaac0d64a3633d1a4ac6`, +LinuxproofSHA256 +`ce46d28a52ec6d144cd284586a2a3ef7fdf9a809389ab8281ce8ebaf79545320`. +Neue eigene Bootstrap-Scratchdaten, leere Umgebung und neuer Netzwerknamespace; +kein Installer geliefert oder gestartet, keine Produktdaten oder Dienste geändert. + +Dies ist ein ausgeführter C-Assertionguard, keine erfundene Rust-Testzahl oder +Installationsabnahme. Windows-Guard und beide tatsächlichen EXE-Installations-/ +Upgrade-/Noop-/Fehlerabnahmen bleiben offen. Jede RMM-Paketwirkung benötigt +weiterhin den eigenen unveränderlichen Plan und tatsächliche WebUI-Genehmigung. diff --git a/docs/windows-exe-contract-proposal.md b/docs/windows-exe-contract-proposal.md new file mode 100644 index 0000000..5e311fa --- /dev/null +++ b/docs/windows-exe-contract-proposal.md @@ -0,0 +1,165 @@ +# Vorschlag für den engsten EXE-Vertrag nach Spezifikation1.19 + +Stand2026-11-14, **Root-Reviewentwurf, nicht beschlossen oder implementiert**. +Spezifikation1.19 erlaubt an dieser Stelle ausschließlich den bestehenden +MSI-Vertrag. Die folgenden Änderungen benötigen eine bewusste Präzisierung1.20 +durch Root. Keine neuen Exporte, Capabilities, Policies oder Ausführungsgates +wurden aktiviert. Der Sourcebuild ist kein nativer Installationsnachweis. + +## 1. Exakt zwei eigene Artefakte und ein typisierter Plan + +Ausgangspunkt ist der geprüfte Fixturebuild +`build-e85496e8-b6dd-4834-8c17-843ee5c5b3da`, Qualification-SHA256 +`f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061`. +Die Kandidaten sind bewusst unsignierte Entwicklungsartefakte: + +| Ziel | EXE-SHA256 | Bytes | +| --- | --- | --- | +| 1.0.0 | `9a972430614625b99985cd3db69f7f8f47e561c954697d57ba21e79fd5b787dc` | 23040 | +| 1.1.0 | `196d22893eaea74d332782c597d4cbce631522006786a4aae074ad0a2bea8c89` | 23552 | + +Nur diese beiden Artefakte gehören zum ersten EXE-Profil; kein beliebiges EXE +mit ähnlich benannten Registrywerten. Ein anderer Build braucht eine neue +explizite Profil-/Rezeptentscheidung und eigene Qualifikation. Die einzige +abgeleitete Argumentliste lautet `--quiet --norestart`; keine Argumentfelder, +URLs, Repair-, Uninstall-, Shell-, Dienst- oder Rebootoptionen. + +`Action::EnsurePackage` erhält **am Ende** ein optionales +`windows_exe_manifest: Option>`. Fehlend wird als None +ausgelassen; vorhandenes null, Enum-Objekte und unbekannte Felder werden +abgewiesen. JsonSchema beschreibt die optionale Eigenschaft ohne null. +Genau eines von APT/MSI/EXE darf vorhanden sein. Alte APT-/MSI- und Linux- +Job-/Planbytes müssen unverändert bleiben; kein JobPayload-/Grant-/IPC- +Versionswechsel. Die Action ist ausschließlich `execution_identity=system`, +`provider=exe`, `package=rmm-windows-exe-fixture`, `architecture=x64`, +`installation_context=machine`, `recipe_version=1`, exakte Version und Recipe-ID. + +Vorgeschlagene kanonische Feldordnung: + +* `ResolvedWindowsExe`: `recipe`, `recipe_sha256`. +* `WindowsExeRecipe`: `schema_version=1`, `recipe_id`, `recipe_version=1`, + `platform=windows`, `architecture=x64`, `context=machine`, + `command_profile=exe_fixture_quiet_no_reboot_v1`, `artifact`, `postcondition`, + `no_reboot=true`, optionales `predecessor`. +* `artifact`: `artifact_id`, `sha256`, `bytes`, mit exakt einem obigen Paar. +* `postcondition`: `registry_hive=hklm`, `registry_view=64` als strikter String, + `registry_key=SOFTWARE\\RustDiscovery\\ExeFixture`, + `product_id=RustDiscovery.ExeFixture`, `product_version`, + `payload_path=C:\\Program Files\\RustDiscoveryFixtures\\exe-payload.txt`, + `payload_sha256`, `payload_bytes=33`. + +Die Recipe-IDs sind `rmm-windows-exe-fixture-install-1.0` und +`rmm-windows-exe-fixture-upgrade-1.1`. `predecessor` ist für1.0 abwesend und +für1.1 zwingend die vollständige feste1.0-Nachbedingung, ebenfalls strict +nonnull/None-omit. Keine frei wählbaren Registrywerte oder Zielpfade. +`recipe_version` ist der String `"1"`, nicht die JSON-Zahl1; `schema_version` +ist die Zahl1. Der Recipehash ist SHA256 der exakten Domain-Serialisierung einschließlich +Artifact-ID; alle folgenden Bindungen verwenden dieselben Bytes. + +## 2. Tenantkatalog, Genehmigung und ausdrückliche SYSTEM-Obergrenze + +Eine eigene immutable `windows_exe_recipes`-Tabelle folgt dem MSI-Muster: +Tenant-/Rezept-/Versions- und Tenant-/Recipehash-Eindeutigkeit, zusammengesetzter +FK auf Tenant/Artifact-ID/SHA/Bytes, FORCE RLS, nur SELECT/INSERT, Verbot von +UPDATE/DELETE. Import/List sind vom MSI-/APT-Katalog getrennt. Kein zusätzlicher +generischer Downloadpfad: pro Job genau eine automatische Artifactreferenz, +vollständige Recipe- und Artifactmengen des Plans; zunächst homogene EXE-Pläne. +Plan, Submit, WebUI-Genehmigung, Delivery, Permit und mTLS-Artifactdownload +prüfen dieselbe Bindung und die aktuellen Rechte erneut. + +Bestehende Rechte `operations:plan`, `operations:submit`, `plans:approve` und +`system:execute` bleiben ihre jeweiligen Voraussetzungen. Policies genehmigen +weiterhin nichts. Eine neue zentrale **und** lokale SYSTEM-Policy/Settings- +Schema3 ergänzt höchstens zwei eindeutige `allowed_exe_recipe_sha256`. +Schema1 bleibt SCM-only, Schema2 SCM/MSI-only; beide verweigern EXE. Schema3 +behält die vorhandenen MSI-Hashes und ergänzt EXE nur ausdrücklich. Das neue +optionale Feld fehlt in alten Serialisierungen; null und fremde Hashes werden +abgewiesen. Tenant/Asset/Agent/Generationen/Principals und Helper-Policy-/Binary- +Pins bleiben vollständig gebunden, `allow_reboot=false` bleibt Pflicht; +maximal120Sekunden Originalbudget und65536Ausgabebytes wie beim MSI-Profil. + +Zusätzlich nötig sind die vorhandenen Windows-/Sync-/Helper- und +`ensure_package`/`system:ensure_package`-Capabilities sowie die **neue enge** +`package.exe.fixture/1`; keine allgemeine SYSTEM-EXE- oder Skriptautorität. +Alle bleiben bis getrennter nativer Qualifikation deaktiviert. Die WebUI zeigt +SYSTEM, Recipe-/Artifacthash, feste Argumente, Budget, Vorgänger und vollständige +Nachbedingungen ausschließlich aus verifizierten gespeicherten Planbytes. +Jobs/Payload/ResolvedTargets/Preview-Aliases und spätere Mutationen werden wie +bei MSI gegengeprüft; echte Domain-Goldenbytes verhindern None-/Feldordnungsfehler. + +## 3. Derselbe Delegationskern, ein enger EXE-Provider + +Der vorhandene mTLS-Client lädt nur das genehmigte Job-/Attempt-Artifact mit +exakter Länge/SHA und höchstens256KiB. Ein fest vorprovisionierter Actor- +Stagingbereich `exe-stage` und SYS-Cache `.exe` erweitern die vorhandenen +Cachehelfer über einen **geschlossenen MSI/EXE-Typ**, nicht über Callerpfade, +URLs oder IPC-Bytearrays. SYSTEM prüft erneut Parent-/Reparse-/ACL-/File-ID- +Bindung sowie Bytes/SHA, kopiert unabhängig in den geschützten Cache und hält +die eigenen Archivhandles. Fehlende Konfiguration führt zu not_configured; +keine implizite Ordner-/ACL-Reparatur. + +OriginalRequest-/Grant-/Boot-/Helper-Lineage, Intent-CAS, dauerhafter Cancel- +Deny, Abandon, RawFullTupleMirror und SignedSync werden **nicht dupliziert**. +Historische und aktuelle Auth-/Clock-/Scope-/Policyprüfungen bleiben erhalten. +Atomarer Helper-Start erfolgt vor Cache-/Installerwirkung; Abandon führt keine +Cache-/Providerarbeit aus. Das ursprüngliche monotone Gesamtbudget umfasst +Cache, Metadaten, Noop, Start, Beobachtung und Nachprüfungen. Frische Peer-/ +Clock-/Fence-/Cancelprüfung unmittelbar vor Noop oder Start, ohne langlebigen +SQLite-Lesesnapshot. Der letzte Read→Spawn-Abstand ist keine Rollbackgarantie. + +Ein neuer enger EXE-Provider startet ausschließlich das gehaltene Cacheartefakt +mit den festen Argumenten, ohne Shell/Netz/weitere Prozesse. Die bisherige +`UnsettledMsi`-Verwaltung wird am vorhandenen Dispatcher zu einem geschlossenen +`OwnedPackageChild::{Msi,Exe}` erweitert: **ein** gemeinsamer gesperrter Slot und +Paketressourcen-Lock, OriginalRequest-/Grantbindung, Child- und Archivhandles. +Nach unklarem Timeout bleiben diese erhalten; keine weiteren MSI-/EXE-Starts, +bis derselbe Prozess nachweislich zur Ruhe gekommen ist. Kein globales Kill, +PID-Adoption, automatischer Retry oder nachträgliches Umschreiben des Unknown. +Helpercrash hebt die ursprüngliche Ledgersperre nicht auf. Cancel nach Start +liefert keine globale Prozessbeendigung oder Zusage zurückgenommener Wirkung; +derselbe Versuch wird weiter beobachtet und sein Ausgang ehrlich festgehalten. + +## 4. Unabhängige Zustands- und Ergebnisregeln + +Der Provider liest nativ ausschließlich HKLM64 und die feste Nutzdatei: +genau7 korrekt typisierte Fixturewerte, keine Unterkeys/Registrylinks; gehaltene +geschützte Nonreparse-Datei mit File-ID, genau33Bytes und festem SHA. Payload1.0 +hat SHA `7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf`, +Payload1.1 `e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0`. +Die übrigen Registrywerte/-typen stehen unverändert im Fixture-README. +Kein Erfolg aus stdout oder EXE-Exit allein, kein Win32_Product-Aufruf. + +| Beobachtung innerhalb des Originalbudgets | Dauerhaftes Ergebnis | +| --- | --- | +| Unabhängig exakt gewünschter Zustand, frischer Fence | erfolgreicher Provider-Noop, kein Child, Exit=None | +| 1.0: vollständig leer; 1.1: vollständig exakt1.0 | einziger jeweils zulässiger Startbestand | +| Widersprüchlicher/teilweiser Bestand vor Start | verweigert, keine automatische Reparatur | +| Child Exit0 und unabhängige vollständige Zielnachbedingungen | erfolgreich; Prozessstart ist kein Beweis tatsächlich veränderter Bytes | +| Exakter Fixture-Exit10 vor eigener Mutation | failed; ursprünglicher Grant bleibt konsumiert, kein erfundenes NoStart/Unlock | +| Exit20 nach möglicher Teilwirkung | unknown, auch wenn der aktuelle Bestand zufällig vollständig erscheint | +| Unerwarteter Exit, unklare Beobachtung, überschrittenes Budget | unknown bei möglicher Wirkung, kein Retry/Retro-Success | + +MSI-Codes3010/1641/1618 bekommen **keine** EXE-Sonderbedeutung. Der feste +Fixturecode enthält keinen Rebootaufruf; Exit0 beweist keine allgemeine +Rebootfreiheit beliebiger EXEs oder Abwesenheit eines ambienten Pendingflags. +Nur der normale signierte Sync darf verbrauchte Ressourcen freigeben. + +## 5. Kleinste Dateigrenze und fehlende Nachweise + +| Bereich | Geplanter Eingriff nach Root-Entscheidung | +| --- | --- | +| Norm | Root: Spezifikation1.20, project-decisions, development; die beschriebenen engen Ausnahmen ausdrücklich festhalten | +| Domain | neu `windows_exe.rs`; `lib.rs`/`jobs.rs` additive Typen/Validatoren/Codec-Goldens, keine alten Feldänderungen | +| Backend | neuer EXE-Katalog und Migration nach0014; vorhandene Jobs/Policy/Gateway/Artifact-Routen um genau den neuen Typ ergänzen | +| WebUI | bestehende API/Safety/Main und betroffene Tests; verifizierte Projektion und eigener Katalogimport/-list | +| Windows | neuer `exe_package.rs`; vorhandene Cachehelfer, SYSTEM-Dispatcher/Settings, helper_runtime/runtime/lib; Intent-/IPC-Operationsvertrag unverändert | +| Core/Protocol | keine neue Zustandsmaschine, kein Unlock-/Grantcodec; Domain-gesteuerte Scopeprüfung nur falls technisch erforderlich additiv | + +Bereits vorhanden: Fixture-Source-Review und lokaler GNU-Build mit ausgeführtem +reinem Linux-Guard; Windows-Guard und Installer nur gebaut. Offen sind echte +Linux→Windows-Guardabnahme, Domain/Schema-/RLS-/Plan-/Policy-/UI-Belege, +nativer sicherer Cache-/PERSIST-/HKLM64-/File-ID-Nachweis sowie separat per +WebUI genehmigte1.0-Installation,1.1-Upgrade und Noops/Fehlerpfade. Source, +Build, native Unitqualifikation und echte Installerwirkung bleiben getrennte +Abnahmeschritte. Vor deren Nachweis keine Ready-/Capability-/Clock-Gateflips; +keine EXE-Ausführung auf dem Notebook. diff --git a/docs/windows-exe-fixture-source.md b/docs/windows-exe-fixture-source.md new file mode 100644 index 0000000..bb34e75 --- /dev/null +++ b/docs/windows-exe-fixture-source.md @@ -0,0 +1,60 @@ +# Windows EXE-Fixture: Quelle und lokale Artefakte + +Stand 2026-11-14, eigener Zweig `codex/windows-exe-fixture` ab `287a784`. +Nur die fünf neuen Dateien unter `tools/windows-exe-fixture/` und diese Notiz. +Kein Domain-/Core-/MSI-/Runtime-/Helper-/Backend-/UI- oder Normvertrag geändert; +kein EXE-Provider exportiert. Der feste MSI-Schnitt aus Version1.19 bleibt +unverändert. Die zusätzliche Fixture deckt noch keine EXE-Abnahme ab. + +Die Quelle ist ein kleines, eigenständiges SYSTEM-/AMD64-Programm ohne freien +Pfad, URL oder Command. Genau `--quiet --norestart`; eigene HKLM64-Kennung und +33Byte-Nutzdatei getrennt vom MSI. Ausgangsbestand, Zielversion, Bytehash und +Noop-/Upgradegrenzen stehen im [README](../tools/windows-exe-fixture/README.md). +Nach dem ersten möglichen Schreibzugriff bleibt ein Fehler unbestimmt, ohne +Retry, Repair oder Rollback. Produktregistry und Nutzdatei müssen durch den +späteren Provider unabhängig gelesen werden. Geschützter Fixtureordner ist +Voraussetzung; keine stillschweigende ACL-Reparatur. + +## Tatsächlich lokal ausgeführt + +`python3 tools/windows-exe-fixture/build.py`, privater finaler Fall +`devstate/windows-exe-fixture/build-e85496e8-b6dd-4834-8c17-843ee5c5b3da/`. +Qualification-SHA256 +`f74c207e8fa6a9254759b103e8d81c962ec2becca9ee2feb9b1156fd395e1061`. +Neun Quellen-/Norminputs vor und nach dem Build identisch; festes vorhandenes +Dockerimage, Netzwerk aus, Build unter Host-UID/GID, kein Zugriff auf Zugänge. + +- Linux: reiner Zustands-/Argumentguard im Container kompiliert und tatsächlich + mit Exit0 ausgeführt, `-std=c11 -O2 -Wall -Wextra -Werror`. +- Windows: derselbe reine Guard und beide Installer mit GNU/Werror kompiliert, + nur gelinkt, **nicht ausgeführt**. AMD64-PE-Strukturen geprüft. +- Installer1.0:23040Bytes, + SHA256`9a972430614625b99985cd3db69f7f8f47e561c954697d57ba21e79fd5b787dc`. +- Installer1.1:23552Bytes, + SHA256`196d22893eaea74d332782c597d4cbce631522006786a4aae074ad0a2bea8c89`. +- Windowsguard:15360Bytes, + SHA256`1929a20c041c96337a8e2665b7aad4ea8a46604ccddebcaab68242c7387b84cf`. +- Linuxguard:16128Bytes, + SHA256`5af37aa734e47dac480a2fe4d6039d4bf6708bb392f4b00320d1c7ab79fac439`, + nur`libc.so.6`, höchste referenzierte glibc2.34. +- Installerimports ausschließlich ADVAPI32/bcrypt/KERNEL32/msvcrt. Originale + Linkdateien und getrennte Stripdateien erhalten. Fixtureartefakte ausdrücklich + unsigniert; kein produktiver Installer-/Signiernachweis. + +Ein ursprünglicher Build kompilierte erfolgreich, konnte seine root-owned +600-Artefakte aber nicht im Hostprozess lesen. Dieser unvollständige Fall samt +Fehlerbeleg bleibt erhalten; der Builder verwendet danach explizit Host-UID/GID. +Der nächste erfolgreiche Zwischenbuild vor der ergänzten nativen AMD64-Prüfung +bleibt ebenfalls historisch erhalten. Nur der obige finale Fall ist der aktuelle +lokale Quellen-/Artefaktbeleg. + +## Geplant, nicht ausgeführt + +Zuerst denselben wirkungslosen Guard auf der Cloud-Linux-VM, danach auf Windows +nachweisen. Danach benötigen EXE-Rezept, Katalog-/Artefaktbindung, eigene +SYSTEM-Policy, Helpercache, Provider-Outcome-/Cancel-/Unknown-Grenzen und WebUI +jeweils ihre explizite Vertragserweiterung und Qualifikation. Es gibt keinen +Installationsbootstrap oder freigabefähigen RMM-EXE-Job in dieser Lieferung. +Native Erstinstallation,1.0→1.1, Noops, Registry64-/ACL-/Handle-/Teilwirkungs- +und Absturznachweise sind offen. Jede Zielwirkung braucht den festen realen +WebUI-Plan; Linux-/Windows-Guard oder Crossbuild ersetzt dies nicht. diff --git a/tools/windows-exe-fixture/README.md b/tools/windows-exe-fixture/README.md new file mode 100644 index 0000000..783ec12 --- /dev/null +++ b/tools/windows-exe-fixture/README.md @@ -0,0 +1,71 @@ +# Eigene EXE-Fixture: nur Artefaktauthoring + +Stand 2026-11-14. Dieser eigenständige C-Quelltext ist **nicht** in Domain, +Agent, Helper, Policy, Capability oder Backend eingebunden. Spezifikation1.19 +bleibt der enge MSI-Vertrag; dieses zusätzliche EXE-Artefakt erteilt keine +Ausführungserlaubnis und ändert diesen Vertrag nicht. Keine Installation auf +Notebook oder VM durch den Builder. Die späteren EXE-Rezept-/Provider-/WebUI- +und nativen Fehlerabnahmen fehlen. + +Die beiden fest kompilierten Versionen `10` / `11` bedeuten1.0.0 /1.1.0. +Einziger Installeraufruf ist jeweils `--quiet --norestart` in genau dieser +Reihenfolge. Es gibt keinen Pfad-, URL-, Command-, Repair-, Uninstall- oder +Rebootparameter. Der Prozess muss tatsächlich SYSTEM sein. Kein Netzwerk, +Dienststart, Unterprozess oder Neustartaufruf. + +Feste eigene Nachbedingungen, getrennt vom MSI: + +- Datei `C:\Program Files\RustDiscoveryFixtures\exe-payload.txt`, genau33Bytes. +- Version1.0.0: ASCII `RustDiscovery EXE fixture 1.0.0\r\n`, SHA256 + `7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf`. +- Version1.1.0: ASCII `RustDiscovery EXE fixture 1.1.0\r\n`, SHA256 + `e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0`. +- Registry **HKLM64** `SOFTWARE\RustDiscovery\ExeFixture`, genau7Werte und keine + Unterkeys: `ProductId=RustDiscovery.ExeFixture`, `Version`, `PayloadSHA256`, + `Architecture=x64`, `Context=machine` jeweilsREG_SZ; `PayloadBytes=33` und + `NoReboot=1` jeweilsREG_DWORD. Registry ist unabhängig von der Nutzdatei lesbar. + +| Zielartefakt | Vollständiger Ausgangsbestand | Entscheidung | +| --- | --- | --- | +| 1.0 | Key und Datei fehlen | Erstinstallation | +| 1.0 | Registry und Datei exakt1.0 | Noop, keine Writeoperation | +| 1.0 | Exakt1.1 oder irgendein Teil-/Fremdzustand | Verweigern | +| 1.1 | Registry und Datei exakt1.0 | Upgrade auf1.1 | +| 1.1 | Registry und Datei exakt1.1 | Noop, keine Writeoperation | +| 1.1 | Leer oder irgendein Teil-/Fremdzustand | Verweigern | + +Der bestehende geschützte Fixtureordner muss vorab vorhanden sein; der Installer +repariert keine Ordner/ACL. Gehaltene Elternhandles verweigern Umbenennung, +Reparse- und Hardlinkblätter werden verweigert, nur SYSTEM/Administrators dürfen +an Zielobjekten schreiben. Die Nutzdatei wird beim Upgrade anhand ihrer +ursprünglichen File-ID und Bytes erneut geprüft und exklusiv gegen weitere +Writer gehalten. Registrylinks/Fremdwerte werden nicht übernommen. Neue eigene +Datei-/Registryobjekte bekommen SYS/Admin-Schreibrechte und Benutzer-Leserechte; +eine vorhandene ACL wird nicht verändert. + +**Nicht atomar:** Nutzdatei und Registry sind getrennte Wirkungen. Exit0 bedeutet +nur das vom Fixtureprozess selbst bestätigte vollständige Ergebnis oder Noop; +ein künftiger Provider muss Registry und Datei unabhängig nachprüfen. Exit10 +verweigert vor einer eigenen Mutation. Exit20 bedeutet mögliche/teilweise Wirkung +nach der ersten Datei-/Keymutation, ausdrücklich **unknown**, kein Retry, +Rollback, Repair oder Freigabe des ursprünglichen Versuchs. Timeout/Prozessverlust +nach Übergabe kann unabhängig vom Exit ebenfalls unknown bedeuten. Diese eigenen +Exitcodes sind keine MSI-Exitsemantik. + +## Lokaler Build + +Geplanter Builderaufruf: `python3 tools/windows-exe-fixture/build.py`. +Der Builder verwendet nur das gepinnte vorhandene GNU-Buildimage, Netzwerk aus, +keine Hostinstallation. Er kompiliert/runnt zuerst den reinen Linux-Guard, +kompiliert dessen Windows-PE sowie beide Installer, erhält Original- und +Stripdateien und speichert einen create-only privaten Quell-/Compiler-/Hash- +Beleg unter `devstate/windows-exe-fixture/build-/`. Er führt keine Windows-EXE +aus. Gehashte Fixtureartefakte sind zunächst bewusst **unsigniert**; das ist +kein Produktions-Signier- oder Installationsnachweis. + +`contract_test.c` prüft ausschließlich die feste Zustands-/CLI-Matrix, ohne +Datei/Registry/Netz und ohne Simulation einer Installerwirkung. Derselbe Guard +muss später zuerst auf der Cloud-Linux-VM, danach auf der Windows-VM laufen. +Native HKLM64-/ACL-/File-ID-/Install-/Upgrade-/Noop-/Teilwirkungsnachweise sind +noch offen. Jede tatsächliche Installation benötigt einen neuen festen Plan und +die reale WebUI-Genehmigung; Bootstrap/SFTP allein ist kein Paketnachweis. diff --git a/tools/windows-exe-fixture/build.py b/tools/windows-exe-fixture/build.py new file mode 100644 index 0000000..02e222c --- /dev/null +++ b/tools/windows-exe-fixture/build.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Host-only, fixed-image EXE authoring. Never uploads or executes an installer.""" +import hashlib +import json +import os +from pathlib import Path +import subprocess +import uuid + +ROOT = Path(__file__).resolve().parents[2] +IMAGE = 'sha256:1b2fd985d2c1fcc3545ace602405dc68fa899201bd8a73fa319ff96377203fa9' +NAMES = ('contract.h', 'contract_test.c', 'fixture.c', 'build.py', 'README.md') + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def snapshot(): + paths = [ROOT/'tools/windows-exe-fixture'/n for n in NAMES] + paths += [ROOT/n for n in ('AGENTS.md', 'Rust_RMM_Implementierungsspezifikation.md', 'docs/project-decisions.md', 'docs/development.md')] + return {str(p.relative_to(ROOT)): sha(p) for p in paths} + + +def write(path, value): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as f: + json.dump(value, f, indent=2, sort_keys=True);f.flush();os.fsync(f.fileno()) + + +def main(): + os.umask(0o077) + base = ROOT/'devstate/windows-exe-fixture';base.mkdir(parents=True, exist_ok=True, mode=0o700) + case = base/('build-'+str(uuid.uuid4()));case.mkdir(mode=0o700) + before = snapshot();write(case/'intent.json', {'image': IMAGE, 'source_files': before, 'build_only': True, 'native_installer_execution': False, 'network': False}) + script = '''set -eu +cd /source +cc --version > /out/linux-compiler.txt +x86_64-w64-mingw32-gcc --version > /out/windows-compiler.txt +cc -std=c11 -O2 -Wall -Wextra -Werror contract_test.c -o /out/linux-precondition-guard +/out/linux-precondition-guard +x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror contract_test.c -Wl,--no-insert-timestamp -o /out/windows-precondition-guard.original.exe +x86_64-w64-mingw32-strip --strip-all /out/windows-precondition-guard.original.exe -o /out/windows-precondition-guard.exe +for version in 10 11; do + x86_64-w64-mingw32-gcc -std=c11 -O2 -Wall -Wextra -Werror -municode -DFIXTURE_VERSION=$version fixture.c -Wl,--no-insert-timestamp,--nxcompat,--dynamicbase,--high-entropy-va -ladvapi32 -lbcrypt -o /out/RustDiscoveryExeFixture-$version.original.exe + x86_64-w64-mingw32-strip --strip-all /out/RustDiscoveryExeFixture-$version.original.exe -o /out/RustDiscoveryExeFixture-$version.exe + x86_64-w64-mingw32-objdump -p /out/RustDiscoveryExeFixture-$version.exe > /out/imports-$version.log +done +readelf -h /out/linux-precondition-guard > /out/linux-elf-header.log +readelf -d /out/linux-precondition-guard > /out/linux-elf-needed.log +readelf --version-info /out/linux-precondition-guard > /out/linux-elf-versions.log +chmod 600 /out/* +''' + args = ['docker', 'run', '--rm', '--user', str(os.getuid())+':'+str(os.getgid()), '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=64m', '-v', str(ROOT/'tools/windows-exe-fixture')+':/source:ro', '-v', str(case)+':/out', '--entrypoint', 'sh', IMAGE, '-c', script] + result = subprocess.run(args, capture_output=True, timeout=120) + write(case/'compiler-output.json', {'exit_code': result.returncode, 'stdout': result.stdout.decode(errors='replace'), 'stderr': result.stderr.decode(errors='replace')}) + after = snapshot();write(case/'source-after.json', after) + if result.returncode != 0 or before != after: + raise RuntimeError('FIXTURE_BUILD_FAILED_RETAINED_'+case.name) + artifacts = {} + for path in sorted(case.glob('*.exe')): + b = path.read_bytes();pe = int.from_bytes(b[60:64], 'little') + if b[:2] != b'MZ' or b[pe:pe+4] != b'PE\0\0' or int.from_bytes(b[pe+4:pe+6], 'little') != 0x8664: + raise RuntimeError('FIXTURE_PE_AMD64_REQUIRED') + if not '.original.' in path.name and len(b) > 262144: + raise RuntimeError('FIXTURE_ARTIFACT_BUDGET') + artifacts[path.name] = {'sha256': sha(path), 'bytes': len(b), 'architecture': 'AMD64', 'authenticode': 'not_signed_fixture_only'} + artifacts['linux-precondition-guard'] = {'sha256': sha(case/'linux-precondition-guard'), 'bytes': (case/'linux-precondition-guard').stat().st_size} + imports = {str(v): [l.strip().split(':', 1)[1].strip() for l in (case/f'imports-{v}.log').read_text().splitlines() if 'DLL Name:' in l] for v in (10, 11)} + write(case/'qualification.json', {'image': IMAGE, 'source_files': before, 'source_before_after_equal': True, 'linux_pure_precondition_guard': 'passed_container_only', 'windows_pure_guard': 'linked_not_executed', 'windows_installer': 'linked_not_executed', 'cloud_linux_native_guard': 'not_executed', 'windows_native': 'not_executed', 'artifacts': artifacts, 'imports': imports, 'no_installer_run': True, 'no_upload': True}) + print(json.dumps({'case': str(case.relative_to(ROOT)), 'qualification_sha256': sha(case/'qualification.json'), 'artifacts': artifacts})) + + +if __name__ == '__main__': + main() diff --git a/tools/windows-exe-fixture/contract.h b/tools/windows-exe-fixture/contract.h new file mode 100644 index 0000000..beda8b6 --- /dev/null +++ b/tools/windows-exe-fixture/contract.h @@ -0,0 +1,27 @@ +#ifndef RMM_EXE_FIXTURE_CONTRACT_H +#define RMM_EXE_FIXTURE_CONTRACT_H +#include +/* This authoring contract is NOT exported by an agent, helper or domain crate. */ +enum fixture_state { FIXTURE_ABSENT, FIXTURE_10, FIXTURE_11, FIXTURE_CONFLICT }; +enum fixture_step { FIXTURE_DENY, FIXTURE_INSTALL, FIXTURE_UPGRADE, FIXTURE_NOOP }; +static enum fixture_state fixture_state(unsigned registry, unsigned payload) { + if (registry == 0 && payload == 0) return FIXTURE_ABSENT; + if (registry == 10 && payload == 10) return FIXTURE_10; + if (registry == 11 && payload == 11) return FIXTURE_11; + return FIXTURE_CONFLICT; +} +static enum fixture_step fixture_step(unsigned desired, enum fixture_state before) { + if (desired == 10) { + if (before == FIXTURE_ABSENT) return FIXTURE_INSTALL; + if (before == FIXTURE_10) return FIXTURE_NOOP; + } else if (desired == 11) { + if (before == FIXTURE_10) return FIXTURE_UPGRADE; + if (before == FIXTURE_11) return FIXTURE_NOOP; + } + return FIXTURE_DENY; +} +static int fixture_arguments(int argc, const wchar_t *const *argv) { + return argc == 3 && wcscmp(argv[1], L"--quiet") == 0 + && wcscmp(argv[2], L"--norestart") == 0; +} +#endif diff --git a/tools/windows-exe-fixture/contract_test.c b/tools/windows-exe-fixture/contract_test.c new file mode 100644 index 0000000..6e1744e --- /dev/null +++ b/tools/windows-exe-fixture/contract_test.c @@ -0,0 +1,25 @@ +/* Pure guard only. No OS, registry, file, installer or network operations. */ +#include "contract.h" +#include +int main(void) { + const enum fixture_step expected[2][4] = { + { FIXTURE_INSTALL, FIXTURE_NOOP, FIXTURE_DENY, FIXTURE_DENY }, + { FIXTURE_DENY, FIXTURE_UPGRADE, FIXTURE_NOOP, FIXTURE_DENY } + }; + const wchar_t *good[] = { L"fixture.exe", L"--quiet", L"--norestart" }; + const wchar_t *foreign[] = { L"fixture.exe", L"--quiet", L"C:\\somewhere" }; + for (unsigned target = 0; target < 2; ++target) + for (unsigned state = 0; state < 4; ++state) + assert(fixture_step(10 + target, (enum fixture_state)state) == expected[target][state]); + assert(fixture_step(12, FIXTURE_ABSENT) == FIXTURE_DENY); + assert(fixture_state(0, 0) == FIXTURE_ABSENT); + assert(fixture_state(10, 10) == FIXTURE_10); + assert(fixture_state(11, 11) == FIXTURE_11); + assert(fixture_state(0, 10) == FIXTURE_CONFLICT); + assert(fixture_state(10, 11) == FIXTURE_CONFLICT); + assert(fixture_state(99, 99) == FIXTURE_CONFLICT); + assert(fixture_arguments(3, good)); + assert(!fixture_arguments(2, good)); + assert(!fixture_arguments(3, foreign)); + return 0; +} diff --git a/tools/windows-exe-fixture/fixture.c b/tools/windows-exe-fixture/fixture.c new file mode 100644 index 0000000..02b57fb --- /dev/null +++ b/tools/windows-exe-fixture/fixture.c @@ -0,0 +1,208 @@ +/* Fixed own EXE fixture authoring source. Not an exported RMM provider. + * No shell, network, service, reboot, repair, retry or caller-selected target. + * An error after the first file/key mutation returns20: effect unresolved. + */ +#define _WIN32_WINNT 0x0a00 +#include +#include +#include +#include +#include +#include +#include "contract.h" +#if !defined(FIXTURE_VERSION) || (FIXTURE_VERSION != 10 && FIXTURE_VERSION != 11) +#error Compile exactly one fixed fixture version10 or11 +#endif +static const wchar_t *const ROOT = L"C:\\Program Files\\RustDiscoveryFixtures"; +static const wchar_t *const FILE_PATH = L"C:\\Program Files\\RustDiscoveryFixtures\\exe-payload.txt"; +static const wchar_t *const PARENT_KEY = L"SOFTWARE\\RustDiscovery"; +static const wchar_t *const PRODUCT_KEY = L"ExeFixture"; +static const wchar_t *const HASH10 = L"7b8019c151f3953261b3afbbea1b59ca7112ab09c7a2911d24d17921d6fd6adf"; +static const wchar_t *const HASH11 = L"e1da48d2a8b89d66db822c24dc2ef7a0cfc13bce11875f15157d03081979d3f0"; +static const char *payload(unsigned version) { + return version == 10 ? "RustDiscovery EXE fixture 1.0.0\r\n" : "RustDiscovery EXE fixture 1.1.0\r\n"; +} +static const wchar_t *version_text(unsigned version) {return version == 10 ? L"1.0.0" : L"1.1.0";} +static const wchar_t *hash_text(unsigned version) {return version == 10 ? HASH10 : HASH11;} +static int privileged_sid(PSID sid) { + return IsWellKnownSid(sid, WinLocalSystemSid) || IsWellKnownSid(sid, WinBuiltinAdministratorsSid); +} +static int protected_object(HANDLE handle, SE_OBJECT_TYPE kind, DWORD read_mask) { + PSID owner = NULL; PACL dacl = NULL; PSECURITY_DESCRIPTOR sd = NULL; + if (GetSecurityInfo(handle, kind, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &owner, NULL, &dacl, NULL, &sd) != ERROR_SUCCESS) return 0; + int valid = owner && privileged_sid(owner) && dacl && dacl->AceCount; + for (DWORD i = 0; valid && i < dacl->AceCount; ++i) { + PVOID raw = NULL; + if (!GetAce(dacl, i, &raw)) {valid = 0; break;} + ACCESS_ALLOWED_ACE *ace = raw; + if (ace->Header.AceType != ACCESS_ALLOWED_ACE_TYPE + || ace->Header.AceSize < sizeof(*ace)) {valid = 0; break;} + if (ace->Header.AceFlags & INHERIT_ONLY_ACE) continue; + PSID who = &ace->SidStart; + if (!IsValidSid(who) || (!privileged_sid(who) && (ace->Mask & ~read_mask))) valid = 0; + } + LocalFree(sd); return valid; +} +static int system_process(void) { + HANDLE token = NULL; _Alignas(8) BYTE buffer[128]; DWORD bytes = sizeof(buffer); + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) return 0; + int ok = GetTokenInformation(token, TokenUser, buffer, bytes, &bytes) + && IsWellKnownSid(((TOKEN_USER *)buffer)->User.Sid, WinLocalSystemSid); + CloseHandle(token); return ok; +} +static int regular(HANDLE file, int directory, BY_HANDLE_FILE_INFORMATION *info) { + return GetFileInformationByHandle(file, info) + && !(info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) + && !!(info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == directory + && (directory || info->nNumberOfLinks == 1); +} +static int same_file(const BY_HANDLE_FILE_INFORMATION *a, const BY_HANDLE_FILE_INFORMATION *b) { + return a->dwVolumeSerialNumber == b->dwVolumeSerialNumber + && a->nFileIndexHigh == b->nFileIndexHigh && a->nFileIndexLow == b->nFileIndexLow; +} +static int file_version(HANDLE file) { + BY_HANDLE_FILE_INFORMATION info; BYTE bytes[64], digest[32]; DWORD read = 0; + BCRYPT_ALG_HANDLE alg = NULL; BCRYPT_HASH_HANDLE hash = NULL; BYTE *object = NULL; + DWORD size = 0, got = 0; wchar_t hex[65]; int version = 99; + if (!regular(file, 0, &info) || !protected_object(file, SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE) + || info.nFileSizeHigh || info.nFileSizeLow != 33 + || SetFilePointer(file, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER + || !ReadFile(file, bytes, sizeof(bytes), &read, NULL) || read != 33) return 99; + if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA256_ALGORITHM, NULL, 0) < 0) goto done; + if (BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&size, sizeof(size), &got, 0) < 0 + || size == 0 || size > 4096) goto done; + object = HeapAlloc(GetProcessHeap(), 0, size); if (!object) goto done; + if (BCryptCreateHash(alg, &hash, object, size, NULL, 0, 0) < 0 + || BCryptHashData(hash, bytes, read, 0) < 0 + || BCryptFinishHash(hash, digest, sizeof(digest), 0) < 0) goto done; + for (unsigned i = 0; i < 32; ++i) { + static const wchar_t digits[] = L"0123456789abcdef"; + hex[2*i] = digits[digest[i] >> 4]; hex[2*i+1] = digits[digest[i] & 15]; + } + hex[64] = 0; + if (!wcscmp(hex, HASH10) && !memcmp(bytes, payload(10), 33)) version = 10; + if (!wcscmp(hex, HASH11) && !memcmp(bytes, payload(11), 33)) version = 11; +done: + if (hash) BCryptDestroyHash(hash); + if (object) HeapFree(GetProcessHeap(), 0, object); + if (alg) BCryptCloseAlgorithmProvider(alg, 0); + return version; +} +static int string_value(HKEY key, const wchar_t *name, const wchar_t *expected) { + wchar_t data[128]; DWORD type = 0, size = sizeof(data); + return RegQueryValueExW(key, name, NULL, &type, (BYTE *)data, &size) == ERROR_SUCCESS + && type == REG_SZ && size == (wcslen(expected) + 1) * sizeof(wchar_t) + && !memcmp(data, expected, size); +} +static int dword_value(HKEY key, const wchar_t *name, DWORD expected) { + DWORD data = 0, type = 0, size = sizeof(data); + return RegQueryValueExW(key, name, NULL, &type, (BYTE *)&data, &size) == ERROR_SUCCESS + && type == REG_DWORD && size == sizeof(data) && data == expected; +} +static int not_registry_link(HKEY key) { + DWORD type = 0, size = 0; + LSTATUS s = RegQueryValueExW(key, L"SymbolicLinkValue", NULL, &type, NULL, &size); + return s == ERROR_FILE_NOT_FOUND; /* Never follow/adopt a caller-created link. */ +} +static int registry_version(void) { + HKEY parent = NULL, key = NULL; DWORD subkeys = 0, values = 0; int version = 99; + LSTATUS s = RegOpenKeyExW(HKEY_LOCAL_MACHINE, PARENT_KEY, REG_OPTION_OPEN_LINK, + KEY_READ | KEY_WOW64_64KEY, &parent); + if (s == ERROR_FILE_NOT_FOUND) return 0; + if (s != ERROR_SUCCESS) return 99; + if (!protected_object((HANDLE)parent, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(parent)) goto done; + s = RegOpenKeyExW(parent, PRODUCT_KEY, REG_OPTION_OPEN_LINK, KEY_READ | KEY_WOW64_64KEY, &key); + if (s == ERROR_FILE_NOT_FOUND) {version = 0; goto done;} + if (s != ERROR_SUCCESS || !protected_object((HANDLE)key, SE_REGISTRY_KEY, KEY_READ) + || !not_registry_link(key)) goto done; + if (RegQueryInfoKeyW(key, NULL, NULL, NULL, &subkeys, NULL, NULL, &values, + NULL, NULL, NULL, NULL) != ERROR_SUCCESS || subkeys || values != 7) goto done; + unsigned candidate = string_value(key, L"Version", L"1.0.0") ? 10 + : string_value(key, L"Version", L"1.1.0") ? 11 : 0; + if (candidate && string_value(key, L"ProductId", L"RustDiscovery.ExeFixture") + && string_value(key, L"PayloadSHA256", hash_text(candidate)) + && string_value(key, L"Architecture", L"x64") && string_value(key, L"Context", L"machine") + && dword_value(key, L"PayloadBytes", 33) && dword_value(key, L"NoReboot", 1)) version = (int)candidate; +done: + if (key) RegCloseKey(key); + if (parent) RegCloseKey(parent); + return version; +} +static int set_string(HKEY key, const wchar_t *name, const wchar_t *value) { + return RegSetValueExW(key, name, 0, REG_SZ, (const BYTE *)value, + (DWORD)((wcslen(value)+1)*sizeof(wchar_t))) == ERROR_SUCCESS; +} +static int write_registry(unsigned version) { + HKEY parent = NULL, key = NULL; PSECURITY_DESCRIPTOR sd = NULL; int ok = 0; + if (!ConvertStringSecurityDescriptorToSecurityDescriptorW( + L"D:P(A;;KA;;;SY)(A;;KA;;;BA)(A;;KR;;;BU)", SDDL_REVISION_1, &sd, NULL)) return 0; + SECURITY_ATTRIBUTES sa = {sizeof(sa), sd, FALSE}; DWORD disposition = 0, bytes = 33, no_reboot = 1; + if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, PARENT_KEY, 0, NULL, REG_OPTION_NON_VOLATILE, + KEY_READ | KEY_CREATE_SUB_KEY | KEY_WOW64_64KEY, &sa, &parent, &disposition) != ERROR_SUCCESS) goto done; + if (!protected_object((HANDLE)parent, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(parent)) goto done; + if (RegCreateKeyExW(parent, PRODUCT_KEY, 0, NULL, REG_OPTION_NON_VOLATILE, + KEY_READ | KEY_SET_VALUE | KEY_WOW64_64KEY, &sa, &key, &disposition) != ERROR_SUCCESS) goto done; + if (!protected_object((HANDLE)key, SE_REGISTRY_KEY, KEY_READ) || !not_registry_link(key)) goto done; + ok = set_string(key, L"ProductId", L"RustDiscovery.ExeFixture") + && set_string(key, L"Version", version_text(version)) + && set_string(key, L"PayloadSHA256", hash_text(version)) + && set_string(key, L"Architecture", L"x64") && set_string(key, L"Context", L"machine") + && RegSetValueExW(key, L"PayloadBytes", 0, REG_DWORD, (BYTE *)&bytes, sizeof(bytes)) == ERROR_SUCCESS + && RegSetValueExW(key, L"NoReboot", 0, REG_DWORD, (BYTE *)&no_reboot, sizeof(no_reboot)) == ERROR_SUCCESS + && RegFlushKey(key) == ERROR_SUCCESS; +done: + if (key) RegCloseKey(key); + if (parent) RegCloseKey(parent); + LocalFree(sd); return ok; +} +int wmain(int argc, wchar_t **argv) { + HANDLE parents[3] = {INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE, INVALID_HANDLE_VALUE}; + const wchar_t *const directories[] = {L"C:\\", L"C:\\Program Files", ROOT}; + HANDLE file = INVALID_HANDLE_VALUE; BY_HANDLE_FILE_INFORMATION original = {0}, current; + int result = 10, observed_file = 0, observed_registry; PSECURITY_DESCRIPTOR sd = NULL; + SYSTEM_INFO platform; GetNativeSystemInfo(&platform); + if (platform.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_AMD64 + || !fixture_arguments(argc, (const wchar_t *const *)argv) || !system_process()) return 10; + for (unsigned i = 0; i < 3; ++i) { + parents[i] = CreateFileW(directories[i], FILE_READ_ATTRIBUTES | READ_CONTROL, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (parents[i] == INVALID_HANDLE_VALUE || !regular(parents[i], 1, ¤t)) goto done; + } + if (!protected_object(parents[2], SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)) goto done; + file = CreateFileW(FILE_PATH, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL); + if (file == INVALID_HANDLE_VALUE) { + if (GetLastError() != ERROR_FILE_NOT_FOUND) goto done; + } else { + if (!regular(file, 0, &original)) goto done; + observed_file = file_version(file); + } + observed_registry = registry_version(); + enum fixture_step step = fixture_step(FIXTURE_VERSION, fixture_state((unsigned)observed_registry, (unsigned)observed_file)); + if (step == FIXTURE_NOOP) {result = 0; goto done;} + if (step == FIXTURE_DENY) goto done; + if (file != INVALID_HANDLE_VALUE) {CloseHandle(file); file = INVALID_HANDLE_VALUE;} + if (!ConvertStringSecurityDescriptorToSecurityDescriptorW( + L"D:P(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;BU)", SDDL_REVISION_1, &sd, NULL)) goto done; + SECURITY_ATTRIBUTES sa = {sizeof(sa), sd, FALSE}; + file = CreateFileW(FILE_PATH, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa, + step == FIXTURE_INSTALL ? CREATE_NEW : OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, NULL); + if (file == INVALID_HANDLE_VALUE) goto done; + /* CREATE_NEW itself is the first possible mutation (an empty own file). */ + if (step == FIXTURE_INSTALL) result = 20; + if (!regular(file, 0, ¤t) || !protected_object(file, SE_FILE_OBJECT, FILE_GENERIC_READ | FILE_GENERIC_EXECUTE)) goto done; + if (step == FIXTURE_UPGRADE && (!same_file(&original, ¤t) || file_version(file) != 10)) goto done; + if (registry_version() != observed_registry) goto done; + /* From this boundary onwards every error is effect-unresolved, no rollback. */ + result = 20; DWORD written = 0; + if (SetFilePointer(file, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER + || !WriteFile(file, payload(FIXTURE_VERSION), 33, &written, NULL) || written != 33 + || !SetEndOfFile(file) || !FlushFileBuffers(file) || !write_registry(FIXTURE_VERSION)) goto done; + if (file_version(file) == FIXTURE_VERSION && registry_version() == FIXTURE_VERSION) result = 0; +done: + if (sd) LocalFree(sd); + if (file != INVALID_HANDLE_VALUE) CloseHandle(file); + for (unsigned i = 0; i < 3; ++i) if (parents[i] != INVALID_HANDLE_VALUE) CloseHandle(parents[i]); + return result; +}