From 84a68e11c2f0b97a5c07ef5ffcfe0635d237778a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 16 Oct 2026 14:30:33 +0200 Subject: [PATCH] Elevate managed hosts file updates --- TASKS.md | 2 +- src/Core.psm1 | 15 ++++++++++++++- src/Elevation.psm1 | 33 ++++++++++++++++++++++++++++++--- src/elevated-worker.ps1 | 41 ++++++++++++++++++++++++++++++++++------- 4 files changed, 79 insertions(+), 12 deletions(-) diff --git a/TASKS.md b/TASKS.md index 43d15d1..8bf5322 100644 --- a/TASKS.md +++ b/TASKS.md @@ -107,5 +107,5 @@ open until it is run on disposable machines with the required account setups. - [ ] Manage Ontime user settings without treating projects, uploads, or logs as config. - [ ] Manage XnView MP preferences without committing its catalog or thumbnails. - [ ] Add safe Nextcloud preconfiguration without committing account credentials. -- [ ] Manage a marked block in the Windows hosts file through the elevated worker. +- [x] Manage a marked block in the Windows hosts file through the elevated worker. - [ ] Document how to capture and customize the application-specific values. diff --git a/src/Core.psm1 b/src/Core.psm1 index 1816bc4..838516e 100644 --- a/src/Core.psm1 +++ b/src/Core.psm1 @@ -86,7 +86,20 @@ function Invoke-ApplyPlan { [void](Add-RunResult -Run $run -Kind config -Name $operation.name -Status Skipped -Message "Required package '$($operation.requiresPackage)' failed") continue } - $configResult = Invoke-ConfigOperation -Operation $operation -Paths $Paths -State $Plan.state -Force:$ForceConfigs + if ($operation.requiresAdmin -and $operation.action -notin @('None', 'Adopt')) { + if ($operation.action -eq 'Conflict' -and -not $ForceConfigs) { + $configResult = [pscustomobject]@{ name = $operation.name; status = 'Conflict'; message = "$($operation.reason); use -ForceConfigs to back up and replace it" } + } + else { + try { + $configResult = Invoke-ElevatedConfigOperation -Operation $operation -RepositoryRoot $RepositoryRoot -Paths $Paths + $Plan.state.configs[$operation.name] = [ordered]@{ target = $operation.target; deployedHash = $operation.sourceHash; sourceHash = $operation.sourceHash; mode = $operation.mode; deployedAt = [DateTimeOffset]::UtcNow.ToString('o'); lastBackup = $configResult.backup } + Write-JsonAtomic -Path $Paths.State -Value $Plan.state + } + catch { $configResult = [pscustomobject]@{ name = $operation.name; status = 'Failed'; message = $_.Exception.Message } } + } + } + else { $configResult = Invoke-ConfigOperation -Operation $operation -Paths $Paths -State $Plan.state -Force:$ForceConfigs } [void](Add-RunResult -Run $run -Kind config -Name $configResult.name -Status $configResult.status -Message $configResult.message) } $result.operations = @($run.results) diff --git a/src/Elevation.psm1 b/src/Elevation.psm1 index 408e0f8..cbb2e28 100644 --- a/src/Elevation.psm1 +++ b/src/Elevation.psm1 @@ -25,7 +25,7 @@ function Invoke-ElevatedPackageBatch { $requestId = [guid]::NewGuid().ToString('N') $requestPath = Join-Path $Paths.Root "elevation-$requestId.request.json" $resultPath = Join-Path $Paths.Root "elevation-$requestId.result.json" - $request = [ordered]@{ schemaVersion = 1; operations = @($Operations); logPath = $LogPath } + $request = [ordered]@{ schemaVersion = 1; requestType = 'packages'; operations = @($Operations); logPath = $LogPath } try { $request | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $requestPath -Encoding utf8NoBOM Protect-ElevationFile -Path $requestPath @@ -35,11 +35,38 @@ function Invoke-ElevatedPackageBatch { try { $process = Start-Process -FilePath 'pwsh.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru } catch { throw "Administrator approval was cancelled or could not start: $($_.Exception.Message)" } if ($process.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $resultPath -PathType Leaf)) { throw "Elevated worker failed with exit code $($process.ExitCode)." } - Protect-ElevationFile -Path $resultPath $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json -Depth 16 return @($result.results) } finally { Remove-Item -LiteralPath $requestPath, $resultPath -Force -ErrorAction SilentlyContinue } } -Export-ModuleMember -Function Test-IsAdministrator, Invoke-ElevatedPackageBatch +function Invoke-ElevatedConfigOperation { + param([Parameter(Mandatory)]$Operation, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Paths) + if ($Operation.mode -ne 'hosts-block') { throw "Config mode '$($Operation.mode)' cannot be elevated." } + $requestId = [guid]::NewGuid().ToString('N') + $requestPath = Join-Path $Paths.Root "elevation-$requestId.request.json" + $resultPath = Join-Path $Paths.Root "elevation-$requestId.result.json" + $request = [ordered]@{ + schemaVersion = 1 + requestType = 'hosts' + operation = [ordered]@{ name = $Operation.name; mode = $Operation.mode; target = $Operation.target; desired = @($Operation.desired); sourceHash = $Operation.sourceHash } + backupRoot = $Paths.Backups + } + try { + $request | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $requestPath -Encoding utf8NoBOM + Protect-ElevationFile -Path $requestPath + $worker = Join-Path $RepositoryRoot 'src/elevated-worker.ps1' + foreach ($path in @($requestPath, $resultPath, $RepositoryRoot, $worker)) { if ($path.Contains('"')) { throw 'Elevation paths contain unsupported quote characters.' } } + $arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$worker`" -RequestPath `"$requestPath`" -ResultPath `"$resultPath`" -RepositoryRoot `"$RepositoryRoot`"" + try { $process = Start-Process -FilePath 'pwsh.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru } + catch { throw "Administrator approval was cancelled or could not start: $($_.Exception.Message)" } + if ($process.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $resultPath -PathType Leaf)) { throw "Elevated hosts worker failed with exit code $($process.ExitCode)." } + $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json -Depth 16 + if (-not $result.succeeded) { throw [string]$result.error } + return $result.result + } + finally { Remove-Item -LiteralPath $requestPath, $resultPath -Force -ErrorAction SilentlyContinue } +} + +Export-ModuleMember -Function Test-IsAdministrator, Invoke-ElevatedPackageBatch, Invoke-ElevatedConfigOperation diff --git a/src/elevated-worker.ps1 b/src/elevated-worker.ps1 index a1006e1..05efacd 100644 --- a/src/elevated-worker.ps1 +++ b/src/elevated-worker.ps1 @@ -24,14 +24,41 @@ try { if (-not $worker.StartsWith(($root.TrimEnd('\') + '\'), [System.StringComparison]::OrdinalIgnoreCase)) { throw 'Elevated worker is outside the repository snapshot.' } $request = Get-Content -LiteralPath $RequestPath -Raw | ConvertFrom-Json -Depth 16 if ($request.schemaVersion -ne 1) { throw 'Unsupported elevation request version.' } - foreach ($operation in @($request.operations)) { - if ($operation.kind -ne 'package' -or $operation.action -notin @('Install', 'Upgrade', 'None', 'Warning')) { throw 'Elevation request contains an unsupported operation.' } - if ($operation.package.id -notmatch '^[A-Za-z0-9._+-]+$' -or $operation.package.source -notmatch '^[A-Za-z0-9._+-]+$') { throw 'Elevation request contains an unsafe package identifier.' } - if ($operation.package.PSObject.Properties['scope'] -and $operation.package.scope -ne 'machine') { throw 'Elevated operations must use machine scope.' } + if ($request.requestType -eq 'packages') { + foreach ($operation in @($request.operations)) { + if ($operation.kind -ne 'package' -or $operation.action -notin @('Install', 'Upgrade', 'None', 'Warning')) { throw 'Elevation request contains an unsupported operation.' } + if ($operation.package.id -notmatch '^[A-Za-z0-9._+-]+$' -or $operation.package.source -notmatch '^[A-Za-z0-9._+-]+$') { throw 'Elevation request contains an unsafe package identifier.' } + if ($operation.package.PSObject.Properties['scope'] -and $operation.package.scope -ne 'machine') { throw 'Elevated operations must use machine scope.' } + } + Import-Module (Join-Path $root 'src/Packages.psm1') -Force + $results = Invoke-PackagePlan -Plan @($request.operations) -LogPath ([string]$request.logPath) + Write-WorkerResult ([ordered]@{ succeeded = -not [bool]($results | Where-Object status -eq 'Failed'); results = $results }) + exit 0 } - Import-Module (Join-Path $root 'src/Packages.psm1') -Force - $results = Invoke-PackagePlan -Plan @($request.operations) -LogPath ([string]$request.logPath) - Write-WorkerResult ([ordered]@{ succeeded = -not [bool]($results | Where-Object status -eq 'Failed'); results = $results }) + if ($request.requestType -ne 'hosts') { throw 'Unknown elevation request type.' } + $operation = $request.operation + if ($operation.mode -ne 'hosts-block' -or $operation.name -notmatch '^[a-z0-9][a-z0-9-]*$') { throw 'Invalid elevated hosts operation.' } + $expectedTarget = [IO.Path]::GetFullPath((Join-Path ([Environment]::SystemDirectory) 'drivers\etc\hosts')) + if ([IO.Path]::GetFullPath([string]$operation.target) -ne $expectedTarget) { throw 'Elevated hosts target is not the Windows hosts file.' } + foreach ($line in @($operation.desired)) { + $parts = @(([string]$line).Trim() -split '\s+') + $address = $null + if ($parts.Count -lt 2 -or -not [Net.IPAddress]::TryParse($parts[0], [ref]$address)) { throw "Invalid elevated hosts entry '$line'." } + foreach ($hostName in $parts[1..($parts.Count - 1)]) { if ($hostName.StartsWith('#')) { break }; if ($hostName -notmatch '^[A-Za-z0-9._-]+$') { throw "Invalid elevated host name '$hostName'." } } + } + $backupFolder = Join-Path ([IO.Path]::GetFullPath([string]$request.backupRoot)) $operation.name + [void](New-Item -ItemType Directory -Path $backupFolder -Force) + $backup = Join-Path $backupFolder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).bak" + Copy-Item -LiteralPath $expectedTarget -Destination $backup -Force + Import-Module (Join-Path $root 'src/Adapters.psm1') -Force + $content = Set-HostsBlockContent -Target $expectedTarget -Name $operation.name -Lines @($operation.desired) + $temporary = Join-Path (Split-Path -Parent $expectedTarget) ".hosts.$([guid]::NewGuid().ToString('N')).tmp" + try { + [IO.File]::WriteAllText($temporary, $content, [Text.UTF8Encoding]::new($false)) + [IO.File]::Move($temporary, $expectedTarget, $true) + } + finally { Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue } + Write-WorkerResult ([ordered]@{ succeeded = $true; result = [ordered]@{ name = $operation.name; status = 'Succeeded'; message = "Deployed; backup: $backup"; backup = $backup; deployedHash = $operation.sourceHash } }) exit 0 } catch {