smoke-exec.ps1 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. <#
  2. Smoke test for `srt-win exec` (the two-hop sandbox-user launch).
  3. Self-contained: provisions the `srt-sandbox` account + WFP filters
  4. under a fixed test-only sublayer GUID via `srt-win install`, then
  5. exercises exec end-to-end. The fixed GUID lets the workflow's
  6. `if: always()` cleanup step uninstall any leaked filters even if
  7. this script throws mid-run.
  8. #>
  9. param(
  10. [Parameter(Mandatory = $true, Position = 0)]
  11. [string] $Exe
  12. )
  13. $ErrorActionPreference = 'Stop'
  14. # Fixed test-only sublayer; distinct from srt-win's compile-time
  15. # default and from anything smoke.ps1 uses. Referenced verbatim by
  16. # the workflow's always()-cleanup step.
  17. $Sublayer = '5b0e64f4-09f1-4c2e-8c97-4d2c0f4e9b7d'
  18. # Loopback PERMIT is scoped to this port range. Anything on
  19. # 127.0.0.1 outside it is BLOCKed. Match srt-win's default but pass
  20. # it explicitly so this script doesn't drift if the default changes.
  21. $PortRange = '60080-60089'
  22. $PortLo = 60080
  23. $PortHi = 60089
  24. # Bind a TcpListener on the first free port from $candidates.
  25. # Throws if none bind.
  26. function Bind-Listener {
  27. param([int[]] $Candidates)
  28. foreach ($p in $Candidates) {
  29. try {
  30. $l = [System.Net.Sockets.TcpListener]::new(
  31. [System.Net.IPAddress]::Loopback, $p)
  32. $l.Start()
  33. return $l
  34. } catch {
  35. # port in use — try next
  36. }
  37. }
  38. throw "no free port among: $($Candidates -join ',')"
  39. }
  40. function Run {
  41. param([string[]] $argv)
  42. & $Exe @argv
  43. if ($LASTEXITCODE -ne 0) {
  44. throw "srt-win $($argv -join ' ') exited $LASTEXITCODE"
  45. }
  46. }
  47. function J { param([string[]] $argv) Run $argv | ConvertFrom-Json }
  48. $cmd = Join-Path $env:SystemRoot 'System32\cmd.exe'
  49. $pwsh = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
  50. # Enable srt-win's per-exec stderr diagnostics (notably the
  51. # self-protect SDDL dump).
  52. $env:SANDBOX_RUNTIME_WIN_DEBUG = '1'
  53. Write-Host "smoke-exec: sublayer=$Sublayer exe=$Exe"
  54. # CreateProcessWithLogonW routes through the Secondary Logon
  55. # service. GHA runners have it; ensure it's running (idempotent).
  56. try { Start-Service seclogon -ea Stop } catch {
  57. Write-Host "smoke-exec: WARNING: Start-Service seclogon: $_"
  58. }
  59. # ── R0b: exec without provisioning → exit 15 ──
  60. $r0b = & $Exe exec -- $cmd /c 'exit 0' 2>&1 | Out-String
  61. if ($LASTEXITCODE -ne 15) {
  62. throw "R0b: expected exit 15 (not provisioned), got ${LASTEXITCODE}. out: $r0b"
  63. }
  64. if ($r0b -notmatch '(?i)srt-win install') {
  65. throw "R0b: expected re-run install hint. out: $r0b"
  66. }
  67. Write-Host 'R0b ok: exec exits 15 with install hint when not provisioned'
  68. # Full install under the test sublayer: provisions srt-sandbox +
  69. # sandbox-runtime-users + DPAPI cred + setup marker + the user-SID
  70. # WFP filter pair.
  71. Run @('install',
  72. '--sublayer-guid',$Sublayer,
  73. '--proxy-port-range',$PortRange)
  74. $us = J @('user','status')
  75. if (-not $us.user.exists) { throw 'R: srt-sandbox not provisioned' }
  76. $sbSid = $us.marker_user_sid
  77. if (-not $sbSid) { throw 'R: setup marker missing user_sid' }
  78. Write-Host "R: sandbox user provisioned (sid=$sbSid)"
  79. # ── V1: wfp verify — behavioral egress-block probe ──────────────
  80. # The non-elevated readiness check that replaced exec's WFP
  81. # pre-flight. The block-user filter from `install` above fires at
  82. # ALE_AUTH_CONNECT → WSAEACCES → exit 0 + "blocked". stderr (the
  83. # runner's BLOCKED line) flows to the host so it's in the CI log;
  84. # stdout is JUST the JSON line. `--target` is required: bind a
  85. # local listener on an out-of-range loopback port (same shape as
  86. # the product path — `verifyWindowsWfpEgress` does this in TS).
  87. $v1Lsn = Bind-Listener (49990..49999)
  88. $v1Tgt = "127.0.0.1:$($v1Lsn.LocalEndpoint.Port)"
  89. $vout = & $Exe wfp verify --target $v1Tgt
  90. $vexit = $LASTEXITCODE
  91. $v1Lsn.Stop()
  92. Write-Host "V1: wfp verify --target $v1Tgt exit=$vexit stdout='$vout'"
  93. if ($vexit -ne 0) {
  94. throw "V1: wfp verify expected exit 0 (blocked), got $vexit"
  95. }
  96. $v = $vout | ConvertFrom-Json
  97. if ($v.egress_probe -ne 'blocked') {
  98. throw "V1: wfp verify expected egress_probe=blocked, got '$($v.egress_probe)'"
  99. }
  100. Write-Host 'V1 ok: wfp verify reports egress_probe=blocked'
  101. # Exec helper. Same .exit/.raw/.out shape as before. The broker
  102. # forwards exactly what it is told via --env (it does NOT enumerate
  103. # its own environment), so pass PATH/PATHEXT here — same overlay the
  104. # TS wrapper builds.
  105. #
  106. # Watchdog: the two-hop chain (broker → CPWLW runner → restricted
  107. # child) has no console; a hang anywhere inside it would otherwise
  108. # sit until the GHA job timeout. 30s is generous — every R-row
  109. # payload is sub-second. System.Diagnostics.Process (not the `&`
  110. # call operator or Start-Process) so we get (a) WaitForExit with a
  111. # timeout and (b) per-element ArgumentList quoting that survives
  112. # PATH-with-spaces.
  113. function RExec {
  114. param([string[]] $tail)
  115. $argv = @('exec',
  116. '--env', "PATH=$($env:PATH)",
  117. '--env', "PATHEXT=$($env:PATHEXT)") + $tail
  118. $psi = [System.Diagnostics.ProcessStartInfo]::new()
  119. $psi.FileName = $Exe
  120. $psi.UseShellExecute = $false
  121. $psi.RedirectStandardOutput = $true
  122. $psi.RedirectStandardError = $true
  123. $psi.Environment['SANDBOX_RUNTIME_WIN_DEBUG'] = '1'
  124. foreach ($a in $argv) { $null = $psi.ArgumentList.Add($a) }
  125. $p = [System.Diagnostics.Process]::Start($psi)
  126. # Drain both pipes concurrently so a full pipe buffer can't wedge
  127. # WaitForExit.
  128. $so = $p.StandardOutput.ReadToEndAsync()
  129. $se = $p.StandardError.ReadToEndAsync()
  130. if (-not $p.WaitForExit(30000)) {
  131. try { $p.Kill($true) } catch { }
  132. $p.WaitForExit()
  133. throw ("RExec: TIMEOUT after 30s. argv: $($argv -join ' ')`n" +
  134. "stderr: $($se.Result)`nstdout: $($so.Result)")
  135. }
  136. $exit = $p.ExitCode
  137. $raw = $so.Result + $se.Result
  138. $lines = $raw -split "`r?`n"
  139. $child = ($lines | Where-Object { $_ -notmatch '^srt-win:' }) -join "`n"
  140. return [pscustomobject]@{ exit = $exit; raw = $raw; out = $child }
  141. }
  142. # ── R1: child runs as srt-sandbox ───────────────────────────────
  143. $r = RExec @('--', $cmd, '/c', 'whoami /user /FO CSV /NH')
  144. if ($r.exit -ne 0) { throw "R1: whoami exited $($r.exit). raw: $($r.raw)" }
  145. $row = $r.out | ConvertFrom-Csv -Header Name,SID
  146. if ($row.SID -ne $sbSid) {
  147. throw "R1: child user SID $($row.SID), expected $sbSid. raw: $($r.raw)"
  148. }
  149. Write-Host "R1 ok: two-hop child runs as srt-sandbox (sid=$($row.SID))"
  150. # ── R2: stdio piped broker ← runner ← child ─────────────────────
  151. $r = RExec @('--', $cmd, '/c', 'echo R2-STDOUT-MARK & echo R2-STDERR-MARK 1>&2')
  152. if ($r.out -notmatch 'R2-STDOUT-MARK') {
  153. throw "R2: stdout marker missing. raw: $($r.raw)"
  154. }
  155. if ($r.raw -notmatch 'R2-STDERR-MARK') {
  156. throw "R2: stderr marker missing. raw: $($r.raw)"
  157. }
  158. Write-Host 'R2 ok: stdout+stderr piped through runner to broker'
  159. # ── R3: exit code propagates broker ← runner ← child ────────────
  160. $r = RExec @('--', $cmd, '/c', 'exit 23')
  161. if ($r.exit -ne 23) {
  162. throw "R3: expected exit 23, got $($r.exit). raw: $($r.raw)"
  163. }
  164. Write-Host 'R3 ok: child exit code propagates through runner'
  165. # ── R4: env-merge — USERPROFILE isolated, PATH overlaid ─────────
  166. # LOGON_WITH_PROFILE gives the runner the sandbox user's profile
  167. # env (USERPROFILE/TEMP under C:\Users\srt-sandbox). The broker's
  168. # PATH is overlaid via the spec so tools resolve. Probe both.
  169. $r = RExec @('--', $cmd, '/c', 'echo UP=%USERPROFILE%& echo PATH=%PATH%')
  170. if ($r.out -notmatch '(?i)UP=.*srt-sandbox') {
  171. throw "R4: USERPROFILE not isolated to srt-sandbox. out: $($r.out)"
  172. }
  173. if ($r.out -notmatch '(?i)PATH=.*System32') {
  174. throw "R4: PATH overlay missing System32. out: $($r.out)"
  175. }
  176. Write-Host 'R4 ok: USERPROFILE isolated, broker PATH overlaid'
  177. # ── R4b: --env overlay restores the *_PROXY case-twin ───────────
  178. # The host spawn layer keeps only ONE casing of an env key, but
  179. # Cygwin/MSYS2 children read the lowercase names — so the runner
  180. # appends the missing twin. Passing HTTP_PROXY via --env and
  181. # finding BOTH casings in the child proves the repair.
  182. $r = RExec @('--env', "HTTP_PROXY=http://127.0.0.1:$PortLo",
  183. '--', $cmd, '/c', 'set http')
  184. if ($r.exit -ne 0) { throw "R4b: 'set http' exited $($r.exit). out: $($r.out)" }
  185. $lines = $r.out -split "`r?`n"
  186. if (-not ($lines | Where-Object { $_ -clike 'http_proxy=*' })) {
  187. throw "R4b: lowercase http_proxy twin missing in child. out: $($r.out)"
  188. }
  189. if (-not ($lines | Where-Object { $_ -clike 'HTTP_PROXY=*' })) {
  190. throw "R4b: uppercase HTTP_PROXY missing in child. out: $($r.out)"
  191. }
  192. Write-Host 'R4b ok: runner restores the lowercase twin of overlay-proxy vars'
  193. # ── R5: outbound blocked by block-user filter ───────────────────
  194. # The user-SID WFP filter blocks all srt-sandbox egress except
  195. # in-range loopback. No proxy env in this row, so the child's
  196. # direct curl must fail.
  197. $r = RExec @('--', $cmd, '/c', 'curl -sS -m 5 https://example.com')
  198. if ($r.exit -eq 0) {
  199. throw "R5: outbound curl succeeded under sandbox " +
  200. "(block-user not in effect?). out: $($r.out)"
  201. }
  202. Write-Host "R5 ok: outbound blocked for srt-sandbox (curl exit=$($r.exit))"
  203. # ── R5b: in-range loopback permitted ─────────────────────────────
  204. $inRangeR = Bind-Listener ($PortHi..($PortLo+5))
  205. $portInR = $inRangeR.LocalEndpoint.Port
  206. try {
  207. $r = RExec @('--', $pwsh, '-NoProfile', '-Command',
  208. "(Test-NetConnection 127.0.0.1 -Port $portInR " +
  209. "-WarningAction SilentlyContinue).TcpTestSucceeded")
  210. if ($r.out -notmatch '(?i)\bTrue\b') {
  211. throw "R5b: loopback to in-range port $portInR did not succeed. raw: $($r.raw)"
  212. }
  213. Write-Host "R5b ok: in-range loopback permitted for srt-sandbox (port=$portInR)"
  214. } finally {
  215. $inRangeR.Stop()
  216. }
  217. # ── R5c: out-of-range loopback blocked ───────────────────────────
  218. $outRange = Bind-Listener (50000, 50001, 50002, 49999)
  219. $portOut = $outRange.LocalEndpoint.Port
  220. try {
  221. $r = RExec @('--', $pwsh, '-NoProfile', '-Command',
  222. "(Test-NetConnection 127.0.0.1 -Port $portOut " +
  223. "-WarningAction SilentlyContinue).TcpTestSucceeded")
  224. if ($r.out -match '(?i)\bTrue\b') {
  225. throw "R5c: loopback to out-of-range port $portOut succeeded. raw: $($r.raw)"
  226. }
  227. # Sanity: prove the listener was actually live (reachable from
  228. # the unsandboxed broker), so a False isn't just "port closed".
  229. $bs = (Test-NetConnection 127.0.0.1 -Port $portOut `
  230. -WarningAction SilentlyContinue).TcpTestSucceeded
  231. if (-not $bs) {
  232. throw "R5c: broker-side connect to its own listener on " +
  233. "$portOut failed — test invalid"
  234. }
  235. Write-Host "R5c ok: loopback to out-of-range port $portOut blocked"
  236. } finally {
  237. $outRange.Stop()
  238. }
  239. # ── R5d: IPv6 loopback out-of-range blocked ──────────────────────
  240. # The WFP fence must cover the v6 layers too: a v4-only filter set
  241. # would leave [::1] as a silent hole to every local service. Real
  242. # listener on [::1], child connect must be denied (an
  243. # AccessDenied/timeout, never a successful connect).
  244. $v6l = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::IPv6Loopback, 49998)
  245. $v6l.Start()
  246. try {
  247. $r = RExec @('--', $pwsh, '-NoProfile', '-Command',
  248. "try { `$c = New-Object Net.Sockets.TcpClient([Net.Sockets.AddressFamily]::InterNetworkV6); " +
  249. "`$c.Connect('::1', 49998); Write-Output CONNECTED } catch { Write-Output blocked }")
  250. if ($r.out -match 'CONNECTED') {
  251. throw "R5d: sandboxed connect to [::1]:49998 succeeded — v6 fence hole. raw: $($r.raw)"
  252. }
  253. Write-Host 'R5d ok: IPv6 loopback out-of-range blocked'
  254. } finally {
  255. $v6l.Stop()
  256. }
  257. # ── R5e: loopback ALIAS (127.0.0.2) out-of-range blocked ─────────
  258. # 127.0.0.0/8 is all loopback; a filter keyed on 127.0.0.1 alone
  259. # would leave every other alias open. No listener needed — the
  260. # discriminating signal is AccessDenied (WFP) vs ConnectionRefused
  261. # (no filter, nothing listening).
  262. $r = RExec @('--', $pwsh, '-NoProfile', '-Command',
  263. "try { `$c = New-Object Net.Sockets.TcpClient; `$c.Connect('127.0.0.2', 49998); Write-Output CONNECTED } " +
  264. "catch { Write-Output ('code=' + `$_.Exception.InnerException.SocketErrorCode) }")
  265. if ($r.out -match 'CONNECTED') {
  266. throw "R5e: sandboxed connect to 127.0.0.2 succeeded. raw: $($r.raw)"
  267. }
  268. if ($r.out -notmatch 'AccessDenied') {
  269. throw "R5e: expected AccessDenied (WFP block), got: $($r.raw)"
  270. }
  271. Write-Host 'R5e ok: loopback alias 127.0.0.2 blocked by the fence'
  272. # ── R5f: non-interactive logon types refused for the sandbox account ─
  273. # The SMB redirector dials from kernel mode as SYSTEM, so the
  274. # SID-keyed WFP fence never sees its connects; the fix denies the
  275. # sandbox group every logon type except interactive. LOOPBACK SMB is
  276. # exempt by NTLM loopback-session reuse (no new logon occurs), so the
  277. # CI-provable check is LogonUser itself: type NETWORK/BATCH/SERVICE
  278. # must refuse with 1385 (what any remote server's LSA runs at SMB
  279. # session setup), INTERACTIVE must stay granted (the
  280. # CreateProcessWithLogonW launch depends on it).
  281. $pwPlain = (& $Exe user read-cred).Trim()
  282. if ($LASTEXITCODE -ne 0 -or -not $pwPlain) { throw 'R5f: read-cred failed' }
  283. $lsig = '[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool LogonUserW(string u, string d, string p, uint type, uint prov, out IntPtr tok);'
  284. $lt = Add-Type -MemberDefinition $lsig -Name R5fLogon -Namespace Srt -PassThru
  285. $sbUser = ((& $Exe user status | ConvertFrom-Json).user.name)
  286. foreach ($probe in @(@{n='NETWORK'; t=3; want=$false}, @{n='BATCH'; t=4; want=$false}, @{n='SERVICE'; t=5; want=$false}, @{n='INTERACTIVE'; t=2; want=$true})) {
  287. $tok = [IntPtr]::Zero
  288. $ok = [Srt.R5fLogon]::LogonUserW($sbUser, '.', $pwPlain, [uint32]$probe.t, 0, [ref]$tok)
  289. $gle = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
  290. if ($probe.want -and -not $ok) { throw "R5f: $($probe.n) logon REFUSED (gle=$gle) - launch path broken" }
  291. if (-not $probe.want -and $ok) { throw "R5f: $($probe.n) logon GRANTED - logon-type denial not in effect" }
  292. if (-not $probe.want -and $gle -ne 1385) { Write-Host "R5f note: $($probe.n) refused with gle=$gle (expected 1385; still refused)" }
  293. }
  294. $pwPlain = $null
  295. Write-Host 'R5f ok: network/batch/service logons refused (1385), interactive granted'
  296. # ── R6: child cannot read the credential key (sandbox DENY) ──────
  297. # The Cred subkey's DACL is the load-bearing gate: machine-scope
  298. # DPAPI means readable = decryptable, and a child that learned its
  299. # own password could CreateProcessWithLogonW itself a fresh logon
  300. # session outside the job/desktop confinement.
  301. $r = RExec @('--', $cmd, '/c', 'reg query HKLM\SOFTWARE\sandbox-runtime\Cred /v Blob')
  302. if ($r.exit -eq 0) {
  303. throw "R6: child READ the Cred registry key (DENY not in effect?). raw: $($r.raw)"
  304. }
  305. if ($r.raw -notmatch '(?i)access is denied|denied') {
  306. throw "R6: expected Access is denied. raw: $($r.raw)"
  307. }
  308. Write-Host 'R6 ok: child cannot read the Cred registry key'
  309. # ── R7: cmd.exe /c passthrough — user-quoted payload survives ───
  310. # build_cmdline wraps the post-/c content in ONE outer "…" pair
  311. # for /s to strip; inner content is verbatim. The `&` is inside
  312. # the user's own "…" so cmd treats it literally.
  313. $r = RExec @('--', $cmd, '/d', '/s', '/c', 'echo "x & y"')
  314. if ($r.exit -ne 0) { throw "R7 exited $($r.exit): $($r.out)" }
  315. $got = $r.out.Trim()
  316. if ($got -ne '"x & y"') {
  317. throw "R7: expected literal '`"x & y`"', got '$got'"
  318. }
  319. Write-Host 'R7 ok: user-quoted payload passes through verbatim'
  320. # ── R7b: cmd metachar passthrough — `&` works as separator ──────
  321. $r = RExec @('--', $cmd, '/d', '/s', '/c', 'echo MARKER & exit 5')
  322. if ($r.exit -ne 5) {
  323. throw "R7b: expected exit 5 from chained command, got $($r.exit). " +
  324. "out: $($r.out)"
  325. }
  326. if ($r.out.Trim() -notlike 'MARKER*') {
  327. throw "R7b: expected MARKER in output. out: $($r.out)"
  328. }
  329. Write-Host 'R7b ok: & chains commands inside sandboxed cmd (passthrough)'
  330. # ── R7c: target_is_cmd recognises trailing-dot cmd.exe. ──────────
  331. $r = RExec @('--', "$cmd.", '/d', '/s', '/c', 'echo MARKER & exit 5')
  332. if ($r.exit -ne 5 -or $r.out.Trim() -notlike 'MARKER*') {
  333. throw "R7c: trailing-dot cmd.exe. did NOT take the cmd-quoting " +
  334. "branch (target_is_cmd trim missing). exit=$($r.exit) " +
  335. "out: $($r.out)"
  336. }
  337. Write-Host 'R7c ok: target_is_cmd recognises trailing-dot cmd.exe.'
  338. # ── R9: child cannot OpenProcess(PROCESS_CREATE_PROCESS) on a ────
  339. # real-user process (cross-user boundary)
  340. # ── R9b: child cannot OpenProcess(PROCESS_CREATE_PROCESS) on the ─
  341. # RUNNER (runner self-protect — would let the child
  342. # PROC_THREAD_ATTRIBUTE_PARENT_PROCESS-spawn under the
  343. # runner's unrestricted token and escape job/winsta/mitigations)
  344. $hostPid = $PID
  345. $probeR9 = @"
  346. `$sig = '[DllImport("kernel32.dll",SetLastError=true)]public static extern System.IntPtr OpenProcess(uint a,bool b,uint p);'
  347. `$k32 = Add-Type -MemberDefinition `$sig -Name K32R -Namespace W -PassThru
  348. function Probe([string]`$tag, [int]`$targetPid) {
  349. # 0x0080 = PROCESS_CREATE_PROCESS
  350. `$h = `$k32::OpenProcess(0x0080, `$false, `$targetPid)
  351. `$le = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
  352. if (`$h -ne [System.IntPtr]::Zero) { "OPENED:`$tag pid=`$targetPid" }
  353. elseif (`$le -eq 5) { "DENIED:`$tag pid=`$targetPid" }
  354. else { "OTHER:`$tag pid=`$targetPid le=`$le" }
  355. }
  356. `$rp = 0
  357. `$cur = `$PID
  358. for (`$i = 0; `$i -lt 8; `$i++) {
  359. `$p = Get-CimInstance Win32_Process -Filter "ProcessId=`$cur" -ea SilentlyContinue
  360. if (-not `$p) { break }
  361. if (`$p.Name -eq 'srt-win.exe') { `$rp = [int]`$p.ProcessId; break }
  362. if (-not `$p.ParentProcessId) { break }
  363. `$cur = `$p.ParentProcessId
  364. }
  365. Probe 'real-user' $hostPid
  366. if (`$rp -eq 0) { 'NORUNNER' } else { Probe 'runner' `$rp }
  367. "@
  368. $r = RExec @('--', $pwsh, '-NoProfile', '-Command', $probeR9)
  369. Write-Host "R9 probe output: $($r.out.Trim())"
  370. if ($r.out -match 'OPENED:real-user') {
  371. throw "R9: child got PROCESS_CREATE_PROCESS on a real-user " +
  372. "process (cross-user boundary breached). raw: $($r.raw)"
  373. }
  374. if ($r.out -notmatch 'DENIED:real-user') {
  375. throw "R9: expected ACCESS_DENIED for real-user target. raw: $($r.raw)"
  376. }
  377. Write-Host 'R9 ok: child denied PROCESS_CREATE_PROCESS on real-user process'
  378. if ($r.out -match 'NORUNNER') {
  379. throw "R9b: runner discovery failed. raw: $($r.raw)"
  380. }
  381. if ($r.out -match 'OPENED:runner') {
  382. throw "R9b: child got PROCESS_CREATE_PROCESS on the runner " +
  383. "(runner self-protect ineffective — sandbox escape). raw: $($r.raw)"
  384. }
  385. if ($r.out -notmatch 'DENIED:runner') {
  386. throw "R9b: expected ACCESS_DENIED for runner target. raw: $($r.raw)"
  387. }
  388. Write-Host 'R9b ok: child denied PROCESS_CREATE_PROCESS on the runner (self-protect holds)'
  389. # ── R11: child cannot OpenProcess(PROCESS_VM_READ) on a default-DACL ──
  390. # real-user process (logon-SID strip).
  391. # seclogon stamps the broker's interactive logon SID into the
  392. # runner's token; CreateRestrictedToken disables it so the child
  393. # does NOT match the default per-process logon-session ACE
  394. # (VM_READ|QUERY|TERMINATE) on same-session real-user processes.
  395. # Without the strip the child can ReadProcessMemory the broker's
  396. # browser/shell/host orchestrator. Spawn a fresh victim under the
  397. # broker user so the target is unambiguously default-DACL (no
  398. # harness side effects on its SD).
  399. $victim = Start-Process -FilePath $cmd -ArgumentList '/c','timeout /t 60 >nul' `
  400. -PassThru -WindowStyle Hidden
  401. try {
  402. $probeR11 = @"
  403. `$sig = '[DllImport("kernel32.dll",SetLastError=true)]public static extern System.IntPtr OpenProcess(uint a,bool b,uint p);'
  404. `$k32 = Add-Type -MemberDefinition `$sig -Name K32V -Namespace W -PassThru
  405. function Probe([string]`$tag, [uint32]`$mask) {
  406. `$h = `$k32::OpenProcess(`$mask, `$false, $($victim.Id))
  407. `$le = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
  408. if (`$h -ne [System.IntPtr]::Zero) { "OPENED:`$tag" }
  409. elseif (`$le -eq 5) { "DENIED:`$tag" }
  410. else { "OTHER:`$tag le=`$le" }
  411. }
  412. # 0x0010 = PROCESS_VM_READ; 0x1000 = PROCESS_QUERY_LIMITED_INFORMATION
  413. Probe 'vm-read' 0x0010
  414. Probe 'query-li' 0x1000
  415. "@
  416. $r = RExec @('--', $pwsh, '-NoProfile', '-Command', $probeR11)
  417. Write-Host "R11 probe output: $($r.out.Trim())"
  418. if ($r.out -match 'OPENED:vm-read') {
  419. throw "R11: child got PROCESS_VM_READ on a default-DACL " +
  420. "real-user process (logon-SID not stripped — child " +
  421. "can ReadProcessMemory the broker's session). raw: $($r.raw)"
  422. }
  423. if ($r.out -notmatch 'DENIED:vm-read') {
  424. throw "R11: expected ACCESS_DENIED for VM_READ. raw: $($r.raw)"
  425. }
  426. if ($r.out -match 'OPENED:query-li') {
  427. throw "R11: child got PROCESS_QUERY_LIMITED_INFORMATION on a " +
  428. "default-DACL real-user process. raw: $($r.raw)"
  429. }
  430. if ($r.out -notmatch 'DENIED:query-li') {
  431. throw "R11: expected ACCESS_DENIED for QUERY_LIMITED. raw: $($r.raw)"
  432. }
  433. Write-Host ('R11 ok: child denied VM_READ + QUERY_LIMITED on ' +
  434. 'default-DACL real-user process (logon-SID stripped)')
  435. } finally {
  436. try { $victim.Kill() } catch { }
  437. }
  438. # ── R12: child is on the broker-created srt-sb-* desktop ─────────
  439. # The broker creates `WinSta0\srt-sb-<pid>-<rand>` and passes it via
  440. # CreateProcessWithLogonW's lpDesktop; the runner attaches there and
  441. # the lockdown child inherits. If the child reports `Default`, the
  442. # fail-closed assertion in run_lockdown was bypassed and the child
  443. # can WH_KEYBOARD_LL-hook the interactive desktop (the Job's UI
  444. # limits do NOT gate low-level hooks). The child's own
  445. # GetThreadDesktop name is the substantive check (the runner's
  446. # `caller_desk=` debug line is gated on SANDBOX_RUNTIME_WIN_DEBUG
  447. # in the RUNNER's env, which isn't in the --env overlay).
  448. $probeR12 = @"
  449. `$sig = @'
  450. [DllImport("user32.dll")]public static extern System.IntPtr GetThreadDesktop(uint t);
  451. [DllImport("kernel32.dll")]public static extern uint GetCurrentThreadId();
  452. [DllImport("user32.dll",CharSet=CharSet.Unicode)]public static extern bool GetUserObjectInformationW(System.IntPtr h,int i,System.Text.StringBuilder b,uint n,out uint r);
  453. '@
  454. `$u = Add-Type -MemberDefinition `$sig -Name U32D -Namespace W -PassThru
  455. `$d = `$u::GetThreadDesktop(`$u::GetCurrentThreadId())
  456. `$sb = [System.Text.StringBuilder]::new(256); `$r = 0
  457. [void]`$u::GetUserObjectInformationW(`$d, 2, `$sb, 512, [ref]`$r)
  458. "CHILD_DESK=" + `$sb.ToString()
  459. "@
  460. $r = RExec @('--', $pwsh, '-NoProfile', '-Command', $probeR12)
  461. Write-Host "R12 probe output: $($r.out.Trim())"
  462. if ($r.out -notmatch 'CHILD_DESK=srt-sb-') {
  463. throw "R12: child not on srt-sb-* desktop — desktop isolation " +
  464. "broken (WH_KEYBOARD_LL keylogging risk). raw: $($r.raw)"
  465. }
  466. if ($r.out -match 'CHILD_DESK=Default') {
  467. throw "R12: child on Default desktop. raw: $($r.raw)"
  468. }
  469. Write-Host 'R12 ok: child on broker-created srt-sb-* desktop (not Default)'
  470. # ── G-rows: per-session FS access for the sandbox user ──────────
  471. # The sandbox child has NO inherent rights on real-user-owned
  472. # files. `acl grant` adds an inheritable MODIFY_NO_FDC ALLOW ACE
  473. # for <sb-SID> on the working-tree root; `acl stamp
  474. # --sandbox-user-sid <sb>` adds an additive (D;OICI;mask;;;<sb>)
  475. # DENY ACE on a path inside it (plus a parent-FDC DENY). The
  476. # G-rows are the design probe: with grant on the root + DENY on a
  477. # file inside, the child reads siblings but not the denied file
  478. # AND cannot del/ren it (the grant lacks FDC and the parent
  479. # carries an explicit FDC DENY for <sb-SID>).
  480. $gRoot = Join-Path $env:TEMP "srt-gscratch-$([guid]::NewGuid().ToString('N'))"
  481. New-Item -ItemType Directory -Path $gRoot -Force | Out-Null
  482. # Expand to the long-form path: $env:TEMP on the GHA runner is
  483. # `C:\Users\RUNNER~1\...` (8.3 short name). The grant lands on the
  484. # canonical (long-form) file object regardless, but the CHILD opens
  485. # by the path we pass it — and resolving an 8.3 component requires
  486. # enumerating the parent dir, which srt-sandbox cannot do for the
  487. # real user's profile. Passing the long form lets bypass-traverse
  488. # (SeChangeNotifyPrivilege) reach the file directly without an
  489. # enumerate step.
  490. $k32 = Add-Type -PassThru -Namespace W -Name K -MemberDefinition `
  491. '[DllImport("kernel32.dll",CharSet=CharSet.Unicode)] public static extern uint GetLongPathName(string s,System.Text.StringBuilder l,uint n);'
  492. $lp = [System.Text.StringBuilder]::new(1024)
  493. if ($k32::GetLongPathName($gRoot, $lp, 1024) -gt 0) { $gRoot = $lp.ToString() }
  494. $gSub = Join-Path $gRoot 'sub'
  495. New-Item -ItemType Directory -Path $gSub -Force | Out-Null
  496. $secret = Join-Path $gSub 'secret.txt'
  497. $sibling = Join-Path $gSub 'sibling.txt'
  498. $subDeny = Join-Path $gRoot 'sub-deny'
  499. New-Item -ItemType Directory -Path $subDeny | Out-Null
  500. $inDeny = Join-Path $subDeny 'inner.txt'
  501. $inAllow = Join-Path $subDeny 'reallow.txt'
  502. # NOT -NoNewline: RExec concatenates child stdout + broker stderr
  503. # before line-splitting, so a no-newline file body would fuse with
  504. # the first `srt-win:` diag line and survive the `^srt-win:` filter.
  505. 'SECRET' | Set-Content -Encoding ASCII $secret
  506. 'SIBLING' | Set-Content -Encoding ASCII $sibling
  507. 'INNER' | Set-Content -Encoding ASCII $inDeny
  508. 'REALLOW' | Set-Content -Encoding ASCII $inAllow
  509. Write-Host "G: scratch=$gRoot sbSid=$sbSid"
  510. function Stdin { param([string[]] $argv, [string] $json)
  511. $raw = $json | & $Exe @argv 2>&1 | Out-String
  512. Write-Host -NoNewline $raw
  513. if ($LASTEXITCODE -ne 0) {
  514. throw "srt-win $($argv -join ' ') exited ${LASTEXITCODE}: $raw"
  515. }
  516. }
  517. try {
  518. # ── G1: working-tree grant — child can list/read/write inside ────
  519. Stdin @('acl','grant','--holder-pid',$PID,
  520. '--sandbox-user-sid',$sbSid) `
  521. "{`"write`":[`"$($gRoot -replace '\\','\\')`"]}"
  522. $r = RExec @('--', $cmd, '/c', "type `"$sibling`"")
  523. if ($r.exit -ne 0 -or $r.out -notmatch 'SIBLING') {
  524. throw "G1: child read sibling failed. exit=$($r.exit) raw: $($r.raw)"
  525. }
  526. $r = RExec @('--', $cmd, '/c', "echo G1-NEW> `"$gSub\new.txt`"")
  527. if ($r.exit -ne 0 -or -not (Test-Path "$gSub\new.txt")) {
  528. throw "G1: child write under granted tree failed. raw: $($r.raw)"
  529. }
  530. Write-Host 'G1 ok: working-tree MODIFY_NO_FDC grant — child reads + creates inside'
  531. # ── G2: DENY ACE inside the grant — read denied ──────────────────
  532. Stdin @('acl','stamp','--holder-pid',$PID,
  533. '--sandbox-user-sid',$sbSid) `
  534. "{`"denyRead`":[`"$($secret -replace '\\','\\')`"]}"
  535. $r = RExec @('--', $cmd, '/c', "type `"$secret`"")
  536. if ($r.exit -eq 0 -or $r.out -match 'SECRET') {
  537. throw "G2: child READ the stamped file. raw: $($r.raw)"
  538. }
  539. $r = RExec @('--', $cmd, '/c', "type `"$sibling`"")
  540. if ($r.out -notmatch 'SIBLING') {
  541. throw "G2: sibling no longer readable post-stamp. raw: $($r.raw)"
  542. }
  543. Write-Host 'G2 ok: DENY ACE + working-tree grant compose — sibling readable, stamped file denied'
  544. # ── G3: parent-FDC DENY — child cannot del/ren the stamped file ──
  545. # The stamp adds (D;OICI;FILE_DELETE_CHILD;;;<sb-SID>) on the
  546. # parent; explicit DENY is evaluated first, so even where the
  547. # parent inherits an allow-FDC the child has no path through it.
  548. $r = RExec @('--', $cmd, '/c', "del `"$secret`"")
  549. if (-not (Test-Path $secret) -or
  550. (Get-Content -Raw $secret).Trim() -ne 'SECRET') {
  551. throw "G3: child deleted/altered the stamped file (parent-FDC DENY did not take). raw: $($r.raw)"
  552. }
  553. $r = RExec @('--', $cmd, '/c', "ren `"$secret`" gone.txt")
  554. if (-not (Test-Path $secret) -or (Test-Path "$gSub\gone.txt")) {
  555. throw "G3: child renamed the stamped file. raw: $($r.raw)"
  556. }
  557. Write-Host 'G3 ok: parent-FDC DENY ACE — child cannot del/ren the stamped file'
  558. # ── G3b: parent-FDC DENY overrides BUILTIN\Users:FA on parent ────
  559. # The sandbox user is a Users member; without the explicit DENY a
  560. # parent with Users:(F) would give it FILE_DELETE_CHILD directly
  561. # (the C:\ProgramData case). The DENY ACE is evaluated before
  562. # any ALLOW, so the deny still holds.
  563. $g3bDir = Join-Path $gRoot 'g3b'
  564. New-Item -ItemType Directory -Path $g3bDir | Out-Null
  565. & icacls $g3bDir /grant '*S-1-5-32-545:(OI)(CI)(F)' | Out-Null
  566. $g3bFile = Join-Path $g3bDir 'sec.txt'
  567. 'G3B' | Set-Content -Encoding ASCII $g3bFile
  568. Stdin @('acl','stamp','--holder-pid',$PID,
  569. '--sandbox-user-sid',$sbSid) `
  570. "{`"denyRead`":[`"$($g3bFile -replace '\\','\\')`"]}"
  571. $r = RExec @('--', $cmd, '/c', "del `"$g3bFile`"")
  572. if (-not (Test-Path $g3bFile) -or
  573. (Get-Content -Raw $g3bFile).Trim() -ne 'G3B') {
  574. throw "G3b: child deleted file under Users:FA parent (DENY did not override). raw: $($r.raw)"
  575. }
  576. $r = RExec @('--', $cmd, '/c', "type `"$g3bFile`"")
  577. if ($r.exit -eq 0 -or $r.out -match 'G3B') {
  578. throw "G3b: child READ file under Users:FA parent. raw: $($r.raw)"
  579. }
  580. Write-Host 'G3b ok: parent-FDC DENY overrides inherited BUILTIN\Users:(F) on parent'
  581. # ── G4: broker (real user) can still read the stamped file ───────
  582. if ((Get-Content -Raw $secret).Trim() -ne 'SECRET') {
  583. throw 'G4: broker lost read on the stamped file'
  584. }
  585. Write-Host 'G4 ok: real-user trustee keeps full access to stamped file'
  586. # ── G5: directory deny — (OI)(CI) DENY ACE covers the subtree; ───
  587. # allowWithinDeny via grant on an inner file.
  588. Stdin @('acl','stamp','--holder-pid',$PID,
  589. '--sandbox-user-sid',$sbSid) `
  590. "{`"denyRead`":[`"$($subDeny -replace '\\','\\')`"]}"
  591. Stdin @('acl','grant','--holder-pid',$PID,
  592. '--sandbox-user-sid',$sbSid) `
  593. "{`"read`":[`"$($inAllow -replace '\\','\\')`"]}"
  594. # Instrumentation: dump exactly what landed on the inner file
  595. # post dir-stamp + inner-grant. The icacls/SDDL pair shows the
  596. # explicit srt-sandbox ALLOW ACE alongside the inherited DENY
  597. # ACE; the child-side `if exist` tells us whether
  598. # bypass-traverse through the denied dir works. Kept on the
  599. # success path too — the dump is the proof for the design claim
  600. # (explicit ALLOW is evaluated before inherited DENY).
  601. Write-Host "G5 diag: icacls $inAllow ->"
  602. & icacls $inAllow
  603. Write-Host "G5 diag: inAllow Sddl=$((Get-Acl $inAllow).Sddl)"
  604. Write-Host "G5 diag: subDeny Sddl=$((Get-Acl $subDeny).Sddl)"
  605. $r = RExec @('--', $cmd, '/c',
  606. "whoami /priv | findstr /i SeChangeNotify")
  607. Write-Host "G5 diag: child SeChangeNotify=$($r.out)"
  608. $r = RExec @('--', $cmd, '/c', "type `"$inDeny`"")
  609. if ($r.exit -eq 0 -or $r.out -match 'INNER') {
  610. throw "G5: child read file under denied dir. raw: $($r.raw)"
  611. }
  612. # Combined probe: echo the path the child sees + if-exist +
  613. # type-via-builtin + read-via-stdin-redirect (cmd's `<` is a
  614. # direct CreateFileW(GENERIC_READ) — bypasses any extra path
  615. # checks `type` might do). Everything goes through one RExec so
  616. # the throw carries it all.
  617. $r = RExec @('--', $cmd, '/c',
  618. ("echo PATH=$inAllow & " +
  619. "if exist `"$inAllow`" (echo IFEXIST=YES) else (echo IFEXIST=NO) & " +
  620. "type `"$inAllow`" 2>&1 & echo --- & " +
  621. "more < `"$inAllow`" 2>&1"))
  622. if ($r.out -notmatch 'REALLOW') {
  623. throw ("G5: allowWithinDeny grant on inner file did not take " +
  624. "effect.`n child raw: $($r.raw)`n " +
  625. "inAllow Sddl: $((Get-Acl $inAllow).Sddl)`n " +
  626. "subDeny Sddl: $((Get-Acl $subDeny).Sddl)")
  627. }
  628. $r = RExec @('--', $cmd, '/c', "type `"$sibling`"")
  629. if ($r.out -notmatch 'SIBLING') {
  630. throw "G5: sibling-of-denied-dir lost access. raw: $($r.raw)"
  631. }
  632. Write-Host 'G5 ok: dir-deny (OI)(CI) covers subtree; sibling unaffected; inner grant overrides'
  633. # ── G6: revoke + restore — child loses access; DACLs round-trip ──
  634. Run @('acl','revoke','--holder-pid',$PID,
  635. '--sandbox-user-sid',$sbSid)
  636. Run @('acl','restore','--holder-pid',$PID,
  637. '--sandbox-user-sid',$sbSid)
  638. $post = (Get-Acl $gRoot).Sddl
  639. if ($post -match [regex]::Escape($sbSid)) {
  640. throw "G6: srt-sandbox ACE still present on root after revoke: $post"
  641. }
  642. $postSub = (Get-Acl $subDeny).Sddl
  643. if ($postSub -match [regex]::Escape($sbSid)) {
  644. throw "G6: srt-sandbox ACE still on dir after restore: $postSub"
  645. }
  646. $r = RExec @('--', $cmd, '/c', "type `"$sibling`"")
  647. if ($r.exit -eq 0) {
  648. throw "G6: child still reads after revoke. raw: $($r.raw)"
  649. }
  650. Write-Host 'G6 ok: revoke + restore remove all sb-user ACEs; child loses access'
  651. } finally {
  652. # Best-effort: don't leak ACEs/stamps if a G-row threw mid-way.
  653. & $Exe acl revoke --holder-pid $PID `
  654. --sandbox-user-sid $sbSid 2>&1 | Out-Null
  655. & $Exe acl restore --holder-pid $PID `
  656. --sandbox-user-sid $sbSid 2>&1 | Out-Null
  657. Remove-Item -Recurse -Force $gRoot -ErrorAction SilentlyContinue
  658. }
  659. # ── teardown ─────────────────────────────────────────────────────
  660. Run @('uninstall','--sublayer-guid',$Sublayer)
  661. $post = J @('wfp','status','--sublayer-guid',$Sublayer)
  662. if ($post.state -ne 'absent') {
  663. throw "post-uninstall expected absent, got $($post.state)"
  664. }
  665. Write-Host 'smoke-exec: PASS (R0b, V1, R1-R7c, R9/R9b, R11, R12, G1-G6/G3b)'