#Requires -Version 5.1 [CmdletBinding(SupportsShouldProcess)] param( [switch]$RunAsSystem, [string]$StatePath = "$env:ProgramData\SGU\Enrollment\local-profile-security-policy.json" ) $ErrorActionPreference = 'Stop' $policyRelativePath = 'Software\Microsoft\Windows\CurrentVersion\Policies\System' $policyValueName = 'DisableLockWorkstation' $systemSid = 'S-1-5-18' function Test-SguRunningAsSystem { $currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value return $currentSid -eq $systemSid } function Set-SguRegistryDword { param( [Parameter(Mandatory)][string]$RegistryPath, [Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][int]$Value ) New-Item -Path $RegistryPath -Force | Out-Null New-ItemProperty -Path $RegistryPath -Name $Name -PropertyType DWord -Value $Value -Force | Out-Null $actual = Get-ItemPropertyValue -Path $RegistryPath -Name $Name -ErrorAction Stop if ([int]$actual -ne $Value) { throw "Could not set $Name to $Value in $RegistryPath." } } function Set-SguRegHiveDword { param( [Parameter(Mandatory)][string]$Hive, [Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)][int]$Value ) # Do not use the PowerShell registry provider against an offline NTUSER.DAT # hive. It can retain a registry-key handle until the runspace exits, which # prevents reg.exe from unloading that hive. reg.exe opens and closes its # own handle before returning. $key = "$Hive\$policyRelativePath" & reg.exe add $key /v $Name /t REG_DWORD /d $Value /f | Out-Null if ($LASTEXITCODE -ne 0) { throw "Could not set $Name in offline hive $Hive (exit code $LASTEXITCODE)." } $verification = (& reg.exe query $key /v $Name) -join [Environment]::NewLine if ($LASTEXITCODE -ne 0 -or ($verification -notmatch "\b$Name\b\s+REG_DWORD\s+0x0*1\b")) { throw "Could not verify $Name in offline hive $Hive." } } function Invoke-SguProfileHivePolicy { param( [Parameter(Mandatory)]$Profile, [Parameter(Mandatory)][string]$HiveName ) $profilePath = [string]$Profile.LocalPath $ntUserDat = Join-Path $profilePath 'NTUSER.DAT' if (-not (Test-Path -LiteralPath $ntUserDat -PathType Leaf)) { return [pscustomobject]@{ UserName = Split-Path $profilePath -Leaf Sid = [string]$Profile.SID LocalPath = $profilePath Status = 'SkippedNoHive' DisableLockWorkstation = $false } } $userName = Split-Path $profilePath -Leaf $loadedHivePath = "Registry::HKEY_USERS\$($Profile.SID)" if ($Profile.Loaded -and (Test-Path -LiteralPath $loadedHivePath)) { Set-SguRegistryDword -RegistryPath (Join-Path $loadedHivePath $policyRelativePath) ` -Name $policyValueName -Value 1 return [pscustomobject]@{ UserName = $userName Sid = [string]$Profile.SID LocalPath = $profilePath Status = 'UpdatedLoadedHive' DisableLockWorkstation = $true } } $regHive = "HKU\$HiveName" & reg.exe load $regHive $ntUserDat | Out-Null if ($LASTEXITCODE -ne 0) { throw "Unable to load the local profile hive for '$userName' (exit code $LASTEXITCODE)." } try { Set-SguRegHiveDword -Hive $regHive -Name $policyValueName -Value 1 } finally { & reg.exe unload $regHive | Out-Null if ($LASTEXITCODE -ne 0) { throw "Unable to unload the local profile hive for '$userName' (exit code $LASTEXITCODE)." } } [pscustomobject]@{ UserName = $userName Sid = [string]$Profile.SID LocalPath = $profilePath Status = 'UpdatedUnloadedHive' DisableLockWorkstation = $true } } function Invoke-SguDefaultProfilePolicy { $defaultProfile = Join-Path $env:SystemDrive 'Users\Default\NTUSER.DAT' if (-not (Test-Path -LiteralPath $defaultProfile -PathType Leaf)) { throw "The default user hive was not found at $defaultProfile." } $hiveName = 'SGU-DefaultProfile-' + [guid]::NewGuid().ToString('N') $regHive = "HKU\$hiveName" & reg.exe load $regHive $defaultProfile | Out-Null if ($LASTEXITCODE -ne 0) { throw "Unable to load the default user hive (exit code $LASTEXITCODE)." } try { Set-SguRegHiveDword -Hive $regHive -Name $policyValueName -Value 1 } finally { & reg.exe unload $regHive | Out-Null if ($LASTEXITCODE -ne 0) { throw "Unable to unload the default user hive (exit code $LASTEXITCODE)." } } } function Invoke-SguSystemWorker { param( [Parameter(Mandatory)][string]$ScriptPath, [Parameter(Mandatory)][string]$ResultPath ) $taskName = 'SGU-ApplyLocalProfileSecurity-' + [guid]::NewGuid().ToString('N') $powerShellPath = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $escapedScriptPath = $ScriptPath.Replace("'", "''") $escapedResultPath = $ResultPath.Replace("'", "''") # Task Scheduler does not apply PowerShell quoting rules to a -File command # line consistently. An encoded command makes the SYSTEM hand-off reliable # even when the enrollment directory contains spaces. $workerCommand = "& '$escapedScriptPath' -RunAsSystem -StatePath '$escapedResultPath'" $encodedWorkerCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($workerCommand)) $arguments = "-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand $encodedWorkerCommand" $action = New-ScheduledTaskAction -Execute $powerShellPath -Argument $arguments $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest try { Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Force | Out-Null Start-ScheduledTask -TaskName $taskName $deadline = (Get-Date).AddMinutes(2) do { Start-Sleep -Milliseconds 400 $task = Get-ScheduledTask -TaskName $taskName -ErrorAction Stop } while ($task.State -eq 'Running' -and (Get-Date) -lt $deadline) $taskInfo = Get-ScheduledTaskInfo -TaskName $taskName -ErrorAction Stop if ($task.State -eq 'Running') { throw 'The temporary SYSTEM policy worker did not finish within two minutes.' } if (-not (Test-Path -LiteralPath $ResultPath -PathType Leaf)) { if ($taskInfo.LastTaskResult -ne 0) { throw "The temporary SYSTEM policy worker failed with exit code $($taskInfo.LastTaskResult) and did not write its verification state." } throw 'The SYSTEM policy worker completed without writing its verification state.' } $result = Get-Content -LiteralPath $ResultPath -Raw | ConvertFrom-Json if ($taskInfo.LastTaskResult -ne 0) { $failureDetail = if ($result.Error) { ": $($result.Error)" } else { '' } throw "The temporary SYSTEM policy worker failed with exit code $($taskInfo.LastTaskResult)$failureDetail" } if (-not $result.IsValid) { throw 'The SYSTEM policy worker did not verify every local user profile.' } return $result } finally { Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue } } $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = [Security.Principal.WindowsPrincipal]::new($identity) if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run this script from an elevated Windows PowerShell session.' } if ($RunAsSystem -and -not (Test-SguRunningAsSystem)) { throw '-RunAsSystem is reserved for the temporary SYSTEM policy worker.' } $stateDirectory = Split-Path -Path $StatePath -Parent if (-not $RunAsSystem) { if (-not $PSCmdlet.ShouldProcess($env:COMPUTERNAME, 'Apply DisableLockWorkstation to every local user profile')) { return } New-Item -ItemType Directory -Path $stateDirectory -Force | Out-Null $workerResult = Invoke-SguSystemWorker -ScriptPath $PSCommandPath -ResultPath $StatePath return [pscustomobject]$workerResult } New-Item -ItemType Directory -Path $stateDirectory -Force | Out-Null $profileResults = [Collections.Generic.List[object]]::new() $defaultProfileConfigured = $false $failure = $null try { $localSids = @(Get-LocalUser | ForEach-Object { $_.SID.Value }) $localProfiles = @(Get-CimInstance Win32_UserProfile | Where-Object { -not $_.Special -and $localSids -contains $_.SID }) $counter = 0 foreach ($profile in $localProfiles) { $counter++ $hiveName = 'SGU-LocalProfile-{0}-{1}' -f $counter, [guid]::NewGuid().ToString('N') $profileResults.Add((Invoke-SguProfileHivePolicy -Profile $profile -HiveName $hiveName)) } Invoke-SguDefaultProfilePolicy $defaultProfileConfigured = $true } catch { $failure = $_.Exception.Message } $failedProfiles = @($profileResults | Where-Object { -not $_.DisableLockWorkstation }) $result = [pscustomobject]@{ ComputerName = $env:COMPUTERNAME GeneratedAt = (Get-Date).ToString('o') IsValid = ([string]::IsNullOrWhiteSpace($failure) -and $defaultProfileConfigured -and $failedProfiles.Count -eq 0) PolicyName = $policyValueName PolicyValue = 1 LocalProfiles = @($profileResults) DefaultProfileConfigured = $defaultProfileConfigured Error = $failure } $result | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $StatePath -Encoding UTF8 if (-not $result.IsValid) { $failureMessage = if ($failure) { $failure } else { 'DisableLockWorkstation could not be applied to every local user profile.' } throw $failureMessage } [pscustomobject]$result