config-central/src/Elevation.psm1

73 lines
4.9 KiB
PowerShell

Set-StrictMode -Version Latest
function Test-IsAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Protect-ElevationFile {
param([Parameter(Mandatory)][string]$Path)
$currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetAccessRuleProtection($true, $false)
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($currentSid, 'FullControl', 'Allow'))
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('BUILTIN\Administrators', 'FullControl', 'Allow'))
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('NT AUTHORITY\SYSTEM', 'FullControl', 'Allow'))
[System.IO.File]::SetAccessControl($Path, $acl)
}
function Invoke-ElevatedPackageBatch {
param([Parameter(Mandatory)]$Operations, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Paths, [string]$LogPath)
if (@($Operations).Count -eq 0) { return @() }
if (Test-IsAdministrator) { return Invoke-PackagePlan -Plan $Operations -LogPath $LogPath }
$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 = 'packages'; operations = @($Operations); logPath = $LogPath }
try {
$request | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $requestPath -Encoding utf8NoBOM
Protect-ElevationFile -Path $requestPath
if ($requestPath.Contains('"') -or $resultPath.Contains('"') -or $RepositoryRoot.Contains('"')) { throw 'Elevation paths contain unsupported quote characters.' }
$worker = Join-Path $RepositoryRoot 'src/elevated-worker.ps1'
$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 worker failed with exit code $($process.ExitCode)." }
$result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json -Depth 16
return @($result.results)
}
finally { Remove-Item -LiteralPath $requestPath, $resultPath -Force -ErrorAction SilentlyContinue }
}
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