Complete bounded Windows maintenance setup and audited development teardown
This commit is contained in:
@@ -0,0 +1,206 @@
|
||||
# Run as an administrator on an enrolled development device.
|
||||
# A separate server policy and normal WebUI job approval are still required.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('Plan','Install','Remove','Resume')][string]$Action = 'Plan',
|
||||
[Parameter(Mandatory=$true)][Guid]$AgentId,
|
||||
[Parameter(Mandatory=$true)][Guid]$AssetId,
|
||||
[Parameter(Mandatory=$true)][Guid]$ReleaseId,
|
||||
[Parameter(Mandatory=$true)][Guid]$CaseId,
|
||||
[ValidateRange(121,3600)][int]$Seconds = 3600
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$actor = 'RmmDiscoveryWindows'
|
||||
$helper = 'RmmDiscoverySystemHelper'
|
||||
$data = Join-Path $env:ProgramData 'RustDiscovery'
|
||||
$root = Join-Path $env:ProgramData 'RustDiscoverySystem'
|
||||
$app = Join-Path $env:ProgramFiles 'RustDiscovery'
|
||||
$cfg = Join-Path $data 'config.json'
|
||||
$jobPolicy = Join-Path $data 'job-time.json'
|
||||
$marker = Join-Path $root 'windows-update-enrollment.json'
|
||||
$admin = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
|
||||
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
|
||||
$utf8 = [Text.UTF8Encoding]::new($false)
|
||||
function Check($condition, $message) { if (!$condition) { throw $message } }
|
||||
function NoLink([string]$path) {
|
||||
for ($p=Get-Item -LiteralPath $path -Force; $null -ne $p; $p=$p.Parent) {
|
||||
if ($p.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Reparse point in fixed path.' }
|
||||
if ($p -is [IO.FileInfo]) { NoLink $p.DirectoryName; break }
|
||||
}
|
||||
}
|
||||
function JsonFile($p) {
|
||||
NoLink $p
|
||||
return [IO.File]::ReadAllText($p) | ConvertFrom-Json
|
||||
}
|
||||
function WriteFixed($p,$s) {
|
||||
if (Test-Path -LiteralPath $p) { Check ([IO.File]::ReadAllText($p) -ceq $s) "Different existing file: $p";return }
|
||||
$f=[IO.File]::Open($p,[IO.FileMode]::CreateNew);try {$b=$utf8.GetBytes($s);$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}
|
||||
}
|
||||
function GetHash($p) { NoLink $p;return (Get-FileHash -LiteralPath $p -Algorithm SHA256).Hash.ToLowerInvariant() }
|
||||
function Service($name) { return Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") }
|
||||
function GetSid($name) { return [Security.Principal.NTAccount]::new('NT SERVICE',$name).Translate([Security.Principal.SecurityIdentifier]) }
|
||||
function DirectoryAcl($readers) {
|
||||
$a=[Security.AccessControl.DirectorySecurity]::new()
|
||||
$a.SetOwner($admin);$a.SetAccessRuleProtection($true,$false)
|
||||
foreach ($id in @($system,$admin)) {$a.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($id,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))}
|
||||
foreach ($id in $readers) {$a.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($id,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))}
|
||||
return $a
|
||||
}
|
||||
function NewPrivateDir($path,$readers) {
|
||||
if (!(Test-Path -LiteralPath $path)){[void][IO.Directory]::CreateDirectory($path,(DirectoryAcl $readers))}
|
||||
NoLink $path
|
||||
}
|
||||
Check ($AgentId -ne [guid]::Empty -and $AssetId -ne [guid]::Empty -and $ReleaseId -ne [guid]::Empty -and $CaseId -ne [guid]::Empty) 'Exact IDs required.'
|
||||
$who=[Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
Check ($who.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 'Elevated operator required.'
|
||||
$id=JsonFile (Join-Path $data 'state\identity.json')
|
||||
$active=Join-Path $data 'release-state\installed-release.json'
|
||||
if(!(Test-Path -LiteralPath $active)){$active=Join-Path $data 'installed-release.json'}
|
||||
$installed=JsonFile $active
|
||||
$conf=JsonFile $cfg
|
||||
$clock=JsonFile $jobPolicy
|
||||
Check ($id.agent_id -ceq $AgentId.ToString() -and $id.asset_id -ceq $AssetId.ToString() -and $installed.release_id -ceq $ReleaseId.ToString()) 'The selected enrollment or release changed.'
|
||||
Check ($conf.enable_jobs -eq $true -and $conf.localservice_time_policy -ceq $jobPolicy -and $clock.tenant_id -ceq $installed.tenant_id -and $clock.job_signing_public_key_hex -cmatch '^[a-f0-9]{64}$') 'Authenticated LocalService bootstrap required.'
|
||||
$images=Join-Path $app ('releases\'+$ReleaseId.ToString())
|
||||
$agentExe=Join-Path $images 'rmm-agent-windows.exe';$helperExe=Join-Path $images 'rmm-helper-windows.exe'
|
||||
$a=Service $actor;$h=Service $helper
|
||||
Check ($a -and $a.StartName -ieq 'NT AUTHORITY\LocalService' -and $a.PathName -ceq ('"'+$agentExe+'" --service --config "'+$cfg+'"')) 'Fixed enrolled LocalService command required.'
|
||||
if($Action -in @('Plan','Install')){
|
||||
$live=Get-CimInstance Win32_Process -Filter ('ProcessId='+$a.ProcessId)
|
||||
Check ($a.State -ceq 'Running' -and $live.ExecutablePath -ieq $agentExe -and (GetHash $live.ExecutablePath) -ceq (GetHash $agentExe)) 'The live SCM process differs from the enrolled agent.'
|
||||
}
|
||||
$helperCommand='"'+$helperExe+'" --service'
|
||||
if ($h) {Check ($h.PathName -ceq $helperCommand -and $h.StartName -eq 'LocalSystem') 'Existing helper belongs to a different pair.'}
|
||||
$manifest=Join-Path $images 'manifest.json'
|
||||
Check ((GetHash $manifest) -ceq $installed.manifest_sha256) 'Installed release manifest changed.'
|
||||
$updater=Join-Path $app 'rmm-updater-windows.exe'
|
||||
$pull=Service 'RmmDiscoveryReleasePull'
|
||||
Check ($pull -and $pull.StartName -eq 'LocalSystem' -and $pull.PathName -ceq ('"'+$updater+'" --release-service')) 'Expected the enrolled ReleasePull service.'
|
||||
if($Action -eq 'Plan'){Check ($pull.StartMode -eq 'Auto' -and $pull.State -eq 'Running') 'ReleasePull must be running normally before a new maintenance window.'}
|
||||
$envelope=Join-Path $images 'envelope.json'
|
||||
$ring=Join-Path $data 'release-keyring.json'
|
||||
foreach($f in @($agentExe,$helperExe,$updater,$envelope,$ring)){NoLink $f}
|
||||
$verified=& $updater --verify-bootstrap $ring $envelope $agentExe $helperExe
|
||||
Check ($LASTEXITCODE -eq 0 -and (($verified|ConvertFrom-Json).release_id -ceq $ReleaseId.ToString())) 'Signed image pair verification failed.'
|
||||
$scopeVersion=& $helperExe --windows-update-scope-version
|
||||
Check ($scopeVersion -ceq 'enrolled-windows-update/1' -and $LASTEXITCODE -eq 0) 'Release a helper with enrolled-windows-update/1 before provisioning.'
|
||||
$binding=[ordered]@{tenant_id=$clock.tenant_id;asset_id=$AssetId.ToString();agent_id=$AgentId.ToString();enrollment_generation=1;assignment_version=1;public_key_hex=$clock.job_signing_public_key_hex}
|
||||
$inputDto=[ordered]@{binding=$binding;release_id=$ReleaseId.ToString();agent_sha256=(GetHash $agentExe);helper_sha256=(GetHash $helperExe);max_runtime_seconds=$Seconds}
|
||||
$markerJson=([ordered]@{case_id=$CaseId.ToString();release_id=$ReleaseId.ToString();agent_id=$AgentId.ToString();asset_id=$AssetId.ToString()}|ConvertTo-Json -Compress)
|
||||
$archive=$root+'.closed-'+$CaseId.ToString()
|
||||
$backup=Join-Path $root 'original-agent-config.json'
|
||||
$written=Join-Path $root 'active-agent-config.json'
|
||||
$gate=$null
|
||||
function VerifyMarker($dir) {
|
||||
NoLink $dir
|
||||
$file=Join-Path $dir 'windows-update-enrollment.json'
|
||||
Check ((Test-Path -LiteralPath $file) -and ([IO.File]::ReadAllText($file) -ceq $markerJson)) 'Protected helper directory belongs to another case.'
|
||||
}
|
||||
function ReplaceConfig($text) {
|
||||
$staged=$cfg+'.windows-update-'+$CaseId.ToString()
|
||||
WriteFixed $staged $text
|
||||
# PowerShell 5.1 marshals $null as an empty backup path. Provide a real path.
|
||||
$previous=Join-Path $root ('replaced-config-'+[guid]::NewGuid().ToString()+'.json')
|
||||
[IO.File]::Replace($staged,$cfg,$previous)
|
||||
}
|
||||
function StartNormal {
|
||||
Set-Service 'RmmDiscoveryReleasePull' -StartupType Automatic
|
||||
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
|
||||
if((Get-Service 'RmmDiscoveryReleasePull').Status -ne 'Running'){Start-Service 'RmmDiscoveryReleasePull'}
|
||||
}
|
||||
function RemoveWindow {
|
||||
if (!(Test-Path -LiteralPath $root)) {
|
||||
Check (!(Service $helper) -and !(JsonFile $cfg).windows_update_helper) 'Helper SCM or configuration present without its protected case marker.'
|
||||
if(Test-Path -LiteralPath $archive){VerifyMarker $archive}
|
||||
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
|
||||
return
|
||||
}
|
||||
VerifyMarker $root
|
||||
$cs=JsonFile $cfg
|
||||
$registered=Service $helper
|
||||
if($registered){Check ($registered.StartName -eq 'LocalSystem' -and $registered.PathName -ceq $helperCommand) 'Foreign helper SCM.'}
|
||||
if($cs.windows_update_helper){
|
||||
Check ((Test-Path -LiteralPath $written) -and (GetHash $written) -ceq (GetHash $cfg) -and (Test-Path -LiteralPath $backup)) 'Operator configuration changed since opening. Review before restoring.'
|
||||
}
|
||||
if((Get-Service $actor).Status -ne 'Stopped'){Stop-Service $actor}
|
||||
try {
|
||||
if($registered){
|
||||
if((Get-Service $helper).Status -ne 'Stopped'){Stop-Service $helper}
|
||||
& "$env:SystemRoot\System32\sc.exe" delete $helper |Out-Null
|
||||
Check ($LASTEXITCODE -eq 0) 'Helper SCM removal failed.'
|
||||
for($i=0;$i -lt 15 -and (Service $helper);$i++){Start-Sleep -Seconds 1}
|
||||
Check (!(Service $helper)) 'Helper SCM deletion pending.'
|
||||
}
|
||||
if($cs.windows_update_helper){ReplaceConfig ([IO.File]::ReadAllText($backup))}
|
||||
Check (!(Test-Path -LiteralPath $archive)) 'Case archive already exists.'
|
||||
[IO.Directory]::Move($root,$archive)
|
||||
} finally {
|
||||
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
|
||||
}
|
||||
}
|
||||
if(Test-Path -LiteralPath $root){VerifyMarker $root}
|
||||
if($Action -eq 'Plan'){[ordered]@{planned=$true;tenant_id=$binding.tenant_id;agent_id=$AgentId;asset_id=$AssetId;release_id=$ReleaseId;agent_sha256=$inputDto.agent_sha256;helper_sha256=$inputDto.helper_sha256;seconds=$Seconds;requires_helper_creation=(!$h);case_id=$CaseId}|ConvertTo-Json -Depth 6 -Compress;return}
|
||||
try {
|
||||
# The updater and agent hold the same file throughout a transition or execution.
|
||||
$gate=[IO.File]::Open((Join-Path $data 'release-job.lock'),'Open','ReadWrite','None')
|
||||
Check ((JsonFile $active).release_id -ceq $ReleaseId.ToString()) 'Release switched during preparation.'
|
||||
if($Action -eq 'Resume'){
|
||||
Check (!(Service $helper) -and !(JsonFile $cfg).windows_update_helper -and !(Test-Path -LiteralPath $root)) 'Helper still active.'
|
||||
if(Test-Path -LiteralPath $archive){VerifyMarker $archive}
|
||||
StartNormal
|
||||
[ordered]@{actor_running=((Get-Service $actor).Status -eq 'Running');release_pull_running=((Get-Service 'RmmDiscoveryReleasePull').Status -eq 'Running')}|ConvertTo-Json -Compress
|
||||
return
|
||||
}
|
||||
if($Action -eq 'Remove'){
|
||||
RemoveWindow
|
||||
[ordered]@{closed=$true;case_id=$CaseId;agent_id=$AgentId;release_id=$ReleaseId;helper_registered=[bool](Service $helper);actor_running=((Get-Service $actor).Status -eq 'Running');release_pull_running=((Get-Service 'RmmDiscoveryReleasePull').Status -eq 'Running')}|ConvertTo-Json -Compress
|
||||
return
|
||||
}
|
||||
Check (!(Test-Path -LiteralPath $archive)) 'Case already closed.'
|
||||
Check ((!$h) -or (Test-Path -LiteralPath $marker)) 'Existing helper service has no matching protected case.'
|
||||
$actorSid=GetSid $actor
|
||||
# The helper runs as SYSTEM; its service SID is optional on file DACLs.
|
||||
NewPrivateDir $root @($actorSid);WriteFixed $marker $markerJson
|
||||
Check (!(Test-Path -LiteralPath (Join-Path $data 'release-state\release-transition.json'))) 'Release transition must finish before maintenance.'
|
||||
Set-Service 'RmmDiscoveryReleasePull' -StartupType Manual
|
||||
if((Get-Service 'RmmDiscoveryReleasePull').Status -ne 'Stopped'){Stop-Service 'RmmDiscoveryReleasePull'}
|
||||
if (!$h) {
|
||||
New-Service -Name $helper -BinaryPathName $helperCommand -StartupType Manual | Out-Null
|
||||
& "$env:SystemRoot\System32\sc.exe" sidtype $helper unrestricted | Out-Null
|
||||
Check ($LASTEXITCODE -eq 0) 'Could not set helper service SID.'
|
||||
}
|
||||
$rendered=($inputDto|ConvertTo-Json -Compress -Depth 6)|& $helperExe --prepare-enrolled-windows-update
|
||||
Check ($LASTEXITCODE -eq 0) 'Typed helper policy renderer failed.'
|
||||
$prepared=$rendered|ConvertFrom-Json
|
||||
NewPrivateDir (Join-Path $root 'state') @()
|
||||
$intents=Join-Path $root 'agent-intents'
|
||||
NewPrivateDir $intents @($actorSid)
|
||||
foreach($leaf in @('system-intents.sqlite','system-intents.sqlite-journal')){
|
||||
$p=Join-Path $intents $leaf
|
||||
if(!(Test-Path -LiteralPath $p)){[IO.File]::Open($p,'CreateNew').Dispose()}
|
||||
NoLink $p
|
||||
$acl=[Security.AccessControl.FileSecurity]::new();$acl.SetOwner($admin);$acl.SetAccessRuleProtection($true,$false)
|
||||
foreach($trusted in @($system,$admin)){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($trusted,'FullControl','Allow'))}
|
||||
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($actorSid,[Security.AccessControl.FileSystemRights]0x12019f,'Allow'))
|
||||
Set-Acl -LiteralPath $p -AclObject $acl
|
||||
}
|
||||
WriteFixed (Join-Path $root 'helper.json') $prepared.helper_settings
|
||||
WriteFixed (Join-Path $root 'agent-pin.json') $prepared.agent_pin
|
||||
if(!$conf.windows_update_helper) {
|
||||
if((Get-Service $actor).Status -ne 'Stopped'){Stop-Service -Name $actor}
|
||||
WriteFixed $backup ([IO.File]::ReadAllText($cfg))
|
||||
$conf|Add-Member -NotePropertyName windows_update_helper -NotePropertyValue $true -Force
|
||||
WriteFixed $written ($conf|ConvertTo-Json -Depth 12 -Compress)
|
||||
ReplaceConfig ([IO.File]::ReadAllText($written))
|
||||
}
|
||||
if((Get-Service $helper).Status -ne 'Running'){Start-Service $helper}
|
||||
if((Get-Service $actor).Status -ne 'Running'){Start-Service $actor}
|
||||
[ordered]@{installed=$true;case_id=$CaseId;tenant_id=$binding.tenant_id;asset_id=$AssetId;agent_id=$AgentId;release_id=$ReleaseId;agent_sha256=$inputDto.agent_sha256;helper_binary_sha256=$inputDto.helper_sha256;helper_policy_sha256=$prepared.helper_policy_sha256;seconds=$Seconds} |ConvertTo-Json -Compress
|
||||
} catch {
|
||||
$failure=$_
|
||||
if ($Action -eq 'Install' -and $gate -and (Test-Path -LiteralPath $marker)) {
|
||||
RemoveWindow
|
||||
StartNormal
|
||||
}
|
||||
throw $failure
|
||||
} finally {if($gate){$gate.Dispose()}}
|
||||
Reference in New Issue
Block a user