Files
2026-11-13 23:38:53 +01:00

212 lines
14 KiB
Python

#!/usr/bin/env python3
"""Explicit native Admin TLS negatives; permanent Windows service stays passive.
Only public CSR leaves Windows. Only public certificates are sent to Windows.
No enrollment, jobs, clock adjustment, identity replacement or TLS bypass.
"""
import argparse
import base64
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import subprocess
import uuid
import client_bootstrap as cb
import cloud_tls_expiry_acceptance as expiry
import remote_client_bootstrap as bootstrap
require=cb.contract.require
STATE=cb.EVIDENCE/'tls-negative'
REMOTE=r'''
$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
if ($p.id -notmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' -or $p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed fixture binding'}
if ($p.action -notin @('prepare','incoming','seal-public','verify-public','probe','witness')) {throw 'Fixed action'}
$binary='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\WindowsTlsProbe.exe'
if ((Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Probe artifact changed'}
$base='C:\ProgramData\RustDiscoveryBootstrap\tls-negative'
$folder=Join-Path $base $p.id
$allowed=@('S-1-5-18','S-1-5-32-544')
function Assert-Directory([string]$Path) {
$item=Get-Item -LiteralPath $Path
if (!$item.PSIsContainer -or (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) {throw 'Private regular directory'}
$acl=Get-Acl -LiteralPath $Path
if (!$acl.AreAccessRulesProtected -or $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin $allowed) {throw 'Private directory owner'}
foreach($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
if ($rule.IdentityReference.Value -notin $allowed -or $rule.AccessControlType -ne 'Allow') {throw 'Private directory ACL'}
}
}
function New-Directory([string]$Path) {
New-Item -ItemType Directory -Path $Path | Out-Null
$acl=New-Object Security.AccessControl.DirectorySecurity
$acl.SetAccessRuleProtection($true,$false)
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
foreach($sid in $allowed) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','ContainerInherit,ObjectInherit','None','Allow')))}
Set-Acl -LiteralPath $Path -AclObject $acl
Assert-Directory $Path
}
function Seal-Files {
foreach($item in Get-ChildItem -LiteralPath $folder) {
if ($item.PSIsContainer -or (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0)) {throw 'Fixture regular file'}
$acl=New-Object Security.AccessControl.FileSecurity
$acl.SetAccessRuleProtection($true,$false)
$acl.SetOwner((New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))
foreach($sid in $allowed) {$acl.AddAccessRule((New-Object Security.AccessControl.FileSystemAccessRule((New-Object Security.Principal.SecurityIdentifier($sid)),'FullControl','Allow')))}
Set-Acl -LiteralPath $item.FullName -AclObject $acl
}
}
if ($p.action -eq 'prepare') {
if (!(Test-Path -LiteralPath $base)) {New-Directory $base}
Assert-Directory $base
if (Test-Path -LiteralPath $folder) {throw 'Fixture already exists; preserve, never repeat blindly'}
New-Directory $folder
$raw=& $binary prepare $p.id; $code=$LASTEXITCODE
Seal-Files
if ($code -ne 0) {throw 'Fixture preparation failed'}
$value=$raw | ConvertFrom-Json
if (!$value.prepared -or $value.case_id -cne $p.id -or $value.private_key_exported) {throw 'Public CSR response'}
$value | ConvertTo-Json -Depth 8 -Compress
} else {
Assert-Directory $base; Assert-Directory $folder
if ($p.action -eq 'incoming') {
foreach($name in @('issuer-ca.pem','valid.pem','expired.pem')) {if (Test-Path -LiteralPath (Join-Path $folder $name)) {throw 'Public certificate already exists'}}
[pscustomobject]@{prepared=$true;public_certificates_only=$true} | ConvertTo-Json -Compress
} elseif ($p.action -in @('seal-public','verify-public')) {
foreach($name in @('issuer-ca.pem','valid.pem','expired.pem')) {
$path=Join-Path $folder $name
if ((Get-Item -LiteralPath $path).Length -gt 32768 -or (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.hashes.$name) {throw 'Exact public certificate hash'}
}
if ($p.action -eq 'seal-public') {Seal-Files}
[pscustomobject]@{verified=$true;public_certificates_only=$true} | ConvertTo-Json -Compress
} elseif ($p.action -eq 'probe') {
if ($p.kind -notin @('valid','expired','wrong-ca','wrong-name')) {throw 'Fixed probe kind'}
$raw=& $binary probe $p.id $p.kind; $code=$LASTEXITCODE
$value=$raw | ConvertFrom-Json
[pscustomobject]@{exit_code=$code;probe=$value} | ConvertTo-Json -Depth 8 -Compress
} else {
throw 'Witness uses the separate bounded read-only script'
}
}
'''
WITNESS=r'''
$ErrorActionPreference='Stop'
$p=([Console]::In.ReadLine() | ConvertFrom-Json)
if ($p.id -notmatch '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' -or $p.sha256 -notmatch '^[0-9a-f]{64}$') {throw 'Fixed witness binding'}
$binary='C:\ProgramData\RustDiscoveryBootstrap\'+$p.sha256+'\WindowsTlsProbe.exe'
if ((Get-FileHash -LiteralPath $binary -Algorithm SHA256).Hash.ToLowerInvariant() -cne $p.sha256) {throw 'Exact witness artifact'}
$state='C:\ProgramData\RustDiscovery\state'
$identity=Get-Content -LiteralPath (Join-Path $state 'identity.json') -Raw | ConvertFrom-Json
$files=[ordered]@{}
foreach($name in @('identity.json','device.pem')) {$files[$name]=(Get-FileHash -LiteralPath (Join-Path $state $name) -Algorithm SHA256).Hash.ToLowerInvariant()}
$key=Get-Item -LiteralPath (Join-Path $state 'device.key')
$service=Get-CimInstance Win32_Service -OperationTimeoutSec 10 -Filter "Name='RmmDiscoveryWindows'"
[pscustomobject]@{identity=[ordered]@{agent_id=$identity.agent_id;asset_id=$identity.asset_id};public_file_hashes=$files;
private_key_metadata=[ordered]@{length=$key.Length;creation_ticks=$key.CreationTimeUtc.Ticks;last_write_ticks=$key.LastWriteTimeUtc.Ticks};
service=[ordered]@{state=$service.State;start_name=$service.StartName;process_id=$service.ProcessId};
existing_private_key_read=$false;bootstrap_admin_tls_probe=$true} | ConvertTo-Json -Depth 8 -Compress
'''
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 stream:json.dump(value,stream,indent=2);stream.write('\n');stream.flush();os.fsync(stream.fileno())
def public_transfer(folder,ident,sha,signed):
raw={'issuer-ca.pem':base64.b64decode(signed['ca'],validate=True)}
require(set(signed['certificates'])=={'valid','expired'},'exact two public fixture leaves')
raw.update({name+'.pem':base64.b64decode(data,validate=True) for name,data in signed['certificates'].items()})
for name,data in raw.items():
require(100<=len(data)<=32768 and b'PRIVATE KEY' not in data,'public certificates only')
path=folder/name;fd=os.open(path,os.O_CREAT|os.O_EXCL|os.O_WRONLY,0o600)
with os.fdopen(fd,'wb') as stream:stream.write(data);stream.flush();os.fsync(stream.fileno())
cb.powershell(REMOTE,dict(action='incoming',id=ident,sha256=sha))
access=cb.contract.protected_json(cb.ROOT/'credentials/windows-dev-access.json');prefix=access['ssh_prefix']
args=['sftp']+[part for part in prefix[1:-1] if part!='-T']+['-b','-',prefix[-1]]
remote='/C:/ProgramData/RustDiscoveryBootstrap/tls-negative/'+ident+'/'
# Fixed public files only. There is deliberately no SFTP get/download path.
batch=''.join('put '+json.dumps(str((folder/name).resolve()))+' '+json.dumps(remote+name)+'\n' for name in raw)
require(subprocess.run(args,input=batch.encode(),capture_output=True,timeout=60).returncode==0,'public certificate SFTP failed')
hashes={name:hashlib.sha256(data).hexdigest() for name,data in raw.items()}
result=cb.powershell(REMOTE,dict(action='seal-public',id=ident,sha256=sha,hashes=hashes))
require(result.get('verified') is True,'public fixture ACL/hash verification')
return dict(public_files_sha256=hashes,sftp_upload_only=True,private_key_transferred=False)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--execute-native-tls-negative',action='store_true',required=True)
parser.add_argument('--artifact',type=Path,required=True)
parser.add_argument('--resume-case',type=uuid.UUID,help='Read-only TLS retest of existing fixtures, preserving every original receipt')
args=parser.parse_args();os.umask(0o077)
artifact=args.artifact.resolve();qualification=cb.contract.protected_json(Path(str(artifact)+'.json'))
sha=hashlib.sha256(artifact.read_bytes()).hexdigest()
require(qualification['binary_sha256']==sha and qualification['release_build'] is True
and qualification['architecture']=='x86_64-pc-windows-gnu'
and all(hashlib.sha256((cb.ROOT/p).read_bytes()).hexdigest()==h for p,h in qualification['source_files'].items()),'qualified exact Windows TLS probe artifact')
STATE.mkdir(mode=0o700,parents=True,exist_ok=True)
ident=str(args.resume_case or uuid.uuid4())
original=STATE/ident
if args.resume_case:
require(original.is_dir() and not original.is_symlink(),'existing original private case')
folder=original/('typed-retest-'+str(uuid.uuid4()))
else:folder=original
folder.mkdir(mode=0o700)
write(folder/'started.json',dict(id=ident,artifact_sha256=sha,execution_context='bootstrap_administrator_tls_probe',no_service_or_identity_mutations=True))
pointer=cb.EVIDENCE/'WindowsTlsProbe.exe.latest.json'
if pointer.exists() and cb.contract.protected_json(pointer)['sha256']==sha:
cb.powershell(cb.VERIFY_UPLOAD,dict(name='WindowsTlsProbe.exe',sha256=sha))
else:cb.upload(artifact,'WindowsTlsProbe.exe')
if args.resume_case:
originals={name:cb.contract.protected_json(original/name) for name in ('started.json','prepared.json','signed-public.json','public-transfer.json','permanent-before.json','wrong-ca.json')}
require(originals['started.json']['id']==ident and originals['wrong-ca.json']['exit_code']==2
and originals['wrong-ca.json']['probe']['verified'] is False,'exact preserved failed case')
signed=originals['signed-public.json'];before=originals['permanent-before.json']
require(signed['id']==ident and dt.datetime.fromisoformat(signed['valid_not_after'])>dt.datetime.now(dt.timezone.utc)+dt.timedelta(minutes=2),
'existing positive certificate must remain valid; never resign or alter clock during retest')
require(cb.powershell(WITNESS,dict(id=ident,sha256=sha),timeout=25)==before,'original permanent witness unchanged before retest')
checked=cb.powershell(REMOTE,dict(action='verify-public',id=ident,sha256=sha,hashes=originals['public-transfer.json']['public_files_sha256']))
require(checked.get('verified') is True,'unchanged original public fixture certificates')
write(folder/'original-evidence.json',dict(id=ident,retained=True,original_files_sha256={name:hashlib.sha256((original/name).read_bytes()).hexdigest() for name in originals},
original_artifact_sha256=originals['started.json']['artifact_sha256'],replacement_artifact_sha256=sha,
no_new_csr=True,no_signing=True,no_fixture_transfer=True))
gate_before=bootstrap.rpc('server.conf',expiry.server_gate,dict(id=ident));write(folder/'server-before.json',gate_before)
require(gate_before==dict(installations=0,jobs=0,outbox=0,permits=0),'unregistered original fixture')
else:
prepared=cb.powershell(REMOTE,dict(action='prepare',id=ident,sha256=sha));write(folder/'prepared.json',prepared)
require(prepared['prepared'] and prepared['case_id']==ident and not prepared['private_key_exported'],'Windows-only fixture key and public CSR')
csr=prepared['csr_pem'].encode();require(len(csr)<8192 and hashlib.sha256(csr).hexdigest()==prepared['csr_sha256'],'bounded original public CSR')
before=cb.powershell(WITNESS,dict(id=ident,sha256=sha),timeout=25);write(folder/'permanent-before.json',before)
gate_before=bootstrap.rpc('server.conf',expiry.server_gate,dict(id=ident));write(folder/'server-before.json',gate_before)
require(gate_before==dict(installations=0,jobs=0,outbox=0,permits=0),'unregistered fixture and zero jobs')
signed=bootstrap.rpc('server.conf',expiry.sign_server,dict(id=ident,csr=base64.b64encode(csr).decode()));write(folder/'signed-public.json',signed)
require(signed['id']==ident and signed['ca_unchanged'] and not signed['clock_adjusted'] and not signed['enrollment_created'],'existing CA unchanged and no clock/enrollment mutation')
transfer=public_transfer(folder,ident,sha,signed);write(folder/'public-transfer.json',transfer)
probes=[]
for label,kind in (('valid-before','valid'),('wrong-ca','wrong-ca'),('wrong-name','wrong-name'),('expired','expired'),('valid-after','valid')):
outcome=cb.powershell(REMOTE,dict(action='probe',id=ident,sha256=sha,kind=kind),timeout=50)
write(folder/(label+'.json'),outcome);probes.append(dict(label=label,**outcome))
require(outcome['exit_code']==0 and outcome['probe'].get('verified') is True
and outcome['probe']['case_id']==ident and outcome['probe']['kind']==kind,'native exact TLS outcome; timeout/unclassified error is not a TLS denial')
after=cb.powershell(WITNESS,dict(id=ident,sha256=sha),timeout=25);write(folder/'permanent-after.json',after)
require(after==before,'permanent service identity/key metadata/public files unchanged')
gate_after=bootstrap.rpc('server.conf',expiry.server_gate,dict(id=ident));write(folder/'server-after.json',gate_after)
require(gate_after==gate_before,'no fixture registration/jobs/grants')
write(folder/'result.json',dict(verified=True,id=ident,probes=probes,server_gate=gate_after,permanent_identity_preserved=True,
private_key_exported=False,enrollment_created=False,jobs_created=False,clock_adjusted=False,
execution_context='bootstrap_administrator_tls_probe',local_service_probe=False,artifact_sha256=sha))
print(json.dumps(dict(verified=True,id=ident,evidence_directory=str(folder),probes=5,private_key_exported=False,local_service_probe=False,jobs_created=False)))
if __name__=='__main__':
try:main()
except Exception as error:
print('WINDOWS_TLS_ACCEPTANCE_INCOMPLETE:'+type(error).__name__)
raise SystemExit(2) from None