smoke-machine-store.ps1 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <#
  2. Machine-wide state store lifecycle smoke (`%ProgramData%\sandbox-runtime`).
  3. Asserts the elevated install provisions the shared state — the
  4. registry store (HKLM\SOFTWARE\sandbox-runtime: identity/marker;
  5. Cred subkey Users-read-only + sandbox DENY; Ca subkey
  6. user-recordable + sandbox DENY) and the ca\-hosting directory
  7. (owned by Administrators, sandbox-group DENY, Users modify) —
  8. that a sandboxed child can read neither the credential key nor
  9. the store directory,
  10. that an install running as SYSTEM (the SCCM/Intune fleet shape)
  11. leaves a credential the INTERACTIVE user's broker can read and
  12. spawn with — the per-user-store bug this store exists to fix —
  13. that a re-install rotates the shared credential in place, that a
  14. NON-ADMIN standard user's broker can read the credential and
  15. write the shared state DB (acl grant/restore — the BUILTIN\Users
  16. ACEs, which the elevated outer script cannot prove) while its
  17. exec refuses fail-closed inside a session it doesn't own (the
  18. BNO-hardening gate), and that a full uninstall removes the
  19. credential with the account.
  20. Self-contained: installs under a fixed test-only sublayer GUID
  21. (distinct from the other smoke scripts); uninstalls in `finally`.
  22. #>
  23. param(
  24. [Parameter(Mandatory = $true, Position = 0)]
  25. [string] $Exe
  26. )
  27. $ErrorActionPreference = 'Stop'
  28. # Fixed test-only sublayer; referenced by cleanup.ps1.
  29. $Sublayer = '4c7d9b21-3e58-4a06-9d17-8f2a6c40be93'
  30. $PortRange = '60080-60089'
  31. function Run { param([string[]] $argv)
  32. & $Exe @argv
  33. if ($LASTEXITCODE -ne 0) {
  34. throw "srt-win $($argv -join ' ') exited $LASTEXITCODE"
  35. }
  36. }
  37. function J { param([string[]] $argv) Run $argv | ConvertFrom-Json }
  38. function RunCapture { param([string[]] $argv)
  39. $raw = & $Exe @argv 2>&1 | Out-String
  40. return [pscustomobject]@{ exit = $LASTEXITCODE; raw = $raw }
  41. }
  42. $cmd = Join-Path $env:SystemRoot 'System32\cmd.exe'
  43. $stateDir = Join-Path $env:ProgramData 'sandbox-runtime'
  44. $regBase = 'HKLM:\SOFTWARE\sandbox-runtime'
  45. function CredRecorded { [bool](Get-ItemProperty "$regBase\Cred" -Name Blob -ea SilentlyContinue) }
  46. $env:SANDBOX_RUNTIME_WIN_DEBUG = '1'
  47. Write-Host "smoke-machine-store: sublayer=$Sublayer exe=$Exe"
  48. try { Start-Service seclogon -ea Stop } catch {
  49. Write-Host "smoke-machine-store: WARNING: Start-Service seclogon: $_"
  50. }
  51. try {
  52. # ── MS1: elevated install provisions the machine store ───────────
  53. Run @('install', '--sublayer-guid', $Sublayer, '--proxy-port-range', $PortRange, '--force')
  54. $us = J @('user', 'status')
  55. if (-not $us.cred_present) { throw 'MS1: cred_present false after machine-store install' }
  56. if (-not (CredRecorded)) { throw 'MS1: Cred\Blob missing from HKLM store' }
  57. $acl = Get-Acl $stateDir
  58. if ($acl.Owner -notmatch 'Administrators$') {
  59. throw "MS1: state dir owner expected Administrators, got '$($acl.Owner)'"
  60. }
  61. $deny = $acl.Access | Where-Object {
  62. $_.AccessControlType -eq 'Deny' -and
  63. $_.IdentityReference.Value -match 'sandbox-runtime-users$'
  64. }
  65. if (-not $deny) {
  66. throw "MS1: state-dir DACL has no DENY for sandbox-runtime-users; got:`n$($acl.Access | Out-String)"
  67. }
  68. $usersModify = $acl.Access | Where-Object {
  69. $_.AccessControlType -eq 'Allow' -and
  70. $_.IdentityReference.Value -match '\\Users$' -and
  71. ($_.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::WriteData)
  72. }
  73. if (-not $usersModify) {
  74. throw "MS1: state-dir DACL grants BUILTIN\Users no write; got:`n$($acl.Access | Out-String)"
  75. }
  76. $cacl = Get-Acl "$regBase\Cred"
  77. $credDeny = $cacl.Access | Where-Object {
  78. $_.AccessControlType -eq 'Deny' -and
  79. $_.IdentityReference.Value -match 'sandbox-runtime-users$'
  80. }
  81. if (-not $credDeny) {
  82. throw "MS1: Cred key has no DENY for sandbox-runtime-users; got:`n$($cacl.Access | Out-String)"
  83. }
  84. $credUsersWrite = $cacl.Access | Where-Object {
  85. $_.AccessControlType -eq 'Allow' -and
  86. $_.IdentityReference.Value -match '\\Users$' -and
  87. ($_.RegistryRights -band [System.Security.AccessControl.RegistryRights]::SetValue)
  88. }
  89. if ($credUsersWrite) {
  90. throw "MS1: Cred key is writable by BUILTIN\Users; got:`n$($cacl.Access | Out-String)"
  91. }
  92. Write-Host 'MS1 ok: store provisioned (dir owner+deny+Users modify; Cred key read-only + denied)'
  93. # ── MS2: sandboxed child denied on the Cred key and store dir ────
  94. $r = RunCapture @('exec', '--quiet', '--', $cmd, '/c', 'reg query HKLM\SOFTWARE\sandbox-runtime\Cred /v Blob')
  95. if ($r.exit -eq 0) { throw "MS2: child READ Cred\Blob. raw: $($r.raw)" }
  96. $r = RunCapture @('exec', '--quiet', '--', $cmd, '/c', 'reg add HKLM\SOFTWARE\sandbox-runtime /v rtEsc /d x /f')
  97. if ($r.exit -eq 0) { throw 'MS2: child WROTE the HKLM store' }
  98. $r = RunCapture @('exec', '--quiet', '--', $cmd, '/c', "dir `"$stateDir`"")
  99. if ($r.exit -eq 0) { throw "MS2: child LISTED the store dir. raw: $($r.raw)" }
  100. Write-Host 'MS2 ok: sandbox child denied on Cred key, store key write, and store dir'
  101. # ── MS3: SYSTEM install is readable by the interactive user ──────
  102. # The fleet shape (SCCM/Intune run installs as SYSTEM). Under the
  103. # per-user store this left the interactive user's dependency check
  104. # at cred_present:false — the bug the machine store fixes.
  105. Run @('uninstall', '--sublayer-guid', $Sublayer)
  106. if (CredRecorded) { throw 'MS3: Cred\Blob survived full uninstall' }
  107. $task = 'srt-win-ms3-system-install'
  108. # A scheduled task starts in System32, so the exe path must be
  109. # absolute; run through a wrapper .cmd that captures output, since
  110. # a SYSTEM task's console is otherwise invisible.
  111. $exeFull = (Resolve-Path $Exe).Path
  112. $ms3Log = 'C:\Windows\Temp\srt-ms3-system-install.log'
  113. $runner = 'C:\Windows\Temp\srt-ms3-system-install.cmd'
  114. Remove-Item $ms3Log -ea SilentlyContinue
  115. $ms3Rc = 'C:\Windows\Temp\srt-ms3-system-install.rc'
  116. Remove-Item $ms3Rc -ea SilentlyContinue
  117. @(
  118. '@echo off'
  119. "`"$exeFull`" install --sublayer-guid $Sublayer --proxy-port-range $PortRange --force > `"$ms3Log`" 2>&1"
  120. "echo %errorlevel% > `"$ms3Rc`""
  121. ) | Set-Content $runner -Encoding ascii
  122. schtasks /Create /F /RU SYSTEM /SC ONCE /ST 00:00 /TN $task /TR "`"$runner`"" | Out-Null
  123. if ($LASTEXITCODE -ne 0) { throw "MS3: schtasks /Create exited $LASTEXITCODE" }
  124. try {
  125. schtasks /Run /TN $task | Out-Null
  126. if ($LASTEXITCODE -ne 0) { throw "MS3: schtasks /Run exited $LASTEXITCODE" }
  127. $deadline = (Get-Date).AddSeconds(120)
  128. while (-not (CredRecorded)) {
  129. if ((Get-Date) -gt $deadline) {
  130. $installOut = if (Test-Path $ms3Log) { Get-Content $ms3Log | Out-String } else { '<no log>' }
  131. throw "MS3: SYSTEM install did not record Cred\Blob in 120s. install output:`n$installOut"
  132. }
  133. Start-Sleep -Seconds 2
  134. }
  135. # The credential is recorded BEFORE the WFP step, so its appearance
  136. # alone can mask a WFP-stage failure — wait for the wrapper's
  137. # recorded exit code and assert the whole install succeeded.
  138. $deadline = (Get-Date).AddSeconds(60)
  139. while (-not (Test-Path $ms3Rc)) {
  140. if ((Get-Date) -gt $deadline) { throw 'MS3: SYSTEM install exit code never recorded' }
  141. Start-Sleep -Seconds 2
  142. }
  143. $rc = (Get-Content $ms3Rc -Raw).Trim()
  144. if ($rc -ne '0') {
  145. $installOut = if (Test-Path $ms3Log) { Get-Content $ms3Log | Out-String } else { '<no log>' }
  146. throw "MS3: SYSTEM install exited ${rc}. install output:`n$installOut"
  147. }
  148. } finally {
  149. schtasks /Delete /F /TN $task | Out-Null
  150. Remove-Item $runner, $ms3Log, $ms3Rc -ea SilentlyContinue
  151. }
  152. $us = J @('user', 'status') # interactive user's view
  153. if (-not $us.cred_present) { throw 'MS3: interactive user sees cred_present:false after SYSTEM install' }
  154. $pw = & $Exe user read-cred
  155. if ($LASTEXITCODE -ne 0) { throw "MS3: interactive read-cred exited $LASTEXITCODE" }
  156. if ($pw.Length -ne 32) { throw "MS3: read-cred expected 32 chars, got $($pw.Length)" }
  157. $r = RunCapture @('exec', '--quiet', '--', $cmd, '/c', 'whoami')
  158. if ($r.exit -ne 0) { throw "MS3: interactive exec after SYSTEM install failed: $($r.raw)" }
  159. Write-Host 'MS3 ok: SYSTEM install; interactive user reads cred and spawns'
  160. # ── MS4: re-install rotates the shared credential in place ───────
  161. # Compare the DECRYPTED secret, not the blob bytes: DPAPI output
  162. # embeds random salt, so ciphertext differs on every write even
  163. # when the password was NOT rotated — the bytes comparison would
  164. # be vacuously green.
  165. $pwBefore = & $Exe user read-cred
  166. if ($LASTEXITCODE -ne 0) { throw "MS4: read-cred before rotation exited $LASTEXITCODE" }
  167. Run @('install', '--sublayer-guid', $Sublayer, '--proxy-port-range', $PortRange, '--force')
  168. $pwAfter = & $Exe user read-cred
  169. if ($LASTEXITCODE -ne 0 -or $pwAfter.Length -ne 32) {
  170. throw "MS4: read-cred after rotation failed (exit $LASTEXITCODE, len $($pwAfter.Length))"
  171. }
  172. if ($pwAfter -eq $pwBefore) {
  173. throw 'MS4: password unchanged across rotating re-install'
  174. }
  175. Write-Host 'MS4 ok: rotation refreshed the shared credential'
  176. # ── MS6: a NON-ADMIN user's broker works against the shared store ─
  177. # The outer script runs as an elevated Administrator, which would
  178. # pass even if the BUILTIN\Users ACEs were wrong (the BA ACE grants
  179. # full control) — so prove the Users leg with a real standard user:
  180. # status reads the shared credential, an acl grant/restore
  181. # round-trip exercises their own per-user session DB, and exec
  182. # (foreign-session here) refuses closed.
  183. $u6 = 'srt-ms6-user'
  184. $pw6 = 'Ms6!' + [guid]::NewGuid().ToString('N').Substring(0, 16)
  185. # /y: net.exe interactively prompts Y/N for passwords longer than
  186. # 14 chars, which hangs (exit -1) with no stdin in CI.
  187. net user $u6 $pw6 /add /y | Out-Null
  188. if ($LASTEXITCODE -ne 0) { throw "MS6: net user add exited $LASTEXITCODE" }
  189. try {
  190. $cred6 = [pscredential]::new(
  191. "$env:COMPUTERNAME\$u6",
  192. (ConvertTo-SecureString $pw6 -AsPlainText -Force))
  193. $pub = 'C:\Users\Public'
  194. $o6 = Join-Path $pub 'srt-ms6-out.txt'
  195. $e6 = Join-Path $pub 'srt-ms6-err.txt'
  196. $i6 = Join-Path $pub 'srt-ms6-in.json'
  197. function RunAsUser6 { param([string[]] $argv, [string] $stdin)
  198. Remove-Item $o6, $e6 -ea SilentlyContinue
  199. # -LoadUserProfile (LOGON_WITH_PROFILE) creates the account's
  200. # profile, but Start-Process -Credential still hands the child
  201. # the CALLER's environment — %LOCALAPPDATA% would point at the
  202. # admin's profile, which the standard user cannot even stat.
  203. # The acl commands open the per-user session store under
  204. # %LOCALAPPDATA%, so route through cmd and override the profile
  205. # variables to the standard user's own tree explicitly.
  206. $prof6 = "C:\Users\$u6"
  207. $inner = "set `"USERPROFILE=$prof6`" && set `"LOCALAPPDATA=$prof6\AppData\Local`" && `"$exeFull`" " + ($argv -join ' ')
  208. $sp = @{
  209. FilePath = $cmd; ArgumentList = @('/c', $inner); Credential = $cred6
  210. WorkingDirectory = $pub; NoNewWindow = $true; Wait = $true
  211. PassThru = $true; LoadUserProfile = $true
  212. RedirectStandardOutput = $o6; RedirectStandardError = $e6
  213. }
  214. if ($stdin) {
  215. Set-Content -Path $i6 -Value $stdin -Encoding ascii
  216. $sp.RedirectStandardInput = $i6
  217. }
  218. $p = Start-Process @sp
  219. [pscustomobject]@{
  220. exit = $p.ExitCode
  221. out = (Get-Content $o6 -Raw -ea SilentlyContinue)
  222. err = (Get-Content $e6 -Raw -ea SilentlyContinue)
  223. }
  224. }
  225. $r = RunAsUser6 @('user', 'status')
  226. if ($r.exit -ne 0) { throw "MS6: user status as standard user exited $($r.exit): $($r.err)" }
  227. $st6 = $r.out | ConvertFrom-Json
  228. if (-not $st6.cred_present) { throw 'MS6: standard user cannot see the shared credential' }
  229. # The grant target must be created BY the standard user: writing
  230. # an ACE needs WRITE_DAC, which they hold via CREATOR OWNER on
  231. # their own files (the real broker shape — a user grants on their
  232. # own working tree), not on directories some admin created.
  233. $probe6 = Join-Path $pub 'srt-ms6-probe'
  234. Remove-Item $probe6 -Recurse -Force -ea SilentlyContinue
  235. $mk = Start-Process -FilePath $cmd -ArgumentList @('/c', "mkdir `"$probe6`"") `
  236. -Credential $cred6 -WorkingDirectory $pub -NoNewWindow -Wait -PassThru -LoadUserProfile
  237. if ($mk.ExitCode -ne 0) { throw "MS6: mkdir as standard user exited $($mk.ExitCode)" }
  238. $r = RunAsUser6 @('acl', 'grant', '--holder-pid', $PID,
  239. '--sandbox-user-sid', $st6.marker_user_sid) `
  240. "{`"write`":[`"$($probe6 -replace '\\','\\')`"]}"
  241. if ($r.exit -ne 0) { throw "MS6: acl grant as standard user exited $($r.exit): $($r.err)" }
  242. # The Ca record must be WRITABLE by a standard user (unelevated
  243. # trust-ca records the DER there). Probe with an open requesting
  244. # exactly RegistryRights::SetValue — the DACL grants Users
  245. # KEY_READ|KEY_SET_VALUE and deliberately NOT KEY_WRITE (whose
  246. # CREATE_SUB_KEY bit is withheld), so tools that open with
  247. # KEY_WRITE (reg.exe add, the old product bug) are denied while
  248. # the product's set-value open succeeds. ReadWriteSubTree only
  249. # sets .NET's managed writable flag; the explicit rights arg
  250. # still governs the actual open.
  251. $caProbe = 'try { ' +
  252. '$k = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(''SOFTWARE\sandbox-runtime\Ca'', ' +
  253. '[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree, ' +
  254. '[System.Security.AccessControl.RegistryRights]::SetValue); ' +
  255. '$k.SetValue(''Ms6Probe'',''x''); Write-Output SETVALUE-OK } catch { Write-Output (''failed: '' + $_.Exception.Message) }'
  256. $r = RunAsUser6 @('user', 'status') # keep env plumbing warm
  257. $o7 = Join-Path $pub 'srt-ms6-ca.txt'
  258. Remove-Item $o7 -ea SilentlyContinue
  259. $pp = Start-Process -FilePath "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" `
  260. -ArgumentList @('-NoProfile','-Command', $caProbe) -Credential $cred6 -WorkingDirectory $pub `
  261. -NoNewWindow -Wait -PassThru -LoadUserProfile -RedirectStandardOutput $o7
  262. $caOut = Get-Content $o7 -Raw -ea SilentlyContinue
  263. if ($caOut -notmatch 'SETVALUE-OK') {
  264. throw "MS6: standard user cannot set-value the Ca record: $caOut"
  265. }
  266. Remove-ItemProperty 'HKLM:\SOFTWARE\sandbox-runtime\Ca' -Name Ms6Probe -ea SilentlyContinue
  267. Remove-Item $o7 -ea SilentlyContinue
  268. # revoke, not restore: grants are released by `acl revoke`
  269. # (restore releases deny stamps) — and assert the ALLOW ACE is
  270. # actually gone rather than trusting the exit code.
  271. $r = RunAsUser6 @('acl', 'revoke', '--holder-pid', $PID,
  272. '--sandbox-user-sid', $st6.marker_user_sid)
  273. if ($r.exit -ne 0) { throw "MS6: acl revoke as standard user exited $($r.exit): $($r.err)" }
  274. # Explicit ACEs only: C:\Users\Public is an ambient write-deny
  275. # target, so the probe dir INHERITS a srt-sandbox deny from it
  276. # ((I) in icacls) — that one is supposed to be there. The revoke
  277. # must remove the explicit grant ACE.
  278. $explicit = (icacls $probe6 | Out-String) -split "`n" |
  279. Where-Object { $_ -match 'srt-sandbox' -and $_ -notmatch '\(I\)' }
  280. if ($explicit) {
  281. throw "MS6: explicit sandbox-user ACE still on $probe6 after revoke: $explicit"
  282. }
  283. # exec from THIS shape must refuse, fail-closed: Start-Process
  284. # -Credential runs the standard user INSIDE the admin's session,
  285. # and the broker requires WRITE_DAC on the session's
  286. # BaseNamedObjects to stamp BNO hardening before spawning — a
  287. # session the user doesn't own is exactly where an unstampable
  288. # child could squat named objects, so erroring is the invariant.
  289. # (Real multi-user brokers run in their owner's own session,
  290. # which grants WRITE_DAC; the same-session spawn is MS3.)
  291. $r = RunAsUser6 @('exec', '--quiet', '--', $cmd, '/c', 'whoami')
  292. if ($r.exit -eq 0) { throw 'MS6: exec inside a foreign session unexpectedly succeeded' }
  293. if (($r.err + $r.out) -notmatch 'BaseNamedObjects|BNO') {
  294. throw "MS6: exec refusal should name the session BNO gate; got: $($r.err)$($r.out)"
  295. }
  296. Write-Host 'MS6 ok: standard user reads the cred + runs session acl ops; foreign-session exec refuses closed'
  297. } finally {
  298. net user $u6 /delete | Out-Null
  299. Remove-Item $o6, $e6, $i6, (Join-Path $pub 'srt-ms6-probe') -Recurse -Force -ea SilentlyContinue
  300. }
  301. # ── MS5: full uninstall removes the credential with the account ──
  302. Run @('uninstall', '--sublayer-guid', $Sublayer)
  303. if (CredRecorded) { throw 'MS5: Cred\Blob survived uninstall' }
  304. if (Test-Path $regBase) { throw 'MS5: HKLM store key survived uninstall' }
  305. $us = J @('user', 'status')
  306. if ($us.cred_present) { throw 'MS5: cred_present still true after uninstall' }
  307. Write-Host 'MS5 ok: uninstall removed the shared credential'
  308. Write-Host 'smoke-machine-store: all checks passed'
  309. } finally {
  310. & $Exe uninstall --sublayer-guid $Sublayer 2>&1 | Out-Null
  311. }