Files
TTSDream/lan-ups/desktop/deploy/windows/deployment.ps1
T

148 lines
7.8 KiB
PowerShell

#Requires -RunAsAdministrator
param(
[Parameter(Mandatory)][ValidateSet('Prepare', 'Install', 'Uninstall')][string]$Mode,
[Parameter(Mandatory)][string]$AppRoot,
[string]$Operator,
[switch]$EnableShutdown
)
$ErrorActionPreference = 'Stop'
$serviceName = 'LanUps.Agent'
$taskName = 'LanUps Desktop'
$serviceKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\LanUps.Agent'
function Confirm-InstallDirectory([string]$Path) {
if ($Path -notmatch '^[A-Za-z]:\\[^"\r\n]+$' -or $Path.Substring(2).Contains(':')) {
throw 'Select a local installation directory.'
}
$fullPath = [IO.Path]::GetFullPath($Path).TrimEnd('\')
$root = [IO.Path]::GetPathRoot($fullPath)
if ($fullPath.Length -le 3 -or [IO.DriveInfo]::new($root).DriveType -ne 'Fixed') {
throw 'Select a directory on a fixed local disk.'
}
$admins = 'S-1-5-32-544'
$system = 'S-1-5-18'
$installer = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
$trusted = @($admins, $system, $installer)
$sidType = [Security.Principal.SecurityIdentifier]
$directoryAcl = [Security.AccessControl.DirectorySecurity]::new()
$directoryAcl.SetAccessRuleProtection($true, $false)
$directoryAcl.SetOwner($sidType::new($admins))
foreach ($account in $trusted[0..1]) {
$directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new($account), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
}
$directoryAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sidType::new('S-1-5-32-545'), 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
function Assert-ProtectedItem($item, [bool]$volumeRoot) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Choose a directory without junctions or symbolic links: $($item.FullName)" }
$acl = Get-Acl -LiteralPath $item.FullName
if ($acl.GetOwner($sidType).Value -notin $trusted) { throw "The installation path must be owned by administrators or Windows: $($item.FullName)" }
# Volume roots can permit creating new folders, but must protect existing children.
$unsafeRights = if ($volumeRoot) { 0x100C0040 } else { 0x500D0156 }
foreach ($rule in $acl.GetAccessRules($true, $true, $sidType)) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $trusted -and
!($rule.PropagationFlags -band [Security.AccessControl.PropagationFlags]::InheritOnly) -and
($rule.FileSystemRights -band $unsafeRights)) {
throw "Ordinary users can modify this installation path: $($item.FullName)"
}
}
}
Assert-ProtectedItem (Get-Item -LiteralPath $root -Force) $true
$pathToCheck = $root
foreach ($part in $fullPath.Substring(3).Split('\')) {
$pathToCheck = Join-Path $pathToCheck $part
if (!(Test-Path -LiteralPath $pathToCheck)) { [void][IO.Directory]::CreateDirectory($pathToCheck, $directoryAcl) }
Assert-ProtectedItem (Get-Item -LiteralPath $pathToCheck -Force) $false
}
foreach ($kind in 'Agent', 'Desktop') {
$existing = Join-Path $fullPath $kind
if (Test-Path -LiteralPath $existing) {
Assert-ProtectedItem (Get-Item -LiteralPath $existing -Force) $false
Get-ChildItem -LiteralPath $existing -Recurse -Force | ForEach-Object { Assert-ProtectedItem $_ $false }
}
}
foreach ($filename in 'deployment.ps1', 'install.ps1') {
$file = Join-Path $fullPath $filename
if (Test-Path -LiteralPath $file) { Assert-ProtectedItem (Get-Item -LiteralPath $file -Force) $false }
}
return $fullPath
}
function Stop-LanUps {
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task -and $task.State -eq 'Running') { Stop-ScheduledTask -InputObject $task }
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and $service.Status -ne 'Stopped') {
Stop-Service -InputObject $service
$service.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(30))
}
$oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$desktopPaths = @(Join-Path $AppRoot 'Desktop\LanUps.Desktop.exe')
if ($oldPath -match '^"([A-Za-z]:\\[^"]+)\\Agent\\LanUps\.Agent\.exe"(?:\s|$)') {
$desktopPaths += Join-Path $Matches[1] 'Desktop\LanUps.Desktop.exe'
}
Get-Process LanUps.Desktop -ErrorAction SilentlyContinue | Where-Object { $_.Path -in $desktopPaths } |
ForEach-Object {
Stop-Process -Id $_.Id -ErrorAction SilentlyContinue
if (!$_.WaitForExit(10000)) { throw "LanUps desktop process $($_.Id) did not stop" }
}
}
$distributionLog = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'LanUps\setup.log'
New-Item -ItemType Directory -Path (Split-Path -Parent $distributionLog) -Force | Out-Null
Start-Transcript -LiteralPath $distributionLog -Append | Out-Null
try {
switch ($Mode) {
'Prepare' {
$AppRoot = Confirm-InstallDirectory $AppRoot
Stop-LanUps
}
'Install' {
if (!$Operator) {
$sessionId = (Get-Process -Id $PID).SessionId
$shell = Get-CimInstance Win32_Process -Filter "Name='explorer.exe' AND SessionId=$sessionId" | Select-Object -First 1
if ($shell) {
$owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner
if (!$owner.ReturnValue -and $owner.User) { $Operator = "$($owner.Domain)\$($owner.User)" }
}
if (!$Operator) {
$Operator = (Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue).Principal.UserId
}
if (!$Operator) {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if ($identity.IsSystem) { throw 'Specify /OPERATOR="DOMAIN\User" when running unattended as SYSTEM.' }
$Operator = $identity.Name
}
}
$oldPath = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$enable = $EnableShutdown -or $oldPath -match '(?i)\s--enable-shutdown\s*$'
& (Join-Path $PSScriptRoot 'install.ps1') -AppRoot $AppRoot -Operator $Operator -EnableShutdown:$enable
}
'Uninstall' {
$registered = (Get-ItemProperty -LiteralPath $serviceKey -Name ImagePath -ErrorAction SilentlyContinue).ImagePath
$expected = '"' + (Join-Path $AppRoot 'Agent\LanUps.Agent.exe') + '"'
if ($registered -and $registered -ine $expected -and $registered -ine "$expected --enable-shutdown") { break }
Stop-LanUps
$task = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($task) { Unregister-ScheduledTask -InputObject $task -Confirm:$false }
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) {
& (Join-Path $env:SystemRoot 'System32\sc.exe') delete $serviceName
if ($LASTEXITCODE) { throw "Could not remove $serviceName service." }
}
}
}
} catch {
Write-Host ($_ | Out-String)
throw
} finally {
Stop-Transcript | Out-Null
if ($Operator) {
try {
$account = [Security.Principal.NTAccount]::new($Operator)
$acl = Get-Acl -LiteralPath $distributionLog
$acl.SetAccessRule([Security.AccessControl.FileSystemAccessRule]::new($account, 'Read', 'Allow'))
Set-Acl -LiteralPath $distributionLog -AclObject $acl
} catch { Write-Warning "Unable to grant access to the setup log: $($_.Exception.Message)" }
}
}