Files
rust-discovery/deploy/windows/clock_readiness.py
T
2026-11-14 02:39:39 +01:00

209 lines
13 KiB
Python

#!/usr/bin/env python3
"""Read-only LocalService W32Time readiness bootstrap; no RMM jobs.
A lost SSH reply is resumed using readback --id, never by repeating start.
The temporary service is separate from the permanent enrolled Windows agent.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parent))
import client_bootstrap as cb
STATE = cb.EVIDENCE / 'clock-readiness'
ROOT = r'C:\ProgramData\RustDiscoveryClockReadiness'
SERVICE = 'RmmWindowsClockReadiness'
PREPARE = r'''$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if($p.sha -notmatch '^[a-f0-9]{64}$' -or $p.name -notin @('WindowsClockReadiness.exe','ClockReadiness.ps1')){throw 'Fixed artifact'}
$root='C:\ProgramData\RustDiscoveryClockReadiness'
function CheckPrivate($path){
$acl=Get-Acl -LiteralPath $path;$owner=$acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
if($owner -notin @('S-1-5-18','S-1-5-32-544') -or $acl.Access.Count -eq 0){throw 'Artifact owner/DACL'}
foreach($ace in $acl.Access){
$sid=$ace.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value
if($ace.AccessControlType -ne 'Allow' -or $sid -notin @('S-1-5-18','S-1-5-32-544','S-1-5-19')){throw 'Artifact broad ACL'}
if($sid -eq 'S-1-5-19' -and ([int64]$ace.FileSystemRights -band (-bnot ([int64][Security.AccessControl.FileSystemRights]::ReadAndExecute -bor [int64][Security.AccessControl.FileSystemRights]::Synchronize)))){throw 'Artifact writable by service account'}
}
}
if(!(Test-Path -LiteralPath $root)){
New-Item -ItemType Directory -Path $root|Out-Null
$a=New-Object Security.AccessControl.DirectorySecurity;$a.SetAccessRuleProtection($true,$false)
foreach($sid in @('S-1-5-18','S-1-5-32-544','S-1-5-19')){
$rights=if($sid -eq 'S-1-5-19'){'ReadAndExecute'}else{'FullControl'}
$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),$rights,'ContainerInherit,ObjectInherit','None','Allow')))
}
$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));Set-Acl -LiteralPath $root -AclObject $a
}
if((Get-Item -LiteralPath $root).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Root reparse'}
CheckPrivate $root
$dir=Join-Path $root $p.sha
if(!(Test-Path -LiteralPath $dir)){New-Item -ItemType Directory -Path $dir|Out-Null}
if((Get-Item -LiteralPath $dir).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Artifact reparse'}
CheckPrivate $dir
$file=Join-Path $dir $p.name
$exists=Test-Path -LiteralPath $file
if($exists -and ((Get-Item -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'File reparse'}
if($exists){CheckPrivate $file}
if($exists -and (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha){throw 'Artifact immutable'}
[pscustomobject]@{exists=$exists;sha=$p.sha}|ConvertTo-Json -Compress
'''
SCRIPT = r'''$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
$id=[guid]::ParseExact($p.id,'D').ToString()
if($id -cne $p.id -or $p.binary -notmatch '^[a-f0-9]{64}$' -or $p.source -notmatch '^[a-f0-9]{64}$' -or $p.action -notin @('start','readback')){throw 'Fixed request'}
$root='C:\ProgramData\RustDiscoveryClockReadiness';$name='RmmWindowsClockReadiness'
$case=Join-Path $root $id;$intent=Join-Path $case 'intent.json';$result=Join-Path $case 'result.json'
$exe=Join-Path (Join-Path $root $p.binary) 'WindowsClockReadiness.exe'
$source=Join-Path (Join-Path $root $p.source) 'ClockReadiness.ps1'
foreach($file in @($exe,$source)){
if((Get-Item -LiteralPath $file).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Reparse'}
}
if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.binary -or (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.source){throw 'Qualified source and binary'}
$command='"'+$exe+'" --service '+$id
function PrivateFile($path){
$a=New-Object Security.AccessControl.FileSecurity;$a.SetAccessRuleProtection($true,$false)
foreach($sid in @('S-1-5-18','S-1-5-32-544')){$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))}
$a.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')));Set-Acl -LiteralPath $path -AclObject $a
}
function WriteNew($path,$data){
$bytes=[Text.Encoding]::UTF8.GetBytes(($data|ConvertTo-Json -Depth 12 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','None')
try{$f.Write($bytes,0,$bytes.Length);$f.Flush($true)}finally{$f.Dispose()};PrivateFile $path
}
if($p.action -eq 'start'){
if((Test-Path -LiteralPath $case) -or (Get-Service -Name $name -ErrorAction SilentlyContinue)){throw 'Use retained case readback; never repeat start'}
New-Item -ItemType Directory -Path $case|Out-Null
WriteNew $intent ([ordered]@{id=$id;binary=$p.binary;source=$p.source;command=$command;service=$name;no_jobs=$true})
New-Service -Name $name -BinaryPathName $command -StartupType Manual -Credential (New-Object Management.Automation.PSCredential('NT AUTHORITY\LocalService',(New-Object Security.SecureString)))|Out-Null
& "$env:WINDIR\System32\sc.exe" sidtype $name unrestricted|Out-Null;if($LASTEXITCODE -ne 0){throw 'Readiness service SID'}
$sid=(New-Object Security.Principal.NTAccount('NT SERVICE\'+$name)).Translate([Security.Principal.SecurityIdentifier])
$a=Get-Acl -LiteralPath $case;$a.SetAccessRuleProtection($true,$true)
$a.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule($sid,'ReadAndExecute,Write','ContainerInherit,ObjectInherit','None','Allow')));Set-Acl -LiteralPath $case -AclObject $a
Start-Service -Name $name
}
if(!(Test-Path -LiteralPath $intent)){throw 'Missing durable intent'}
$i=Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json
if($i.id -cne $id -or $i.binary -cne $p.binary -or $i.source -cne $p.source -or $i.command -cne $command -or $i.service -cne $name){throw 'Retained intent mismatch'}
$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsClockReadiness'"
if($service -and ($service.PathName -cne $command -or $service.StartName -notin @('NT AUTHORITY\LocalService','NT AUTHORITY\Local Service'))){throw 'Service owner/configuration mismatch'}
$deadline=[DateTime]::UtcNow.AddSeconds(25)
while($service -and $service.State -ne 'Stopped' -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Milliseconds 250;$service=Get-CimInstance Win32_Service -Filter "Name='RmmWindowsClockReadiness'"}
if($service -and $service.State -ne 'Stopped'){throw 'Readiness still active; retain case and readback'}
$token=$null;$tokenPath=Join-Path $case 'token.json'
if(Test-Path -LiteralPath $tokenPath){
if((Get-Item -LiteralPath $tokenPath).Length -gt 1024 -or ((Get-Item -LiteralPath $tokenPath).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Token report bound'}
$token=Get-Content -LiteralPath $tokenPath -Raw|ConvertFrom-Json
if($token.user_sid -cne 'S-1-5-19' -or $token.administrator_member -ne $false -or $token.system_user -ne $false){throw 'Token report identity'}
PrivateFile $tokenPath
}
$data=$null
if(Test-Path -LiteralPath $result){
if((Get-Item -LiteralPath $result).Length -gt 16384 -or ((Get-Item -LiteralPath $result).Attributes -band [IO.FileAttributes]::ReparsePoint)){throw 'Result bound'}
$data=Get-Content -LiteralPath $result -Raw|ConvertFrom-Json
if($data.case_id -cne $id -or $data.token_sid -cne 'S-1-5-19' -or $data.token.user_sid -cne 'S-1-5-19' -or $data.token.administrator_member -ne $false -or $data.token.system_user -ne $false -or $data.token.elevation_flag -notin @(0,1) -or $data.token.elevation_type -notin @(1,2,3) -or $data.elevated -ne ($data.token.elevation_flag -ne 0) -or $data.service_name -cne $name -or $data.read_only -ne $true){throw 'Actual LocalService report'}
PrivateFile $result
}
if($service){
$cleanup=Join-Path $case 'cleanup-intent.json'
if(!(Test-Path -LiteralPath $cleanup)){WriteNew $cleanup ([ordered]@{id=$id;command=$command;service=$name;remove_only_own_stopped_service=$true})}
else{$c=Get-Content -LiteralPath $cleanup -Raw|ConvertFrom-Json;if($c.id -cne $id -or $c.command -cne $command -or $c.service -cne $name){throw 'Cleanup intent mismatch'}}
& "$env:WINDIR\System32\sc.exe" delete $name|Out-Null;if($LASTEXITCODE -ne 0){throw 'Readiness cleanup'}
}
[pscustomobject]@{id=$id;native_report=$data;partial_token=$token;service_removed=!(Get-Service -Name $name -ErrorAction SilentlyContinue);service_exit_code=if($service){$service.ExitCode}else{$null};service_specific_exit_code=if($service){$service.ServiceSpecificExitCode}else{$null};no_jobs=$true;no_clock_change=$true;no_agent_change=$true}|ConvertTo-Json -Depth 15 -Compress
'''
LAUNCH = r'''$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine()|ConvertFrom-Json)
if($p.source -notmatch '^[a-f0-9]{64}$'){throw 'Source hash'}
$file='C:\ProgramData\RustDiscoveryClockReadiness\'+$p.source+'\ClockReadiness.ps1'
if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.source){throw 'Source changed'}
$inputJson=$p|ConvertTo-Json -Compress
$raw=$inputJson|& "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File $file
if($LASTEXITCODE -ne 0){throw 'Readiness source failed'}
$raw
'''
def save(folder, name, value):
fd = os.open(folder / name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as out:
json.dump(value, out, indent=2)
out.flush()
os.fsync(out.fileno())
def stage(path, name):
digest = hashlib.sha256(path.read_bytes()).hexdigest()
value = cb.powershell(PREPARE, dict(sha=digest, name=name))
if not value['exists']:
access = cb.contract.protected_json(cb.ROOT / 'credentials/windows-dev-access.json')
prefix = access['ssh_prefix']
args = ['sftp'] + [p for p in prefix[1:-1] if p != '-T'] + ['-b', '-', prefix[-1]]
remote = '/C:/ProgramData/RustDiscoveryClockReadiness/' + digest + '/' + name
batch = 'put ' + json.dumps(str(path.resolve())) + ' ' + json.dumps(remote) + '\n'
result = subprocess.run(args, input=batch.encode(), capture_output=True, timeout=120)
if result.returncode:
raise RuntimeError('CLOCK_ARTIFACT_UPLOAD_FAILED')
if not cb.powershell(PREPARE, dict(sha=digest, name=name))['exists']:
raise RuntimeError('CLOCK_ARTIFACT_READBACK_FAILED')
return digest
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('start', 'readback'))
parser.add_argument('--binary', type=Path)
parser.add_argument('--id')
args = parser.parse_args()
os.umask(0o077)
STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
if args.action == 'start':
if args.id or not args.binary or not args.binary.is_file():
raise RuntimeError('NEW_CASE_BINARY_REQUIRED')
ident = str(uuid.uuid4())
folder = STATE / ident
folder.mkdir(mode=0o700)
source_path = folder / 'ClockReadiness.ps1'
fd = os.open(source_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as out:
out.write(SCRIPT)
intent = dict(id=ident, binary=hashlib.sha256(args.binary.read_bytes()).hexdigest(), source=hashlib.sha256(SCRIPT.encode()).hexdigest(), no_jobs=True)
save(folder, 'intent.json', intent)
print('Retained readiness case ' + ident, flush=True)
stage(args.binary, 'WindowsClockReadiness.exe')
stage(source_path, 'ClockReadiness.ps1')
save(folder, 'start-intent.json', dict(**intent, action='start'))
else:
if not args.id or args.binary:
raise RuntimeError('READBACK_SAME_CASE_REQUIRED')
ident = str(uuid.UUID(args.id))
folder = STATE / ident
intent = cb.contract.protected_json(folder / 'intent.json')
if intent['source'] != hashlib.sha256(SCRIPT.encode()).hexdigest():
raise RuntimeError('QUALIFIED_SOURCE_CHANGED')
result = cb.powershell(LAUNCH, dict(**intent, action=args.action), timeout=60)
save(folder, 'readback-' + str(uuid.uuid4()) + '.json', result)
report = result['native_report']
if not result['service_removed'] or not report or len(report['samples']) != 2:
raise RuntimeError('READINESS_NATIVE_REPORT_INCOMPLETE')
diagnostic = all(s['trusted'] for s in report['samples'])
qualified = all(s.get('adapter_qualified') is True for s in report['samples'])
ready = diagnostic and qualified
completed = dict(native_execution_verified=True, diagnostic_status_ready=diagnostic, adapter_qualified=qualified, clock_ready=ready, **result)
if not (folder / 'result.json').exists():
save(folder, 'result.json', completed)
elif cb.contract.protected_json(folder / 'result.json')['native_report'] != report:
raise RuntimeError('IMMUTABLE_NATIVE_REPORT_CHANGED')
print(json.dumps(dict(id=ident,native_execution_verified=True,diagnostic_status_ready=diagnostic,adapter_qualified=qualified,clock_ready=ready,reasons=[s['reason'] for s in report['samples']],rpc_codes=[s['rpc_code'] for s in report['samples']],token=report.get('token'),service_removed=True,no_jobs=True)))
if __name__ == '__main__':
main()