workpen 0.8.0

Workpen dest-deny and a per-child process jail (Landlock, Seatbelt, Windows).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
//! Write-restricted token spawn. Not a dest-parent-copy of Bline.

use std::ffi::{OsStr, OsString};
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::os::windows::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::ptr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;

use super::{KernelAccess, KernelApply, KernelError, KernelPolicy, combine_spawn_restore};

#[path = "windows_net.rs"]
mod windows_net;

type Handle = *mut core::ffi::c_void;
type Dword = u32;
type Bool = i32;

const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
const DISABLE_MAX_PRIVILEGE: Dword = 0x1;
const WRITE_RESTRICTED: Dword = 0x8;
const TOKEN_ASSIGN_PRIMARY: Dword = 0x0001;
const TOKEN_DUPLICATE: Dword = 0x0002;
const TOKEN_QUERY: Dword = 0x0008;
const TOKEN_ADJUST_DEFAULT: Dword = 0x0080;
const TOKEN_ADJUST_SESSIONID: Dword = 0x0100;
const TOKEN_PRIMARY_MASK: Dword = TOKEN_ASSIGN_PRIMARY
    | TOKEN_DUPLICATE
    | TOKEN_QUERY
    | TOKEN_ADJUST_DEFAULT
    | TOKEN_ADJUST_SESSIONID;
const SECURITY_NT_AUTHORITY: [u8; 6] = [0, 0, 0, 0, 0, 5];
const SECURITY_WORLD_SID_AUTHORITY: [u8; 6] = [0, 0, 0, 0, 0, 1];
const SECURITY_RESTRICTED_CODE_RID: Dword = 12;
const SECURITY_WORLD_RID: Dword = 0;
const GENERIC_ALL: Dword = 0x1000_0000;
const GRANT_ACCESS: u32 = 1;
const DENY_ACCESS: u32 = 3;
const NO_INHERITANCE: Dword = 0;
const TRUSTEE_IS_SID: u32 = 0;
const TRUSTEE_IS_WELL_KNOWN_GROUP: u32 = 5;
const NO_MULTIPLE_TRUSTEE: u32 = 0;
const SUB_CONTAINERS_AND_OBJECTS_INHERIT: Dword = 0x3;
const SE_FILE_OBJECT: u32 = 1;
const DACL_SECURITY_INFORMATION: Dword = 0x4;
const CREATE_SUSPENDED: Dword = 0x0000_0004;
const CREATE_UNICODE_ENVIRONMENT: Dword = 0x0000_0400;
const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: Dword = 0x2000;
const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: u32 = 9;
const JOB_OBJECT_BASIC_UI_RESTRICTIONS: u32 = 4;
const JOB_OBJECT_UILIMIT_HANDLES: Dword = 0x0000_0001;
const JOB_OBJECT_UILIMIT_READCLIPBOARD: Dword = 0x0000_0002;
const JOB_OBJECT_UILIMIT_WRITECLIPBOARD: Dword = 0x0000_0004;
const JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: Dword = 0x0000_0008;
const JOB_OBJECT_UILIMIT_EXITWINDOWS: Dword = 0x0000_0080;
/// Clipboard, system parameters, and ExitWindows. Not HANDLES:
/// that flag blocks USER handles owned outside the job, and MSYS
/// `DllMain` then exits `0xC0000142`.
const UI_RESTRICTIONS: Dword = JOB_OBJECT_UILIMIT_READCLIPBOARD
    | JOB_OBJECT_UILIMIT_WRITECLIPBOARD
    | JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS
    | JOB_OBJECT_UILIMIT_EXITWINDOWS;
const _: () = assert!(UI_RESTRICTIONS & JOB_OBJECT_UILIMIT_HANDLES == 0);
const SE_KERNEL_OBJECT: u32 = 6;
/// `DIRECTORY_QUERY | DIRECTORY_TRAVERSE | DIRECTORY_CREATE_OBJECT | DIRECTORY_CREATE_SUBDIRECTORY | READ_CONTROL`.
/// MSYS requests this mask for its shared directory (`CYG_SHARED_DIR_ACCESS`).
const MSYS_DIR_ACCESS: Dword = 0x0002_000F;
const DIRECTORY_ALL_ACCESS: Dword = 0x000F_000F;
/// `SECTION_ALL_ACCESS`.
const SECTION_ALL_ACCESS: Dword = 0x000F_001F;
/// MSYS mask plus WRITE_DAC, so the parent can edit the leaf it creates
/// without also granting DELETE to Everyone.
const MSYS_DIR_WRITE_DAC: Dword = MSYS_DIR_ACCESS | 0x0004_0000;
/// `SECTION_ALL_ACCESS`. MSYS `NtCreateSection` requests
/// `STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE`
/// (`0x000F0007`), which is a subset. The per-user section inherits this
/// mask from the MSYS directory because `sec_none` passes a null descriptor.
const MSYS_SECTION_ACCESS: Dword = 0x000F_001F;
const MSYS_INHERIT_ACCESS: Dword = MSYS_DIR_ACCESS | MSYS_SECTION_ACCESS;
/// `FILE_ALL_ACCESS`. Named-pipe create needs `FILE_CREATE_PIPE_INSTANCE`.
const FILE_ALL_ACCESS: Dword = 0x001F_01FF;
const FILE_SHARE_DELETE: Dword = 0x4;
const FILE_DIRECTORY_FILE: u32 = 0x1;
/// Not a Windows `SE_OBJECT_TYPE`. Restore reopens `\Device\NamedPipe`.
const NPFS_RESTORE: u32 = 0x4E50_4653;
const OBJ_CASE_INSENSITIVE: u32 = 0x40;
const OBJ_OPENIF: u32 = 0x80;
const OBJECT_INHERIT_ACE: Dword = 0x1;
const CONTAINER_INHERIT_ACE: Dword = 0x2;
const STATUS_OBJECT_NAME_NOT_FOUND: i32 = 0xC000_0034_u32 as i32;
const STATUS_OBJECT_PATH_NOT_FOUND: i32 = 0xC000_003A_u32 as i32;
const STATUS_ACCESS_DENIED: i32 = 0xC000_0022_u32 as i32;
const WRITE_OWNER: u32 = 0x0008_0000;
const OWNER_SECURITY_INFORMATION: Dword = 0x1;
const TOKEN_ADJUST_PRIVILEGES: Dword = 0x0020;
const TOKEN_USER: u32 = 1;
const SE_PRIVILEGE_ENABLED: Dword = 0x0000_0002;
const TOKEN_DEFAULT_DACL: u32 = 6;
const TOKEN_PRIMARY: u32 = 1;
const SECURITY_IMPERSONATION: u32 = 2;
const INFINITE: Dword = 0xFFFF_FFFF;
const WAIT_OBJECT_0: Dword = 0;
const WAIT_TIMEOUT: Dword = 0x0000_0102;
const WAIT_FAILED: Dword = 0xFFFF_FFFF;
const STD_INPUT_HANDLE: Dword = -10i32 as Dword;
const STD_OUTPUT_HANDLE: Dword = -11i32 as Dword;
const STD_ERROR_HANDLE: Dword = -12i32 as Dword;
const STARTF_USESTDHANDLES: Dword = 0x0000_0100;
const DUPLICATE_SAME_ACCESS: Dword = 0x0000_0002;
const GENERIC_READ: Dword = 0x8000_0000;
const GENERIC_WRITE: Dword = 0x4000_0000;
const GENERIC_EXECUTE: Dword = 0x2000_0000;
const FILE_SHARE_READ: Dword = 0x0001;
const FILE_SHARE_WRITE: Dword = 0x0002;
const OPEN_EXISTING: Dword = 3;

#[repr(C)]
struct SidIdentifierAuthority {
    value: [u8; 6],
}

#[repr(C)]
struct SidAndAttributes {
    sid: Handle,
    attributes: Dword,
}

#[repr(C)]
struct Luid {
    low_part: Dword,
    high_part: i32,
}

#[repr(C)]
struct LuidAndAttributes {
    luid: Luid,
    attributes: Dword,
}

#[repr(C)]
struct TokenPrivileges {
    count: Dword,
    attr: LuidAndAttributes,
}

#[derive(Clone, Copy)]
#[repr(C)]
struct TrusteeW {
    p_multiple_trustee: *mut TrusteeW,
    multiple_trustee_operation: u32,
    trustee_form: u32,
    trustee_type: u32,
    ptstr_name: Handle,
}

#[repr(C)]
struct ExplicitAccessW {
    grf_access_permissions: Dword,
    grf_access_mode: u32,
    grf_inheritance: Dword,
    trustee: TrusteeW,
}

#[repr(C)]
struct StartupInfoW {
    cb: Dword,
    lp_reserved: *mut u16,
    lp_desktop: *mut u16,
    lp_title: *mut u16,
    dw_x: Dword,
    dw_y: Dword,
    dw_x_size: Dword,
    dw_y_size: Dword,
    dw_x_count_chars: Dword,
    dw_y_count_chars: Dword,
    dw_fill_attribute: Dword,
    dw_flags: Dword,
    w_show_window: u16,
    cb_reserved2: u16,
    lp_reserved2: *mut u8,
    h_std_input: Handle,
    h_std_output: Handle,
    h_std_error: Handle,
}

#[repr(C)]
struct ProcessInformation {
    h_process: Handle,
    h_thread: Handle,
    dw_process_id: Dword,
    dw_thread_id: Dword,
}

#[repr(C)]
struct SecurityAttributes {
    n_length: Dword,
    lp_security_descriptor: *mut core::ffi::c_void,
    b_inherit_handle: Bool,
}

#[repr(C)]
struct JobobjectBasicLimitInformation {
    per_process_user_time_limit: i64,
    per_job_user_time_limit: i64,
    limit_flags: Dword,
    minimum_working_set_size: usize,
    maximum_working_set_size: usize,
    active_process_limit: Dword,
    affinity: usize,
    priority_class: Dword,
    scheduling_class: Dword,
}

#[repr(C)]
struct IoCounters {
    read_operation_count: u64,
    write_operation_count: u64,
    other_operation_count: u64,
    read_transfer_count: u64,
    write_transfer_count: u64,
    other_transfer_count: u64,
}

#[repr(C)]
struct JobobjectExtendedLimitInformation {
    basic_limit_information: JobobjectBasicLimitInformation,
    io_info: IoCounters,
    process_memory_limit: usize,
    job_memory_limit: usize,
    peak_process_memory_used: usize,
    peak_job_memory_used: usize,
}

#[repr(C)]
struct JobobjectBasicUiRestrictions {
    ui_restrictions_class: Dword,
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn GetCurrentProcess() -> Handle;
    fn GetCurrentProcessId() -> u32;
    fn ProcessIdToSessionId(process_id: u32, session_id: *mut u32) -> i32;
    fn GetCurrentThread() -> Handle;
    fn CancelSynchronousIo(h_thread: Handle) -> Bool;
    fn CloseHandle(h_object: Handle) -> Bool;
    fn GetLastError() -> Dword;
    fn SearchPathW(
        lp_path: *const u16,
        lp_file_name: *const u16,
        lp_extension: *const u16,
        n_buffer_length: Dword,
        lp_buffer: *mut u16,
        lp_file_part: *mut *mut u16,
    ) -> Dword;
    fn CreateJobObjectW(lp_job_attributes: *mut core::ffi::c_void, lp_name: *const u16) -> Handle;
    fn SetInformationJobObject(
        h_job: Handle,
        job_object_information_class: u32,
        lp_job_object_information: *mut core::ffi::c_void,
        cb_job_object_information_length: Dword,
    ) -> Bool;
    fn AssignProcessToJobObject(h_job: Handle, h_process: Handle) -> Bool;
    fn ResumeThread(h_thread: Handle) -> Dword;
    fn WaitForSingleObject(h_handle: Handle, dw_milliseconds: Dword) -> Dword;
    fn GetExitCodeProcess(h_process: Handle, lp_exit_code: *mut Dword) -> Bool;
    fn TerminateProcess(h_process: Handle, u_exit_code: u32) -> Bool;
    fn GetStdHandle(n_std_handle: Dword) -> Handle;
    fn DuplicateHandle(
        h_source_process_handle: Handle,
        h_source_handle: Handle,
        h_target_process_handle: Handle,
        lp_target_handle: *mut Handle,
        dw_desired_access: Dword,
        b_inherit_handle: Bool,
        dw_options: Dword,
    ) -> Bool;
    fn CreateFileW(
        lp_file_name: *const u16,
        dw_desired_access: Dword,
        dw_share_mode: Dword,
        lp_security_attributes: *mut core::ffi::c_void,
        dw_creation_disposition: Dword,
        dw_flags_and_attributes: Dword,
        h_template_file: Handle,
    ) -> Handle;
    fn GetModuleHandleW(lp_module_name: *const u16) -> Handle;
    fn GetProcAddress(h_module: Handle, lp_proc_name: *const u8) -> *mut core::ffi::c_void;
    fn CreatePipe(
        h_read_pipe: *mut Handle,
        h_write_pipe: *mut Handle,
        lp_pipe_attributes: *mut SecurityAttributes,
        n_size: Dword,
    ) -> Bool;
    fn ReadProcessMemory(
        h_process: Handle,
        lp_base_address: *const core::ffi::c_void,
        lp_buffer: *mut u8,
        n_size: usize,
        lp_number_of_bytes_read: *mut usize,
    ) -> Bool;
    fn WriteProcessMemory(
        h_process: Handle,
        lp_base_address: *mut core::ffi::c_void,
        lp_buffer: *const u8,
        n_size: usize,
        lp_number_of_bytes_written: *mut usize,
    ) -> Bool;
    fn VirtualAllocEx(
        h_process: Handle,
        lp_address: *mut core::ffi::c_void,
        dw_size: usize,
        fl_allocation_type: Dword,
        fl_protect: Dword,
    ) -> *mut core::ffi::c_void;
    fn VirtualProtectEx(
        h_process: Handle,
        lp_address: *mut core::ffi::c_void,
        dw_size: usize,
        fl_new_protect: Dword,
        lpfl_old_protect: *mut Dword,
    ) -> Bool;
    fn ReadFile(
        h_file: Handle,
        lp_buffer: *mut u8,
        n_number_of_bytes_to_read: Dword,
        lp_number_of_bytes_read: *mut Dword,
        lp_overlapped: *mut core::ffi::c_void,
    ) -> Bool;
    fn WriteFile(
        h_file: Handle,
        lp_buffer: *const u8,
        n_number_of_bytes_to_write: Dword,
        lp_number_of_bytes_written: *mut Dword,
        lp_overlapped: *mut core::ffi::c_void,
    ) -> Bool;
    fn SetHandleInformation(h_object: Handle, dw_mask: Dword, dw_flags: Dword) -> Bool;
    fn GetFinalPathNameByHandleW(
        h_file: Handle,
        lpsz_file_path: *mut u16,
        cch_file_path: Dword,
        dw_flags: Dword,
    ) -> Dword;
    fn LCMapStringW(
        locale: u32,
        flags: Dword,
        src: *const u16,
        src_len: i32,
        dest: *mut u16,
        dest_len: i32,
    ) -> i32;
}

const HANDLE_FLAG_INHERIT: Dword = 0x0000_0001;

#[link(name = "advapi32")]
unsafe extern "system" {
    fn OpenProcessToken(
        process_handle: Handle,
        desired_access: Dword,
        token_handle: *mut Handle,
    ) -> Bool;
    fn CreateRestrictedToken(
        existing_token_handle: Handle,
        flags: Dword,
        disable_sid_count: Dword,
        sids_to_disable: *const SidAndAttributes,
        delete_privilege_count: Dword,
        privileges_to_delete: *const core::ffi::c_void,
        restricted_sid_count: Dword,
        sids_to_restrict: *const SidAndAttributes,
        new_token_handle: *mut Handle,
    ) -> Bool;
    fn DuplicateTokenEx(
        h_existing_token: Handle,
        dw_desired_access: Dword,
        lp_token_attributes: *mut core::ffi::c_void,
        impersonation_level: u32,
        token_type: u32,
        ph_new_token: *mut Handle,
    ) -> Bool;
    fn CreateProcessAsUserW(
        h_token: Handle,
        lp_application_name: *const u16,
        lp_command_line: *mut u16,
        lp_process_attributes: *mut core::ffi::c_void,
        lp_thread_attributes: *mut core::ffi::c_void,
        b_inherit_handles: Bool,
        dw_creation_flags: Dword,
        lp_environment: *mut core::ffi::c_void,
        lp_current_directory: *const u16,
        lp_startup_info: *mut StartupInfoW,
        lp_process_information: *mut ProcessInformation,
    ) -> Bool;
    fn AllocateAndInitializeSid(
        p_identifier_authority: *const SidIdentifierAuthority,
        n_sub_authority_count: u8,
        n_sub_authority0: Dword,
        n_sub_authority1: Dword,
        n_sub_authority2: Dword,
        n_sub_authority3: Dword,
        n_sub_authority4: Dword,
        n_sub_authority5: Dword,
        n_sub_authority6: Dword,
        n_sub_authority7: Dword,
        p_sid: *mut Handle,
    ) -> Bool;
    fn FreeSid(p_sid: Handle) -> Handle;
    fn GetNamedSecurityInfoW(
        p_object_name: *const u16,
        object_type: u32,
        security_info: Dword,
        ppsid_owner: *mut Handle,
        ppsid_group: *mut Handle,
        pp_dacl: *mut Handle,
        pp_sacl: *mut Handle,
        pp_security_descriptor: *mut Handle,
    ) -> Dword;
    fn SetNamedSecurityInfoW(
        p_object_name: *mut u16,
        object_type: u32,
        security_info: Dword,
        psid_owner: Handle,
        psid_group: Handle,
        p_dacl: Handle,
        p_sacl: Handle,
    ) -> Dword;
    fn GetSecurityInfo(
        handle: Handle,
        object_type: u32,
        security_info: Dword,
        ppsid_owner: *mut Handle,
        ppsid_group: *mut Handle,
        pp_dacl: *mut Handle,
        pp_sacl: *mut Handle,
        pp_security_descriptor: *mut Handle,
    ) -> Dword;
    fn SetSecurityInfo(
        handle: Handle,
        object_type: u32,
        security_info: Dword,
        psid_owner: Handle,
        psid_group: Handle,
        p_dacl: Handle,
        p_sacl: Handle,
    ) -> Dword;
    fn SetEntriesInAclW(
        c_count_of_explicit_entries: u32,
        p_list_of_explicit_entries: *mut ExplicitAccessW,
        old_acl: Handle,
        new_acl: *mut Handle,
    ) -> Dword;
    fn GetTokenInformation(
        token_handle: Handle,
        token_information_class: u32,
        token_information: *mut core::ffi::c_void,
        token_information_length: Dword,
        return_length: *mut Dword,
    ) -> Bool;
    fn SetTokenInformation(
        token_handle: Handle,
        token_information_class: u32,
        token_information: *mut core::ffi::c_void,
        token_information_length: Dword,
    ) -> Bool;
    fn InitializeSecurityDescriptor(sd: *mut u8, revision: u32) -> Bool;
    fn InitializeAcl(acl: *mut u8, length: Dword, revision: u32) -> Bool;
    fn AddAccessAllowedAce(acl: *mut u8, revision: u32, mask: Dword, sid: Handle) -> Bool;
    fn AddAccessAllowedAceEx(
        acl: *mut u8,
        revision: u32,
        flags: u32,
        mask: Dword,
        sid: Handle,
    ) -> Bool;
    fn AddAccessDeniedAce(acl: *mut u8, revision: u32, mask: Dword, sid: Handle) -> Bool;
    fn GetAce(acl: Handle, index: Dword, ace: *mut Handle) -> Bool;
    fn AddAce(
        acl: *mut u8,
        revision: u32,
        index: Dword,
        ace_list: *const u8,
        ace_list_bytes: Dword,
    ) -> Bool;
    fn EqualSid(a: Handle, b: Handle) -> Bool;
    fn ConvertSidToStringSidW(sid: Handle, string_sid: *mut *mut u16) -> Bool;
    fn SetSecurityDescriptorDacl(
        sd: *mut u8,
        present: Bool,
        dacl: *mut u8,
        defaulted: Bool,
    ) -> Bool;
    fn LookupPrivilegeValueW(
        lp_system_name: *const u16,
        lp_name: *const u16,
        lp_luid: *mut Luid,
    ) -> Bool;
    fn AdjustTokenPrivileges(
        token: Handle,
        disable_all: Bool,
        new_state: *mut TokenPrivileges,
        buffer_length: Dword,
        previous: *mut core::ffi::c_void,
        return_length: *mut Dword,
    ) -> Bool;
    fn GetLengthSid(sid: Handle) -> Dword;
    fn CopySid(len: Dword, dest: *mut u8, src: Handle) -> Bool;
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn LocalFree(h_mem: Handle) -> Handle;
}

struct CloseOnDrop(Handle);
// SAFETY: exclusive kernel HANDLE; drain threads take ownership.
unsafe impl Send for CloseOnDrop {}
impl Drop for CloseOnDrop {
    fn drop(&mut self) {
        if !self.0.is_null() && self.0 != INVALID_HANDLE_VALUE {
            // SAFETY: `self.0` is a kernel handle we own.
            unsafe {
                CloseHandle(self.0);
            }
            self.0 = ptr::null_mut();
        }
    }
}

struct RestrictedSid(Handle);
impl RestrictedSid {
    fn new() -> Result<Self, KernelError> {
        let authority = SidIdentifierAuthority {
            value: SECURITY_NT_AUTHORITY,
        };
        let mut sid = ptr::null_mut();
        // SAFETY: `authority` lives for the call; `sid` is written by the API.
        let ok = unsafe {
            AllocateAndInitializeSid(
                &authority,
                1,
                SECURITY_RESTRICTED_CODE_RID,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                &mut sid,
            )
        };
        if ok == 0 || sid.is_null() {
            return Err(last_error("AllocateAndInitializeSid"));
        }
        Ok(Self(sid))
    }
}
impl Drop for RestrictedSid {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: `self.0` came from AllocateAndInitializeSid.
            unsafe {
                FreeSid(self.0);
            }
            self.0 = ptr::null_mut();
        }
    }
}

struct WorldSid(Handle);
impl WorldSid {
    fn new() -> Result<Self, KernelError> {
        let authority = SidIdentifierAuthority {
            value: SECURITY_WORLD_SID_AUTHORITY,
        };
        let mut sid = ptr::null_mut();
        // SAFETY: `authority` lives for the call; `sid` is written by the API.
        let ok = unsafe {
            AllocateAndInitializeSid(
                &authority,
                1,
                SECURITY_WORLD_RID,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                &mut sid,
            )
        };
        if ok == 0 || sid.is_null() {
            return Err(last_error("AllocateAndInitializeSid"));
        }
        Ok(Self(sid))
    }
}
impl Drop for WorldSid {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: `self.0` came from AllocateAndInitializeSid.
            unsafe {
                FreeSid(self.0);
            }
            self.0 = ptr::null_mut();
        }
    }
}

struct LocalMem(Handle);
impl Drop for LocalMem {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: `self.0` came from LocalAlloc / GetNamedSecurityInfo / SetEntriesInAcl.
            unsafe {
                LocalFree(self.0);
            }
            self.0 = ptr::null_mut();
        }
    }
}

struct AclRestore {
    path: Vec<u16>,
    object_type: u32,
    /// Owns the security descriptor so `dacl` stays valid until restore.
    _sd: LocalMem,
    dacl: Handle,
    restored: bool,
}
impl AclRestore {
    fn restore(&mut self) -> Result<(), KernelError> {
        if self.restored {
            return Ok(());
        }
        let err = if self.object_type == NPFS_RESTORE {
            let Ok(file) = open_nt_file(r"\Device\NamedPipe", 0x0006_0000, FILE_DIRECTORY_FILE)
            else {
                return Err(KernelError::Apply(
                    "restore could not reopen the named pipe device".into(),
                ));
            };
            let err = unsafe {
                SetSecurityInfo(
                    file,
                    SE_FILE_OBJECT,
                    DACL_SECURITY_INFORMATION,
                    ptr::null_mut(),
                    ptr::null_mut(),
                    self.dacl,
                    ptr::null_mut(),
                )
            };
            unsafe { CloseHandle(file) };
            err
        } else if self.object_type == SE_KERNEL_OBJECT {
            let name =
                String::from_utf16_lossy(self.path.split(|c| *c == 0).next().unwrap_or(&self.path));
            let Ok(dir) = open_object_directory(&name) else {
                return Err(KernelError::Apply(
                    "restore could not reopen the object directory".into(),
                ));
            };
            let err = unsafe {
                SetSecurityInfo(
                    dir,
                    SE_KERNEL_OBJECT,
                    DACL_SECURITY_INFORMATION,
                    ptr::null_mut(),
                    ptr::null_mut(),
                    self.dacl,
                    ptr::null_mut(),
                )
            };
            unsafe { CloseHandle(dir) };
            err
        } else {
            // SAFETY: `path` is a NUL-terminated file path; `dacl` is from the saved SD.
            unsafe {
                SetNamedSecurityInfoW(
                    self.path.as_mut_ptr(),
                    self.object_type,
                    DACL_SECURITY_INFORMATION,
                    ptr::null_mut(),
                    ptr::null_mut(),
                    self.dacl,
                    ptr::null_mut(),
                )
            }
        };
        if err != 0 {
            return Err(win32_error("restore DACL", err));
        }
        self.restored = true;
        Ok(())
    }
}
impl Drop for AclRestore {
    fn drop(&mut self) {
        if let Err(err) = self.restore() {
            eprintln!("workpen: {err}");
        }
    }
}

// Unwind in reverse. Two ACEs on one path each saved the DACL from
// before that ACE. Restoring the later save first would put the earlier
// ACE back. Drop only eprintln-swallows leftovers.
fn restore_guards(guards: &mut [AclRestore]) -> Result<(), KernelError> {
    for guard in guards.iter_mut().rev() {
        guard.restore()?;
    }
    Ok(())
}

pub(super) unsafe fn free_sid(sid: Handle) {
    // SAFETY: caller owns a SID from AllocateAndInitializeSid or userenv.
    unsafe {
        FreeSid(sid);
    }
}

fn last_error(op: &str) -> KernelError {
    // SAFETY: GetLastError has no preconditions.
    let err = unsafe { GetLastError() };
    KernelError::Apply(format!("{op} failed (win32 {err})"))
}

fn win32_error(op: &str, err: Dword) -> KernelError {
    KernelError::Apply(format!("{op} failed (win32 {err})"))
}

fn wide_path(path: &Path) -> Vec<u16> {
    path.as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}

fn wide_os(s: &OsStr) -> Vec<u16> {
    s.encode_wide().chain(std::iter::once(0)).collect()
}

pub(super) fn write_restricted_supported() -> bool {
    static OK: OnceLock<bool> = OnceLock::new();
    *OK.get_or_init(probe_write_restricted)
}

fn probe_write_restricted() -> bool {
    let Ok(sid) = RestrictedSid::new() else {
        return false;
    };
    create_write_restricted_token(sid.0).is_ok()
}

struct Prepared {
    token: CloseOnDrop,
    job: CloseOnDrop,
    acl_guards: Vec<AclRestore>,
    _sid: RestrictedSid,
    _world: WorldSid,
    helper: Option<PathBuf>,
    _net: Option<NetGuards>,
    wfp_skipped: bool,
}

struct NetGuards {
    _helper: windows_net::HelperFile,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum StdioCapture {
    Inherit,
    Collect,
    Forward,
}

pub(super) fn spawn_write_restricted(
    policy: &KernelPolicy,
    cmd: &mut Command,
    timeout: Option<Duration>,
) -> Result<(KernelApply, ExitStatus), KernelError> {
    let (applied, status, _, timed_out) =
        spawn_write_restricted_io(policy, cmd, timeout, StdioCapture::Inherit)?;
    if timed_out {
        return Err(KernelError::Timeout);
    }
    Ok((applied, status))
}

pub(super) fn spawn_write_restricted_output(
    policy: &KernelPolicy,
    cmd: &mut Command,
    timeout: Option<Duration>,
) -> Result<(KernelApply, std::process::Output, bool), KernelError> {
    let (applied, status, output, timed_out) =
        spawn_write_restricted_io(policy, cmd, timeout, StdioCapture::Collect)?;
    Ok((
        applied,
        output.unwrap_or_else(|| std::process::Output {
            status,
            stdout: Vec::new(),
            stderr: Vec::new(),
        }),
        timed_out,
    ))
}

pub(super) fn spawn_write_restricted_forward(
    policy: &KernelPolicy,
    cmd: &mut Command,
    timeout: Option<Duration>,
) -> Result<(KernelApply, ExitStatus, bool), KernelError> {
    let (applied, status, _, timed_out) =
        spawn_write_restricted_io(policy, cmd, timeout, StdioCapture::Forward)?;
    Ok((applied, status, timed_out))
}

fn spawn_write_restricted_io(
    policy: &KernelPolicy,
    cmd: &mut Command,
    timeout: Option<Duration>,
    capture: StdioCapture,
) -> Result<(KernelApply, ExitStatus, Option<std::process::Output>, bool), KernelError> {
    let prepared = if policy.network_blocked() {
        prepare_network_blocked(policy)?
    } else {
        prepare_write_restricted(policy)?
    };
    spawn_prepared(prepared, cmd, timeout, capture)
}

fn prepare_write_restricted(policy: &KernelPolicy) -> Result<Prepared, KernelError> {
    let rw_paths = rw_grant_paths(policy);
    if rw_paths.is_empty() && read_grant_paths(policy).is_empty() {
        return Err(KernelError::Apply(
            "write-restricted spawn needs a read or read-write grant".into(),
        ));
    }
    let sid = RestrictedSid::new()?;
    let world = WorldSid::new()?;
    let mut acl_guards = grant_write_aces(&rw_paths, sid.0)?;
    acl_guards.extend(deny_dest_aces(&dest_deny_paths(policy), world.0)?);
    acl_guards.extend(deny_dest_aces(&profile_secret_dirs(), sid.0)?);
    acl_guards.extend(allow_session_object_create(sid.0)?);
    let token = create_write_restricted_token(sid.0).map_err(prefix_apply("token setup"))?;
    let job = create_kill_job().map_err(prefix_apply("job setup"))?;
    Ok(Prepared {
        token,
        job,
        acl_guards,
        _sid: sid,
        _world: world,
        helper: None,
        _net: None,
        wfp_skipped: false,
    })
}

fn prepare_network_blocked(policy: &KernelPolicy) -> Result<Prepared, KernelError> {
    let workspace = container_anchor(policy)?;
    let helper =
        windows_net::HelperFile::install(&workspace).map_err(prefix_apply("net helper"))?;
    let (package_sid, wfp_skipped) = cached_blocked_profile(helper.path())?;
    let mut prepared = prepare_write_restricted(policy)?;
    for path in rw_grant_paths(policy) {
        grant_package_root(&path, package_sid, &mut prepared.acl_guards)?;
    }
    for path in read_grant_paths(policy) {
        grant_package_read(&path, package_sid, &mut prepared.acl_guards)?;
    }
    prepared
        .acl_guards
        .extend(deny_dest_aces(&dest_deny_paths(policy), package_sid)?);
    prepared
        .acl_guards
        .extend(deny_dest_aces(&profile_secret_dirs(), package_sid)?);
    prepared.acl_guards.push(set_acl_entry(
        helper.path(),
        package_sid,
        GENERIC_ALL,
        GRANT_ACCESS,
        NO_INHERITANCE,
    )?);
    prepared.wfp_skipped = wfp_skipped;
    prepared.token = wrap_appcontainer_token(prepared.token, package_sid)?;
    prepared.helper = Some(helper.path().to_path_buf());
    prepared._net = Some(NetGuards { _helper: helper });
    Ok(prepared)
}

fn container_anchor(policy: &KernelPolicy) -> Result<PathBuf, KernelError> {
    if let Some(path) = rw_grant_paths(policy).into_iter().next() {
        return Ok(path);
    }
    read_grant_paths(policy)
        .into_iter()
        .next()
        .ok_or_else(|| KernelError::Apply("network deny needs a read or read-write grant".into()))
}

struct BlockedSlot {
    profile: windows_net::AppContainerProfile,
    wfp: Option<windows_net::WfpSession>,
}

// SAFETY: the profile and WFP engine are owned by this slot. The mutex
// is the only share. Drop closes them.
unsafe impl Send for BlockedSlot {}

static BLOCKED: Mutex<Option<BlockedSlot>> = Mutex::new(None);
static BLOCKED_CREATES: AtomicU64 = AtomicU64::new(0);

pub(super) fn appcontainer_creates() -> u32 {
    u32::try_from(BLOCKED_CREATES.load(Ordering::Relaxed)).unwrap_or(u32::MAX)
}

pub(super) fn reset_appcontainer_creates() {
    BLOCKED_CREATES.store(0, Ordering::Relaxed);
}

pub(super) fn shutdown_jail_cache() {
    let mut slot = BLOCKED.lock().unwrap_or_else(|err| err.into_inner());
    *slot = None;
}

fn cached_blocked_profile(helper: &Path) -> Result<(Handle, bool), KernelError> {
    let mut slot = BLOCKED.lock().unwrap_or_else(|err| err.into_inner());
    if let Some(existing) = slot.as_ref() {
        return Ok((existing.profile.sid(), existing.wfp.is_none()));
    }
    let pid = unsafe { GetCurrentProcessId() };
    BLOCKED_CREATES.fetch_add(1, Ordering::Relaxed);
    let profile = windows_net::AppContainerProfile::create_stable(&format!("wpnh.b.{pid}"))
        .map_err(prefix_apply("AppContainer profile"))?;
    let wfp = windows_net::WfpSession::apply(profile.sid(), helper)
        .map_err(prefix_apply("WFP package filter"))?;
    let sid = profile.sid();
    let skipped = wfp.is_none();
    *slot = Some(BlockedSlot { profile, wfp });
    Ok((sid, skipped))
}

/// Best-effort grant on the session object directory. MSYS does not
/// create `\BaseNamedObjects\msys-...` through this ACE when that
/// leaf already exists. [`allow_msys_shared_dirs`] grants the leaf.
/// A missed ACE does not fail the spawn.
fn allow_session_object_create(sid: Handle) -> Result<Vec<AclRestore>, KernelError> {
    let rights = DIRECTORY_ALL_ACCESS | SECTION_ALL_ACCESS | GENERIC_ALL;
    let mut guards = Vec::new();
    for name in object_namespace_names() {
        match grant_directory_object(&name, sid, rights) {
            Ok(guard) => guards.push(guard),
            Err(err) => eprintln!("workpen: namespace ACE skipped: {err}"),
        }
    }
    Ok(guards)
}

fn object_namespace_names() -> Vec<String> {
    let mut names = vec![r"\BaseNamedObjects".to_string()];
    let mut session = 0u32;
    let ok = unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session) };
    if ok != 0 {
        names.push(format!("\\Sessions\\{session}\\BaseNamedObjects"));
    }
    names
}

fn grant_directory_object(
    name: &str,
    sid: Handle,
    rights: Dword,
) -> Result<AclRestore, KernelError> {
    let dir = open_object_directory(name)?;
    let mut owner = ptr::null_mut();
    let mut group = ptr::null_mut();
    let mut dacl = ptr::null_mut();
    let mut sacl = ptr::null_mut();
    let mut sd = ptr::null_mut();
    let got = unsafe {
        GetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            &mut owner,
            &mut group,
            &mut dacl,
            &mut sacl,
            &mut sd,
        )
    };
    if got != 0 {
        unsafe { CloseHandle(dir) };
        return Err(win32_error("GetSecurityInfo", got));
    }
    let sd = LocalMem(sd);
    let mut entry = ExplicitAccessW {
        grf_access_permissions: rights,
        grf_access_mode: GRANT_ACCESS,
        // Children created in this directory inherit the ACE. An MSYS
        // leaf that already exists does not. That leaf is granted below.
        grf_inheritance: OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
        trustee: TrusteeW {
            p_multiple_trustee: ptr::null_mut(),
            multiple_trustee_operation: NO_MULTIPLE_TRUSTEE,
            trustee_form: TRUSTEE_IS_SID,
            trustee_type: TRUSTEE_IS_WELL_KNOWN_GROUP,
            ptstr_name: sid,
        },
    };
    let mut new_acl = ptr::null_mut();
    let set = unsafe { SetEntriesInAclW(1, &mut entry, dacl, &mut new_acl) };
    if set != 0 {
        unsafe { CloseHandle(dir) };
        return Err(win32_error("SetEntriesInAclW", set));
    }
    let new_acl = LocalMem(new_acl);
    let applied = unsafe {
        SetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            new_acl.0,
            ptr::null_mut(),
        )
    };
    unsafe { CloseHandle(dir) };
    if applied != 0 {
        return Err(win32_error("SetSecurityInfo", applied));
    }
    Ok(AclRestore {
        path: wide_os(OsStr::new(name)),
        object_type: SE_KERNEL_OBJECT,
        _sd: sd,
        dacl,
        restored: false,
    })
}

fn open_directory_for_dacl(name: &str) -> Result<Handle, KernelError> {
    match open_directory_status(name, 0x0006_0000) {
        Ok(dir) => Ok(dir),
        Err(status) if status == STATUS_ACCESS_DENIED => {
            take_directory_ownership(name)?;
            open_directory_status(name, 0x0006_0000).map_err(|status| {
                KernelError::Apply(format!(
                    "NtOpenDirectoryObject {name} after ownership failed (ntstatus {status:#x})"
                ))
            })
        }
        Err(status) => Err(KernelError::Apply(format!(
            "NtOpenDirectoryObject {name} failed (ntstatus {status:#x})"
        ))),
    }
}

fn relax_child_bno(process: Handle, restricted: Handle, world: Handle) {
    let mut token = ptr::null_mut();
    let opened = unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) };
    if opened == 0 {
        eprintln!(
            "workpen: msys bno token failed: {}",
            last_error("OpenProcessToken")
        );
        return;
    }
    let token = CloseOnDrop(token);
    let mut bytes = 0u32;
    unsafe {
        GetTokenInformation(token.0, 44, ptr::null_mut(), 0, &mut bytes);
    }
    if bytes < 16 {
        eprintln!("workpen: msys bno query size={bytes} win32 {}", unsafe {
            GetLastError()
        });
        return;
    }
    let mut buf = vec![0u8; bytes as usize];
    let ok =
        unsafe { GetTokenInformation(token.0, 44, buf.as_mut_ptr().cast(), bytes, &mut bytes) };
    if ok == 0 {
        eprintln!(
            "workpen: msys bno query failed: {}",
            last_error("GetTokenInformation TokenBnoIsolation")
        );
        return;
    }
    let prefix = unsafe { buf.as_ptr().cast::<*mut u16>().read() };
    let enabled = unsafe { *buf.as_ptr().add(8) };
    if prefix.is_null() {
        return;
    }
    let mut len = 0usize;
    while unsafe { *prefix.add(len) } != 0 && len < 512 {
        len += 1;
    }
    let text = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(prefix, len) });
    if enabled != 0 && !text.is_empty() {
        let mut session = 0u32;
        let session_ok = unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session) };
        let mut paths = vec![text.clone()];
        if session_ok != 0 {
            paths.push(format!(r"\Sessions\{session}\BaseNamedObjects\{text}"));
        }
        paths.push(format!(r"\BaseNamedObjects\{text}"));
        for path in paths {
            match null_directory_dacl(&path, restricted, world) {
                Ok(_) => {}
                Err(err) => eprintln!("workpen: msys bno dacl skipped: {path}: {err}"),
            }
        }
    }
}

/// Replace this object directory's DACL with null.
/// Do not call this on `\BaseNamedObjects` itself.
fn null_directory_dacl(
    name: &str,
    _restricted: Handle,
    _world: Handle,
) -> Result<Option<AclRestore>, KernelError> {
    let dir = open_directory_for_dacl(name)?;
    let mut owner = ptr::null_mut();
    let mut group = ptr::null_mut();
    let mut dacl = ptr::null_mut();
    let mut sacl = ptr::null_mut();
    let mut sd = ptr::null_mut();
    let got = unsafe {
        GetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            &mut owner,
            &mut group,
            &mut dacl,
            &mut sacl,
            &mut sd,
        )
    };
    if got != 0 {
        unsafe { CloseHandle(dir) };
        return Err(win32_error("GetSecurityInfo", got));
    }
    let sd = LocalMem(sd);
    // DACL_SECURITY_INFORMATION plus a null DACL pointer installs a
    // null DACL. The saved DACL above is restored after the child exits.
    let applied = unsafe {
        SetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        )
    };
    unsafe { CloseHandle(dir) };
    if applied != 0 {
        return Err(win32_error("SetSecurityInfo null DACL", applied));
    }
    Ok(Some(AclRestore {
        path: wide_os(OsStr::new(name)),
        object_type: SE_KERNEL_OBJECT,
        _sd: sd,
        dacl,
        restored: false,
    }))
}

#[repr(C)]
struct UnicodeString {
    length: u16,
    maximum_length: u16,
    buffer: *mut u16,
}

#[repr(C)]
struct ObjectAttributes {
    length: u32,
    root_directory: Handle,
    object_name: *mut UnicodeString,
    attributes: u32,
    security_descriptor: *mut core::ffi::c_void,
    security_quality_of_service: *mut core::ffi::c_void,
}

#[repr(C)]
struct IoStatusBlock {
    status: usize,
    information: usize,
}

#[link(name = "ntdll")]
unsafe extern "system" {
    fn NtOpenDirectoryObject(
        directory_handle: *mut Handle,
        desired_access: u32,
        object_attributes: *mut ObjectAttributes,
    ) -> i32;
    fn NtCreateDirectoryObject(
        directory_handle: *mut Handle,
        desired_access: u32,
        object_attributes: *mut ObjectAttributes,
    ) -> i32;
    fn NtOpenSection(
        section_handle: *mut Handle,
        desired_access: u32,
        object_attributes: *mut ObjectAttributes,
    ) -> i32;
    fn NtOpenFile(
        file_handle: *mut Handle,
        desired_access: u32,
        object_attributes: *mut ObjectAttributes,
        io_status_block: *mut IoStatusBlock,
        share_access: u32,
        open_options: u32,
    ) -> i32;
}

fn open_object_directory(name: &str) -> Result<Handle, KernelError> {
    // READ_CONTROL | WRITE_DAC. The DACL edit does not need directory create.
    open_directory_status(name, 0x0006_0000).map_err(|status| {
        KernelError::Apply(format!(
            "NtOpenDirectoryObject {name} failed (ntstatus {status:#x})"
        ))
    })
}

/// MSYS `get_shared_parent_dir` calls `NtCreateDirectoryObject` on
/// `\BaseNamedObjects\msys-2.0S<n>-<install key>` with `OBJ_OPENIF`.
/// Checkout's git has usually created that leaf already, with an
/// Everyone ACE that does not name the restricted SID, so a grant on
/// the parent directory still returns `0xC0000022`.
fn allow_msys_shared_dirs(
    program: &Path,
    restricted: Handle,
    world: Handle,
    guards: &mut Vec<AclRestore>,
) {
    let Some(dll) = msys_dll_beside(program) else {
        return;
    };
    let nt_path = match msys_install_nt_path(&dll) {
        Ok(path) => path,
        Err(err) => {
            eprintln!("workpen: msys dll path skipped: {err}");
            return;
        }
    };
    let hash = hash_path_name(0, &nt_path);
    let shared_id = msys_shared_id(&dll).unwrap_or_else(|| "msys-2.0S5".to_string());
    let leaf = format!("{shared_id}-{hash:016x}");
    ensure_msys_shared_dir(&format!(r"\BaseNamedObjects\{leaf}"), restricted, world);
    let mut session = 0u32;
    let ok = unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session) };
    if ok != 0 && session != 0 {
        ensure_msys_shared_dir(
            &format!(r"\Sessions\BNOLINKS\{session}\{leaf}"),
            restricted,
            world,
        );
    }
    // `SID.1` is created in the leaf above. `Restricted` is unrelated.
    // Nulling `\BaseNamedObjects` itself breaks AppContainer tests.
    ensure_msys_shared_dir(r"\BaseNamedObjects\Restricted", restricted, world);
    // `Restricted` only. Restored after the child exits.
    // Do not null `\BaseNamedObjects`.
    // `sigproc_init` creates the signal pipe with `sec_user`, which
    // does not name `S-1-5-12`. The pipe device allow is restored
    // with the other guards.
    allow_signal_pipe(restricted, guards);
    for name in restricted_namespace_names() {
        match null_directory_dacl(&name, restricted, world) {
            Ok(Some(guard)) => guards.push(guard),
            Ok(None) => {}
            Err(err) => eprintln!("workpen: msys restricted dir skipped: {name}: {err}"),
        }
    }
}

fn allow_signal_pipe(restricted: Handle, guards: &mut Vec<AclRestore>) {
    let file = match open_nt_file(r"\Device\NamedPipe", 0x0006_0000, FILE_DIRECTORY_FILE) {
        Ok(file) => file,
        Err(status) => {
            eprintln!("workpen: npfs open skipped ntstatus {status:#x}");
            return;
        }
    };
    match grant_npfs_inherit(file, restricted) {
        Ok(Some(guard)) => guards.push(guard),
        Ok(None) => {}
        Err(err) => eprintln!("workpen: npfs inherit skipped: {err}"),
    }
}

fn open_nt_file(name: &str, access: u32, options: u32) -> Result<Handle, i32> {
    let mut wide: Vec<u16> = OsStr::new(name).encode_wide().collect();
    let bytes = u16::try_from(wide.len() * 2).unwrap_or(u16::MAX);
    let mut us = UnicodeString {
        length: bytes,
        maximum_length: bytes,
        buffer: wide.as_mut_ptr(),
    };
    let mut attrs = ObjectAttributes {
        length: std::mem::size_of::<ObjectAttributes>() as u32,
        root_directory: ptr::null_mut(),
        object_name: &mut us,
        attributes: OBJ_CASE_INSENSITIVE,
        security_descriptor: ptr::null_mut(),
        security_quality_of_service: ptr::null_mut(),
    };
    let mut iosb = IoStatusBlock {
        status: 0,
        information: 0,
    };
    let mut handle = ptr::null_mut();
    let status = unsafe {
        NtOpenFile(
            &mut handle,
            access,
            &mut attrs,
            &mut iosb,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            options,
        )
    };
    if status != 0 || handle.is_null() {
        return Err(status);
    }
    Ok(handle)
}

fn grant_npfs_inherit(file: Handle, sid: Handle) -> Result<Option<AclRestore>, KernelError> {
    let result = grant_npfs_inherit_inner(file, sid);
    unsafe { CloseHandle(file) };
    result
}

fn grant_npfs_inherit_inner(file: Handle, sid: Handle) -> Result<Option<AclRestore>, KernelError> {
    let mut owner = ptr::null_mut();
    let mut group = ptr::null_mut();
    let mut dacl = ptr::null_mut();
    let mut sacl = ptr::null_mut();
    let mut sd = ptr::null_mut();
    let got = unsafe {
        GetSecurityInfo(
            file,
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            &mut owner,
            &mut group,
            &mut dacl,
            &mut sacl,
            &mut sd,
        )
    };
    if got != 0 {
        return Err(win32_error("GetSecurityInfo", got));
    }
    let sd = LocalMem(sd);
    // A null device DACL already lets the restricted token create a
    // pipe. Replacing it would remove everyone else's access.
    if dacl.is_null() {
        return Ok(None);
    }
    let mask = GENERIC_ALL | FILE_ALL_ACCESS;
    let trustee = TrusteeW {
        p_multiple_trustee: ptr::null_mut(),
        multiple_trustee_operation: NO_MULTIPLE_TRUSTEE,
        trustee_form: TRUSTEE_IS_SID,
        trustee_type: TRUSTEE_IS_WELL_KNOWN_GROUP,
        ptstr_name: sid,
    };
    // A direct ACE covers create-in-directory. NPFS assigns the new
    // pipe's security with a null parent, so inheritance does not
    // rewrite `sec_user`. The direct ACE is the create check.
    let mut entries = [
        ExplicitAccessW {
            grf_access_permissions: mask,
            grf_access_mode: GRANT_ACCESS,
            grf_inheritance: NO_INHERITANCE,
            trustee,
        },
        ExplicitAccessW {
            grf_access_permissions: mask,
            grf_access_mode: GRANT_ACCESS,
            grf_inheritance: OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE,
            trustee,
        },
    ];
    let mut new_acl = ptr::null_mut();
    let set = unsafe { SetEntriesInAclW(2, entries.as_mut_ptr(), dacl, &mut new_acl) };
    if set != 0 {
        return Err(win32_error("SetEntriesInAclW", set));
    }
    let new_acl = LocalMem(new_acl);
    let applied = unsafe {
        SetSecurityInfo(
            file,
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            new_acl.0,
            ptr::null_mut(),
        )
    };
    if applied != 0 {
        return Err(win32_error("SetSecurityInfo", applied));
    }
    Ok(Some(AclRestore {
        path: wide_os(OsStr::new(r"\Device\NamedPipe")),
        object_type: NPFS_RESTORE,
        _sd: sd,
        dacl,
        restored: false,
    }))
}

/// `sec_user` does not name `S-1-5-12`, and the write end of the signal
/// pipe is opened with `GENERIC_WRITE`. Replace the descriptor on every
/// `NtCreateNamedPipeFile` in this process. ntdll is mapped before
/// `DllMain`, so the patch is visible to `sigproc_init`.
fn install_ntdll_pipe_hook(process: Handle, restricted: Handle) -> Result<(), KernelError> {
    let stub = ntdll_export(b"NtCreateNamedPipeFile\0")?;
    let mut head = [0u8; 8];
    let read = unsafe {
        ReadProcessMemory(
            process,
            stub.cast(),
            head.as_mut_ptr(),
            head.len(),
            ptr::null_mut(),
        )
    };
    if read == 0 {
        return Err(last_error("ReadProcessMemory ntdll"));
    }
    if head[0..4] != [0x4C, 0x8B, 0xD1, 0xB8] {
        return Err(KernelError::Apply(format!(
            "NtCreateNamedPipeFile stub {:02x?}",
            &head[..]
        )));
    }
    let syscall = u32::from_le_bytes(head[4..8].try_into().unwrap());
    let sd = remote_user_and_restricted_sd(process, restricted)?;
    let cave = alloc_hook_cave(process, stub as usize);
    if cave.is_null() {
        return Err(last_error("VirtualAllocEx near ntdll"));
    }
    let code = pipe_hook_shellcode(sd as u64, syscall);
    if !write_remote(process, cave, &code) {
        return Err(last_error("WriteProcessMemory shellcode"));
    }
    let rel = (cave as isize).wrapping_sub(stub as isize + 5);
    let rel = i32::try_from(rel)
        .map_err(|_| KernelError::Apply("pipe hook cave is out of rel32 range".to_string()))?;
    let mut patch = vec![0xE9];
    patch.extend_from_slice(&rel.to_le_bytes());
    if !write_remote(process, stub.cast(), &patch) {
        return Err(last_error("WriteProcessMemory ntdll stub"));
    }
    Ok(())
}

fn ntdll_export(name: &[u8]) -> Result<*mut u8, KernelError> {
    let module_name = wide_os(OsStr::new("ntdll.dll"));
    let module = unsafe { GetModuleHandleW(module_name.as_ptr()) };
    if module.is_null() {
        return Err(last_error("GetModuleHandleW ntdll"));
    }
    let addr = unsafe { GetProcAddress(module, name.as_ptr()) };
    if addr.is_null() {
        return Err(last_error("GetProcAddress NtCreateNamedPipeFile"));
    }
    Ok(addr.cast())
}

fn pipe_hook_shellcode(sd: u64, syscall: u32) -> Vec<u8> {
    let mut code = vec![
        0x4D, 0x85, 0xC0, // test r8, r8
        0x74, 0x0E, // jz to the syscall setup
        0x48, 0xB8, // mov rax, imm64
    ];
    code.extend_from_slice(&sd.to_le_bytes());
    code.extend_from_slice(&[
        0x49, 0x89, 0x40, 0x20, // mov [r8+20h], rax
        0x4C, 0x8B, 0xD1, // mov r10, rcx
        0xB8, // mov eax, imm32
    ]);
    code.extend_from_slice(&syscall.to_le_bytes());
    code.extend_from_slice(&[0x0F, 0x05, 0xC3]); // syscall; ret
    code
}

fn remote_user_and_restricted_sd(
    process: Handle,
    restricted: Handle,
) -> Result<*mut core::ffi::c_void, KernelError> {
    let user = current_user_sid()?;
    let remote = unsafe { VirtualAllocEx(process, ptr::null_mut(), 512, 0x3000, 0x04) };
    if remote.is_null() {
        return Err(last_error("VirtualAllocEx security descriptor"));
    }
    let mut buf = vec![0u8; 512];
    let sd = buf.as_mut_ptr();
    let acl = unsafe { sd.add(64) };
    let ready = unsafe {
        InitializeSecurityDescriptor(sd, 1) != 0
            && InitializeAcl(acl, 360, 2) != 0
            && AddAccessAllowedAce(
                acl,
                2,
                GENERIC_ALL | FILE_ALL_ACCESS,
                user.as_ptr().cast_mut().cast(),
            ) != 0
            && AddAccessAllowedAce(acl, 2, GENERIC_ALL | FILE_ALL_ACCESS, restricted) != 0
            && SetSecurityDescriptorDacl(sd, 1, acl, 0) != 0
    };
    if !ready {
        return Err(last_error("pipe security descriptor"));
    }
    unsafe {
        sd.add(32)
            .cast::<*mut core::ffi::c_void>()
            .write(remote.add(64));
    }
    if !write_remote(process, remote, &buf) {
        return Err(last_error("WriteProcessMemory security descriptor"));
    }
    Ok(remote)
}

fn alloc_hook_cave(process: Handle, stub: usize) -> *mut core::ffi::c_void {
    let page = stub & !0xFFFF;
    for step in 1..512usize {
        let hint = page.wrapping_sub(step * 0x10000) as *mut core::ffi::c_void;
        let got = unsafe { VirtualAllocEx(process, hint, 0x1000, 0x3000, 0x40) };
        if !got.is_null() {
            return got;
        }
    }
    ptr::null_mut()
}

fn write_remote(process: Handle, addr: *mut core::ffi::c_void, bytes: &[u8]) -> bool {
    let ok =
        unsafe { WriteProcessMemory(process, addr, bytes.as_ptr(), bytes.len(), ptr::null_mut()) };
    if ok != 0 {
        return true;
    }
    let mut old = 0u32;
    if unsafe { VirtualProtectEx(process, addr, bytes.len(), 0x40, &mut old) } == 0 {
        return false;
    }
    let ok =
        unsafe { WriteProcessMemory(process, addr, bytes.as_ptr(), bytes.len(), ptr::null_mut()) };
    unsafe {
        VirtualProtectEx(process, addr, bytes.len(), old, &mut old);
    }
    ok != 0
}

fn restricted_namespace_names() -> Vec<String> {
    // Only `Restricted`. Nulling `\BaseNamedObjects` itself breaks
    // AppContainer creation in tests that run at the same time.
    let mut names = vec![r"\BaseNamedObjects\Restricted".to_string()];
    let mut session = 0u32;
    let ok = unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut session) };
    if ok != 0 && session != 0 {
        names.push(format!(r"\Sessions\{session}\BaseNamedObjects\Restricted"));
    }
    names
}

fn msys_dll_beside(program: &Path) -> Option<PathBuf> {
    let dll = program.parent()?.join("msys-2.0.dll");
    dll.is_file().then_some(dll)
}

fn msys_shared_id(dll: &Path) -> Option<String> {
    let bytes = std::fs::read(dll).ok()?;
    // The version banner is `shared id: msys-2.0S<n>`. A bare scan can
    // match an earlier `msys-2.0S` byte run that is not the shared id.
    shared_id_after(&bytes, b"shared id: msys-2.0S")
        .or_else(|| shared_id_after(&bytes, b"msys-2.0S"))
}

fn shared_id_after(bytes: &[u8], needle: &[u8]) -> Option<String> {
    let rel = bytes
        .windows(needle.len())
        .position(|window| window == needle)?;
    let start = rel + needle.len();
    let digits = bytes[start..]
        .iter()
        .take_while(|byte| byte.is_ascii_digit())
        .count();
    if digits == 0 {
        return None;
    }
    Some(format!(
        "msys-2.0S{}",
        String::from_utf8_lossy(&bytes[start..start + digits])
    ))
}

fn msys_install_nt_path(dll: &Path) -> Result<Vec<u16>, KernelError> {
    let wide = wide_path(dll);
    // SAFETY: `wide` is a NUL-terminated path. The share mode matches
    // MSYS `FILE_SHARE_VALID_FLAGS` so a running git does not block the open.
    let file = unsafe {
        CreateFileW(
            wide.as_ptr(),
            GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_WRITE | 0x4,
            ptr::null_mut(),
            OPEN_EXISTING,
            0,
            ptr::null_mut(),
        )
    };
    if file.is_null() || file == INVALID_HANDLE_VALUE {
        return Err(last_error("CreateFileW msys dll"));
    }
    let mut buf = vec![0u16; 32768];
    // SAFETY: `file` is the open DLL; `buf` receives the Win32 path.
    let n = unsafe { GetFinalPathNameByHandleW(file, buf.as_mut_ptr(), buf.len() as Dword, 0) };
    unsafe { CloseHandle(file) };
    if n == 0 || n as usize >= buf.len() {
        return Err(last_error("GetFinalPathNameByHandleW"));
    }
    buf.truncate(n as usize);
    normalize_msys_install_path(&mut buf);
    Ok(buf)
}

/// MSYS turns the DLL path into an NT path and hashes that, including
/// the file name. `\??\` is `\\?\` with the second character replaced.
fn normalize_msys_install_path(path: &mut Vec<u16>) {
    let slash = u16::from(b'\\');
    let question = u16::from(b'?');
    let prefixed = path.len() >= 2 && path[0] == slash && path[1] == slash;
    if !prefixed {
        let mut next = vec![slash, slash, question, slash];
        next.append(path);
        *path = next;
    }
    if path.len() >= 2 {
        path[1] = question;
    }
}

/// Cygwin `hash_path_name`: each unit is upcased, then
/// `hash = ch + (hash << 6) + (hash << 16) - hash` in 64 bits.
fn hash_path_name(mut hash: u64, name: &[u16]) -> u64 {
    let upper = upcase_path(name);
    for unit in upper {
        let ch = u64::from(unit);
        hash = ch
            .wrapping_add(hash.wrapping_shl(6))
            .wrapping_add(hash.wrapping_shl(16))
            .wrapping_sub(hash);
    }
    hash
}

fn upcase_path(name: &[u16]) -> Vec<u16> {
    let mut out = name.to_vec();
    if out.is_empty() {
        return out;
    }
    // LOCALE_INVARIANT + LCMAP_UPPERCASE. ASCII matches
    // `RtlUpcaseUnicodeChar`. A failed map still uppercases A-Z.
    let mapped = unsafe {
        LCMapStringW(
            0x007F,
            0x0000_0200,
            name.as_ptr(),
            name.len() as i32,
            out.as_mut_ptr(),
            out.len() as i32,
        )
    };
    if mapped == 0 {
        for unit in &mut out {
            if (u16::from(b'a')..=u16::from(b'z')).contains(unit) {
                *unit -= 32;
            }
        }
    }
    out
}

fn ensure_msys_shared_dir(name: &str, restricted: Handle, world: Handle) {
    let dir = match open_directory_status(name, 0x0006_0000) {
        Ok(dir) => dir,
        Err(status)
            if status == STATUS_OBJECT_NAME_NOT_FOUND || status == STATUS_OBJECT_PATH_NOT_FOUND =>
        {
            match create_msys_directory(name, restricted, world) {
                Ok(dir) => dir,
                Err(status) => {
                    eprintln!("workpen: msys shared create skipped: {name} (ntstatus {status:#x})");
                    return;
                }
            }
        }
        Err(status) if status == STATUS_ACCESS_DENIED => {
            // The leaf exists, but its DACL does not grant WRITE_DAC.
            if let Err(err) = take_directory_ownership(name) {
                eprintln!("workpen: msys shared owner skipped: {name}: {err}");
                return;
            }
            match open_directory_status(name, 0x0006_0000) {
                Ok(dir) => dir,
                Err(status) => {
                    eprintln!("workpen: msys shared open skipped: {name} (ntstatus {status:#x})");
                    return;
                }
            }
        }
        Err(status) => {
            eprintln!("workpen: msys shared open skipped: {name} (ntstatus {status:#x})");
            return;
        }
    };
    secure_msys_directory(dir, name, restricted);
}

fn take_directory_ownership(name: &str) -> Result<(), KernelError> {
    enable_privilege("SeTakeOwnershipPrivilege")?;
    let dir = open_directory_status(name, WRITE_OWNER | 0x0002_0000).map_err(|status| {
        KernelError::Apply(format!(
            "NtOpenDirectoryObject {name} WRITE_OWNER failed (ntstatus {status:#x})"
        ))
    })?;
    let user = current_user_sid()?;
    // SAFETY: `dir` is open for WRITE_OWNER. `user` is a SID copy.
    let set = unsafe {
        SetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            OWNER_SECURITY_INFORMATION,
            user.as_ptr().cast_mut().cast(),
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null_mut(),
        )
    };
    unsafe { CloseHandle(dir) };
    if set != 0 {
        return Err(win32_error("SetSecurityInfo owner", set));
    }
    Ok(())
}

fn enable_privilege(name: &str) -> Result<(), KernelError> {
    let mut token = ptr::null_mut();
    // SAFETY: current process. Adjust plus query is enough to enable one privilege.
    let opened = unsafe {
        OpenProcessToken(
            GetCurrentProcess(),
            TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
            &mut token,
        )
    };
    if opened == 0 {
        return Err(last_error("OpenProcessToken privileges"));
    }
    let token = CloseOnDrop(token);
    let wide = wide_os(OsStr::new(name));
    let mut luid = Luid {
        low_part: 0,
        high_part: 0,
    };
    // SAFETY: `wide` is a NUL-terminated privilege name.
    let looked = unsafe { LookupPrivilegeValueW(ptr::null(), wide.as_ptr(), &mut luid) };
    if looked == 0 {
        return Err(last_error("LookupPrivilegeValueW"));
    }
    let mut state = TokenPrivileges {
        count: 1,
        attr: LuidAndAttributes {
            luid,
            attributes: SE_PRIVILEGE_ENABLED,
        },
    };
    // SAFETY: `state` is one privilege. Previous state is unused.
    let adjusted = unsafe {
        AdjustTokenPrivileges(token.0, 0, &mut state, 0, ptr::null_mut(), ptr::null_mut())
    };
    let err = unsafe { GetLastError() };
    if adjusted == 0 || err == 1300 {
        return Err(KernelError::Apply(format!(
            "AdjustTokenPrivileges {name} failed (win32 {err})"
        )));
    }
    Ok(())
}

fn current_user_sid() -> Result<Vec<u8>, KernelError> {
    let token = open_current_process_token()?;
    token_user_sid(token.0)
}

fn token_user_sid(token: Handle) -> Result<Vec<u8>, KernelError> {
    let mut bytes = 0u32;
    unsafe {
        GetTokenInformation(token, TOKEN_USER, ptr::null_mut(), 0, &mut bytes);
    }
    if bytes < 8 {
        return Err(last_error("GetTokenInformation TokenUser"));
    }
    let mut buf = vec![0u8; bytes as usize];
    // SAFETY: `buf` is `bytes` long. The class is TokenUser.
    let ok = unsafe {
        GetTokenInformation(
            token,
            TOKEN_USER,
            buf.as_mut_ptr().cast(),
            bytes,
            &mut bytes,
        )
    };
    if ok == 0 {
        return Err(last_error("GetTokenInformation TokenUser"));
    }
    let sid = unsafe { buf.as_ptr().cast::<Handle>().read() };
    if sid.is_null() {
        return Err(KernelError::Apply("TokenUser SID is null".into()));
    }
    let len = unsafe { GetLengthSid(sid) };
    if len == 0 || len > 256 {
        return Err(last_error("GetLengthSid"));
    }
    let mut copy = vec![0u8; len as usize];
    // SAFETY: `sid` is the TokenUser SID inside `buf`, which stays alive.
    let copied = unsafe { CopySid(len, copy.as_mut_ptr(), sid) };
    if copied == 0 {
        return Err(last_error("CopySid"));
    }
    Ok(copy)
}

fn open_directory_status(name: &str, access: u32) -> Result<Handle, i32> {
    let mut wide: Vec<u16> = OsStr::new(name).encode_wide().collect();
    let bytes = u16::try_from(wide.len() * 2).unwrap_or(u16::MAX);
    let mut us = UnicodeString {
        length: bytes,
        maximum_length: bytes,
        buffer: wide.as_mut_ptr(),
    };
    let mut attrs = ObjectAttributes {
        length: std::mem::size_of::<ObjectAttributes>() as u32,
        root_directory: ptr::null_mut(),
        object_name: &mut us,
        attributes: OBJ_CASE_INSENSITIVE,
        security_descriptor: ptr::null_mut(),
        security_quality_of_service: ptr::null_mut(),
    };
    let mut handle = ptr::null_mut();
    // SAFETY: `us` and `wide` live for the call.
    let status = unsafe { NtOpenDirectoryObject(&mut handle, access, &mut attrs) };
    if status != 0 || handle.is_null() {
        return Err(status);
    }
    Ok(handle)
}

fn create_msys_directory(name: &str, restricted: Handle, world: Handle) -> Result<Handle, i32> {
    let mut sd = [0u64; 8];
    let sd_ptr = sd.as_mut_ptr().cast::<u8>();
    // ACLs must be DWORD-aligned. A `Vec<u8>` is not.
    let mut acl_words = vec![0u32; 64];
    let acl = acl_words.as_mut_ptr().cast::<u8>();
    let ready = unsafe {
        InitializeSecurityDescriptor(sd_ptr, 1) != 0
            && InitializeAcl(acl, acl_words.len() as Dword * 4, 2) != 0
            && AddAccessAllowedAce(acl, 2, MSYS_DIR_WRITE_DAC, world) != 0
            && AddAccessAllowedAce(acl, 2, MSYS_DIR_ACCESS, restricted) != 0
            && SetSecurityDescriptorDacl(sd_ptr, 1, acl, 0) != 0
    };
    if !ready {
        return Err(STATUS_OBJECT_PATH_NOT_FOUND);
    }
    let mut wide: Vec<u16> = OsStr::new(name).encode_wide().collect();
    let bytes = u16::try_from(wide.len() * 2).unwrap_or(u16::MAX);
    let mut us = UnicodeString {
        length: bytes,
        maximum_length: bytes,
        buffer: wide.as_mut_ptr(),
    };
    let mut attrs = ObjectAttributes {
        length: std::mem::size_of::<ObjectAttributes>() as u32,
        root_directory: ptr::null_mut(),
        object_name: &mut us,
        attributes: OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
        security_descriptor: sd.as_mut_ptr().cast(),
        security_quality_of_service: ptr::null_mut(),
    };
    let mut handle = ptr::null_mut();
    // SAFETY: `sd`, `acl`, `us`, and `wide` live for the call.
    let status = unsafe { NtCreateDirectoryObject(&mut handle, MSYS_DIR_WRITE_DAC, &mut attrs) };
    if status != 0 || handle.is_null() {
        return Err(status);
    }
    Ok(handle)
}

fn grant_sid_on_directory(dir: Handle, sid: Handle, rights: Dword) -> Result<(), KernelError> {
    let mut owner = ptr::null_mut();
    let mut group = ptr::null_mut();
    let mut dacl = ptr::null_mut();
    let mut sacl = ptr::null_mut();
    let mut sd = ptr::null_mut();
    // SAFETY: `dir` is an open object directory.
    let got = unsafe {
        GetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            &mut owner,
            &mut group,
            &mut dacl,
            &mut sacl,
            &mut sd,
        )
    };
    if got != 0 {
        return Err(win32_error("GetSecurityInfo", got));
    }
    let _sd = LocalMem(sd);
    // A null DACL already grants every SID. The caller adds an
    // inheritable section allow when this returns.
    if dacl.is_null() {
        return Ok(());
    }
    let new_acl = match acl_with_grant(dacl, sid, rights) {
        Ok(acl) => acl,
        Err(err) => return Err(err),
    };
    // SAFETY: `new_acl` is a LocalAlloc ACL from SetEntriesInAclW.
    let applied = unsafe {
        SetSecurityInfo(
            dir,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            new_acl.0,
            ptr::null_mut(),
        )
    };
    if applied != 0 {
        return Err(win32_error("SetSecurityInfo", applied));
    }
    Ok(())
}

/// `sec_none` passes a null descriptor, so `SID.1` inherits this
/// directory. The directory-open ACE is not inheritable. Children need
/// an allow for the user and for `S-1-5-12`.
fn secure_msys_directory(dir: Handle, name: &str, restricted: Handle) {
    let granted = grant_sid_on_directory(dir, restricted, MSYS_DIR_ACCESS);
    let inherited = append_inheritable_section_allows(dir, restricted);
    // `Restricted` is not the parent of `SID.1`.
    let existing = if name.contains("msys-") {
        grant_existing_user_section(name, restricted)
    } else {
        Ok(())
    };
    unsafe { CloseHandle(dir) };
    if let Err(err) = granted {
        eprintln!("workpen: msys shared ACE skipped: {name}: {err}");
    }
    if let Err(err) = inherited {
        eprintln!("workpen: msys inherit skipped: {name}: {err}");
    }
    if let Err(err) = existing {
        eprintln!("workpen: msys user section skipped: {name}: {err}");
    }
}

fn append_inheritable_section_allows(
    object: Handle,
    restricted: Handle,
) -> Result<(), KernelError> {
    let user = current_user_sid()?;
    let user_sid = user.as_ptr().cast_mut().cast();
    let (dacl, _sd) = object_dacl(object)?;
    let have_user = acl_has_inherit_allow(dacl, user_sid, MSYS_INHERIT_ACCESS);
    let have_restricted = acl_has_inherit_allow(dacl, restricted, MSYS_INHERIT_ACCESS);
    if have_user && have_restricted {
        return Ok(());
    }
    let mut words = vec![0u32; 1024];
    let acl = words.as_mut_ptr().cast::<u8>();
    let bytes = (words.len() * 4) as Dword;
    if unsafe { InitializeAcl(acl, bytes, 2) } == 0 {
        return Err(last_error("InitializeAcl"));
    }
    if !dacl.is_null() {
        copy_aces(dacl, acl)?;
    }
    let flags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
    if !have_user
        && unsafe { AddAccessAllowedAceEx(acl, 2, flags, MSYS_INHERIT_ACCESS, user_sid) } == 0
    {
        return Err(last_error("AddAccessAllowedAceEx user"));
    }
    if !have_restricted
        && unsafe { AddAccessAllowedAceEx(acl, 2, flags, MSYS_INHERIT_ACCESS, restricted) } == 0
    {
        return Err(last_error("AddAccessAllowedAceEx restricted"));
    }
    let applied = unsafe {
        SetSecurityInfo(
            object,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            acl.cast(),
            ptr::null_mut(),
        )
    };
    if applied != 0 {
        return Err(win32_error("SetSecurityInfo", applied));
    }
    Ok(())
}

fn object_dacl(object: Handle) -> Result<(Handle, LocalMem), KernelError> {
    let mut owner = ptr::null_mut();
    let mut group = ptr::null_mut();
    let mut dacl = ptr::null_mut();
    let mut sacl = ptr::null_mut();
    let mut sd = ptr::null_mut();
    let got = unsafe {
        GetSecurityInfo(
            object,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            &mut owner,
            &mut group,
            &mut dacl,
            &mut sacl,
            &mut sd,
        )
    };
    if got != 0 {
        return Err(win32_error("GetSecurityInfo", got));
    }
    Ok((dacl, LocalMem(sd)))
}

fn copy_aces(from: Handle, to: *mut u8) -> Result<(), KernelError> {
    let count = u32::from(ace_count(from));
    for index in 0..count {
        let mut ace = ptr::null_mut();
        if unsafe { GetAce(from, index, &mut ace) } == 0 || ace.is_null() {
            return Err(last_error("GetAce"));
        }
        let bytes = ace.cast::<u8>();
        let size = unsafe { u16::from_le_bytes([*bytes.add(2), *bytes.add(3)]) };
        if unsafe { AddAce(to, 2, Dword::MAX, bytes, u32::from(size)) } == 0 {
            return Err(last_error("AddAce"));
        }
    }
    Ok(())
}

fn ace_count(acl: Handle) -> u16 {
    if acl.is_null() {
        return 0;
    }
    let bytes = acl.cast::<u8>();
    unsafe { u16::from_le_bytes([*bytes.add(4), *bytes.add(5)]) }
}

fn acl_has_inherit_allow(acl: Handle, sid: Handle, mask: Dword) -> bool {
    if acl.is_null() || sid.is_null() {
        return false;
    }
    let count = u32::from(ace_count(acl));
    for index in 0..count {
        let mut ace = ptr::null_mut();
        if unsafe { GetAce(acl, index, &mut ace) } == 0 || ace.is_null() {
            return false;
        }
        let bytes = ace.cast::<u8>();
        let size = unsafe { u16::from_le_bytes([*bytes.add(2), *bytes.add(3)]) };
        if size < 20 {
            continue;
        }
        let kind = unsafe { *bytes };
        let flags = unsafe { *bytes.add(1) };
        let ace_mask = unsafe {
            u32::from_le_bytes([*bytes.add(4), *bytes.add(5), *bytes.add(6), *bytes.add(7)])
        };
        if kind != 0 || flags & (OBJECT_INHERIT_ACE as u8) == 0 {
            continue;
        }
        if ace_mask & mask != mask {
            continue;
        }
        if unsafe { EqualSid(bytes.add(8).cast(), sid) } != 0 {
            return true;
        }
    }
    false
}

/// MSYS `user_info::create` opens `SID.1` with `OBJ_OPENIF`. An existing
/// section does not inherit a directory ACE added later.
fn grant_existing_user_section(dir_name: &str, restricted: Handle) -> Result<(), KernelError> {
    let user = current_user_sid()?;
    let text = sid_to_string(&user)?;
    let path = format!(r"{dir_name}\{text}.1");
    match open_section_status(&path, 0x0006_0000) {
        Ok(section) => {
            let result = append_inheritable_section_allows(section, restricted);
            unsafe { CloseHandle(section) };
            result
        }
        Err(status)
            if status == STATUS_OBJECT_NAME_NOT_FOUND || status == STATUS_OBJECT_PATH_NOT_FOUND =>
        {
            Ok(())
        }
        Err(status) => {
            eprintln!("workpen: msys user section open {path} ntstatus {status:#x}");
            Ok(())
        }
    }
}

fn sid_to_string(sid: &[u8]) -> Result<String, KernelError> {
    let mut wide = ptr::null_mut();
    let ok = unsafe { ConvertSidToStringSidW(sid.as_ptr().cast_mut().cast(), &mut wide) };
    if ok == 0 || wide.is_null() {
        return Err(last_error("ConvertSidToStringSidW"));
    }
    let mut len = 0usize;
    unsafe {
        while *wide.add(len) != 0 && len < 200 {
            len += 1;
        }
    }
    let text = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(wide, len) });
    unsafe { LocalFree(wide.cast()) };
    if text.is_empty() {
        return Err(KernelError::Apply("empty SID string".into()));
    }
    Ok(text)
}

fn open_section_status(name: &str, access: u32) -> Result<Handle, i32> {
    let mut wide: Vec<u16> = OsStr::new(name).encode_wide().collect();
    let bytes = u16::try_from(wide.len() * 2).unwrap_or(u16::MAX);
    let mut us = UnicodeString {
        length: bytes,
        maximum_length: bytes,
        buffer: wide.as_mut_ptr(),
    };
    let mut attrs = ObjectAttributes {
        length: std::mem::size_of::<ObjectAttributes>() as u32,
        root_directory: ptr::null_mut(),
        object_name: &mut us,
        attributes: OBJ_CASE_INSENSITIVE,
        security_descriptor: ptr::null_mut(),
        security_quality_of_service: ptr::null_mut(),
    };
    let mut handle = ptr::null_mut();
    let status = unsafe { NtOpenSection(&mut handle, access, &mut attrs) };
    if status != 0 || handle.is_null() {
        return Err(status);
    }
    Ok(handle)
}

fn acl_with_grant(old: Handle, sid: Handle, rights: Dword) -> Result<LocalMem, KernelError> {
    let mut entry = ExplicitAccessW {
        grf_access_permissions: rights,
        grf_access_mode: GRANT_ACCESS,
        grf_inheritance: NO_INHERITANCE,
        trustee: TrusteeW {
            p_multiple_trustee: ptr::null_mut(),
            multiple_trustee_operation: NO_MULTIPLE_TRUSTEE,
            trustee_form: TRUSTEE_IS_SID,
            trustee_type: TRUSTEE_IS_WELL_KNOWN_GROUP,
            ptstr_name: sid,
        },
    };
    let mut new_acl = ptr::null_mut();
    // SAFETY: `entry` lives for the call. `old` may be null.
    let set = unsafe { SetEntriesInAclW(1, &mut entry, old, &mut new_acl) };
    if set != 0 || new_acl.is_null() {
        return Err(win32_error("SetEntriesInAclW", set));
    }
    Ok(LocalMem(new_acl))
}

#[repr(C)]
struct TokenDefaultDacl {
    default_dacl: *mut u8,
}

fn grant_token_default_dacl(token: Handle, sid: Handle) -> Result<(), KernelError> {
    // A null token default does not become a null object DACL.
    // `sec_none` needs an allow that names `S-1-5-12` and the user.
    let user = token_user_sid(token)?;
    let world = WorldSid::new().map_err(|_| KernelError::Apply("world SID".into()))?;
    let mut acl_words = vec![0u32; 64];
    let acl = acl_words.as_mut_ptr().cast::<u8>();
    let mask = GENERIC_ALL | 0x001F_FFFF;
    let ready = unsafe {
        InitializeAcl(acl, (acl_words.len() * 4) as Dword, 2) != 0
            && AddAccessAllowedAce(acl, 2, mask, world.0) != 0
            && AddAccessAllowedAce(acl, 2, mask, user.as_ptr().cast_mut().cast()) != 0
            && AddAccessAllowedAce(acl, 2, mask, sid) != 0
    };
    if !ready {
        return Err(last_error("default DACL"));
    }
    let info = TokenDefaultDacl { default_dacl: acl };
    // SAFETY: `acl_words` stays alive for the call. The kernel copies it.
    let set = unsafe {
        SetTokenInformation(
            token,
            TOKEN_DEFAULT_DACL,
            (&raw const info).cast_mut().cast(),
            std::mem::size_of::<TokenDefaultDacl>() as Dword,
        )
    };
    if set == 0 {
        return Err(last_error("SetTokenInformation TokenDefaultDacl"));
    }
    Ok(())
}

/// Process-lifetime AppContainer for [`super::KernelPolicy::spawn_reexec`].
///
/// The package sid stays valid until process exit. Callers copy the
/// pointer out of the mutex and must not free it.
struct ReexecSlot {
    package: Handle,
    capability: Handle,
    _profile: windows_net::AppContainerProfile,
    _capability: CapabilitySid,
}

// SAFETY: both SIDs are owned by this slot and freed only when the slot
// drops at process exit. The mutex publishes the slot; callers only read
// the pointer values.
unsafe impl Send for ReexecSlot {}

static REEXEC: Mutex<Option<ReexecSlot>> = Mutex::new(None);
static REEXEC_CREATES: AtomicU64 = AtomicU64::new(0);

pub(super) fn reexec_profile_creates() -> u64 {
    REEXEC_CREATES.load(Ordering::Relaxed)
}

struct CapabilitySid(Handle);

impl CapabilitySid {
    /// `S-1-15-3-1`, the internet client capability. Not a profile-read
    /// capability and not private-network.
    fn internet_client() -> Result<Self, KernelError> {
        let authority = SidIdentifierAuthority {
            value: [0, 0, 0, 0, 0, 15],
        };
        let mut sid = ptr::null_mut();
        // SAFETY: `authority` lives for the call. Subauthorities 3, 1 are
        // SECURITY_CAPABILITY_BASE_RID and internet client.
        let ok =
            unsafe { AllocateAndInitializeSid(&authority, 2, 3, 1, 0, 0, 0, 0, 0, 0, &mut sid) };
        if ok == 0 || sid.is_null() {
            return Err(last_error("AllocateAndInitializeSid"));
        }
        Ok(Self(sid))
    }
}

impl Drop for CapabilitySid {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: `self.0` came from AllocateAndInitializeSid.
            unsafe {
                FreeSid(self.0);
            }
            self.0 = ptr::null_mut();
        }
    }
}

fn cached_reexec() -> Result<(Handle, Handle), KernelError> {
    let mut slot = REEXEC
        .lock()
        .map_err(|_| KernelError::Apply("re-exec profile cache is poisoned".into()))?;
    if let Some(existing) = slot.as_ref() {
        return Ok((existing.package, existing.capability));
    }
    let capability = CapabilitySid::internet_client()?;
    let attrs = [windows_net::SidAndAttributes {
        sid: capability.0,
        attributes: windows_net::SE_GROUP_ENABLED,
    }];
    let profile = windows_net::AppContainerProfile::create_network_open(&attrs)
        .map_err(prefix_apply("AppContainer profile"))?;
    let package = profile.sid();
    let cap_sid = capability.0;
    REEXEC_CREATES.fetch_add(1, Ordering::Relaxed);
    *slot = Some(ReexecSlot {
        package,
        capability: cap_sid,
        _profile: profile,
        _capability: capability,
    });
    Ok((package, cap_sid))
}

pub(super) fn spawn_reexec(
    policy: &super::KernelPolicy,
    cmd: &mut Command,
) -> Result<(KernelApply, ExitStatus), KernelError> {
    let (applied, status, _, timed_out) =
        spawn_reexec_io(policy, cmd, None, StdioCapture::Inherit)?;
    if timed_out {
        return Err(KernelError::Timeout);
    }
    Ok((applied, status))
}

pub(super) fn spawn_reexec_output(
    policy: &super::KernelPolicy,
    cmd: &mut Command,
) -> Result<(KernelApply, std::process::Output), KernelError> {
    let (applied, status, output, timed_out) =
        spawn_reexec_io(policy, cmd, None, StdioCapture::Collect)?;
    if timed_out {
        return Err(KernelError::Timeout);
    }
    Ok((
        applied,
        output.unwrap_or_else(|| std::process::Output {
            status,
            stdout: Vec::new(),
            stderr: Vec::new(),
        }),
    ))
}

fn spawn_reexec_io(
    policy: &super::KernelPolicy,
    cmd: &mut Command,
    timeout: Option<Duration>,
    capture: StdioCapture,
) -> Result<(KernelApply, ExitStatus, Option<std::process::Output>, bool), KernelError> {
    let program = resolve_program(cmd.get_program())?;
    let prepared = prepare_reexec(policy, &program)?;
    spawn_prepared(prepared, cmd, timeout, capture)
}

/// AppContainer with outbound network and no WFP BLOCK.
///
/// Profile-secret denies use the package SID, not Everyone, so a missed
/// restore cannot lock the user out of their own directory.
fn prepare_reexec(policy: &super::KernelPolicy, program: &Path) -> Result<Prepared, KernelError> {
    let mut prepared = prepare_write_restricted(policy)?;
    let (package_sid, cap_sid) = cached_reexec()?;
    for path in rw_grant_paths(policy) {
        grant_package_root(&path, package_sid, &mut prepared.acl_guards)
            .map_err(|err| annotate_path(&path, err))?;
    }
    for path in read_grant_paths(policy) {
        grant_package_read(&path, package_sid, &mut prepared.acl_guards)
            .map_err(|err| annotate_path(&path, err))?;
    }
    // Package SID, not Everyone.
    for path in profile_secret_dirs() {
        match deny_dest_ace(&path, package_sid) {
            Ok(guard) => prepared.acl_guards.push(guard),
            Err(err) => return Err(annotate_path(&path, err)),
        }
    }
    grant_program_execute(program, package_sid, &mut prepared.acl_guards)
        .map_err(|err| annotate_path(program, err))?;
    let attrs = [windows_net::SidAndAttributes {
        sid: cap_sid,
        attributes: windows_net::SE_GROUP_ENABLED,
    }];
    prepared.token = wrap_appcontainer_token_caps(prepared.token, package_sid, &attrs)?;
    prepared.helper = None;
    prepared.wfp_skipped = false;
    prepared._net = None;
    Ok(prepared)
}

fn read_grant_paths(policy: &super::KernelPolicy) -> Vec<PathBuf> {
    let rw = rw_grant_paths(policy);
    let mut paths = Vec::new();
    for grant in policy.grants() {
        if grant.access == super::KernelAccess::Read
            && !rw.iter().any(|path| path == &grant.path)
            && !paths.iter().any(|path| path == &grant.path)
        {
            paths.push(grant.path.clone());
        }
    }
    paths
}

fn grant_package_read(
    path: &Path,
    sid: Handle,
    guards: &mut Vec<AclRestore>,
) -> Result<(), KernelError> {
    // Do not call SetNamedSecurityInfo on System32 or Program Files.
    // A runner can block that write until the test is killed.
    if is_system_root_grant(path) {
        return Ok(());
    }
    let inherit = if path.is_dir() {
        SUB_CONTAINERS_AND_OBJECTS_INHERIT
    } else {
        NO_INHERITANCE
    };
    match set_acl_entry(
        path,
        sid,
        GENERIC_READ | GENERIC_EXECUTE,
        GRANT_ACCESS,
        inherit,
    ) {
        Ok(guard) => guards.push(guard),
        // System directories are already readable by ALL APPLICATION
        // PACKAGES. Editing System32's DACL is not required.
        Err(err) if acl_is_access_denied(&err) && is_system_path(path) => {}
        Err(err) => return Err(err),
    }
    Ok(())
}

fn grant_program_execute(
    program: &Path,
    sid: Handle,
    guards: &mut Vec<AclRestore>,
) -> Result<(), KernelError> {
    match set_acl_entry(
        program,
        sid,
        GENERIC_READ | GENERIC_EXECUTE,
        GRANT_ACCESS,
        NO_INHERITANCE,
    ) {
        Ok(guard) => guards.push(guard),
        Err(err) if acl_is_access_denied(&err) && is_system_path(program) => {}
        Err(err) => return Err(err),
    }
    // A directory ACE does not grant existing DLLs. Skip the parent so
    // a large deps folder is not rewritten.
    Ok(())
}

fn annotate_path(path: &Path, err: KernelError) -> KernelError {
    match err {
        KernelError::Apply(msg) => KernelError::Apply(format!("{msg} ({})", path.display())),
        other => other,
    }
}

fn acl_is_access_denied(err: &KernelError) -> bool {
    match err {
        KernelError::Apply(msg) => msg.contains("(win32 5)"),
        _ => false,
    }
}

/// The read roots [`super::system_read_dirs`] adds. Not a subdirectory
/// the host passed itself.
fn is_system_root_grant(path: &Path) -> bool {
    let path = normalize_win_path(path);
    let mut roots = Vec::new();
    if let Some(root) = std::env::var_os("SystemRoot") {
        let root = PathBuf::from(root);
        roots.push(normalize_win_path(&root));
        roots.push(normalize_win_path(&root.join("System32")));
        roots.push(normalize_win_path(&root.join("SysWOW64")));
    }
    for key in ["ProgramFiles", "ProgramFiles(x86)"] {
        if let Some(root) = std::env::var_os(key) {
            roots.push(normalize_win_path(Path::new(&root)));
        }
    }
    roots.iter().any(|root| path == *root)
}

fn is_system_path(path: &Path) -> bool {
    let path = normalize_win_path(path);
    let mut roots = Vec::new();
    if let Some(root) = std::env::var_os("SystemRoot") {
        roots.push(root);
    }
    for key in ["ProgramFiles", "ProgramFiles(x86)"] {
        if let Some(root) = std::env::var_os(key) {
            roots.push(root);
        }
    }
    roots
        .iter()
        .any(|root| dir_prefix(&path, &normalize_win_path(Path::new(root))))
}

/// `\\?\C:\Windows\System32` and `C:\Windows\System32` compare equal.
fn normalize_win_path(path: &Path) -> String {
    let text = path.to_string_lossy().replace('/', "\\");
    let text = text
        .strip_prefix("\\\\?\\UNC\\")
        .map(|rest| format!("\\\\{rest}"))
        .unwrap_or_else(|| {
            text.strip_prefix("\\\\?\\")
                .unwrap_or(text.as_str())
                .to_string()
        });
    text.trim_end_matches('\\').to_ascii_lowercase()
}

fn dir_prefix(path: &str, root: &str) -> bool {
    path == root || path.starts_with(&format!("{root}\\"))
}

/// Exact profile directories from the workspace-jail deny list.
/// Missing directories are skipped. This does not walk the profile.
fn profile_secret_dirs() -> Vec<PathBuf> {
    let Some(home) = std::env::var_os("USERPROFILE") else {
        return Vec::new();
    };
    let home = PathBuf::from(home);
    let mut out = Vec::new();
    for name in [".ssh", ".aws", ".gnupg", ".azure", ".docker", ".kube"] {
        let path = home.join(name);
        if path.is_dir() {
            out.push(path);
        }
    }
    let gh = home.join(".config").join("gh");
    if gh.is_dir() {
        out.push(gh);
    }
    out
}

/// AppContainer plus WFP on `workspace`, without creating a user process.
/// `Ok(true)` is win32 5 (WFP skipped). The helper file is removed on drop.
pub(super) fn probe_wfp_skipped(workspace: &Path) -> Result<bool, KernelError> {
    let policy = super::process_jail(workspace, std::iter::empty::<&Path>())?;
    let prepared = prepare_network_blocked(&policy)?;
    Ok(prepared.wfp_skipped)
}

fn wrap_appcontainer_token(
    restricted: CloseOnDrop,
    package_sid: Handle,
) -> Result<CloseOnDrop, KernelError> {
    wrap_appcontainer_token_caps(restricted, package_sid, &[])
}

fn wrap_appcontainer_token_caps(
    restricted: CloseOnDrop,
    package_sid: Handle,
    capabilities: &[windows_net::SidAndAttributes],
) -> Result<CloseOnDrop, KernelError> {
    match windows_net::create_appcontainer_token(restricted.0, package_sid, capabilities) {
        Ok(handle) => {
            drop(restricted);
            Ok(CloseOnDrop(handle))
        }
        Err(first) => {
            let current = current_primary_token()?;
            match windows_net::create_appcontainer_token(current.0, package_sid, capabilities) {
                Ok(handle) => {
                    drop((restricted, current));
                    Ok(CloseOnDrop(handle))
                }
                Err(second) => Err(KernelError::Apply(format!(
                    "AppContainer token failed ({first}); fallback ({second})"
                ))),
            }
        }
    }
}

fn current_primary_token() -> Result<CloseOnDrop, KernelError> {
    let process_token = open_current_process_token()?;
    duplicate_primary_token(process_token.0)
}

/// One inheritable GRANT on the ReadWrite root. Dest-deny files get an
/// explicit package DENY after this so inherit cannot reopen them.
fn grant_package_root(
    root: &Path,
    sid: Handle,
    guards: &mut Vec<AclRestore>,
) -> Result<(), KernelError> {
    let meta = std::fs::symlink_metadata(root)
        .map_err(|e| KernelError::Apply(format!("package ACE {}: {e}", root.display())))?;
    let is_dir = meta.is_dir() && !meta.file_type().is_symlink();
    let inherit = if is_dir {
        SUB_CONTAINERS_AND_OBJECTS_INHERIT
    } else {
        NO_INHERITANCE
    };
    guards.push(set_acl_entry(
        root,
        sid,
        GENERIC_ALL,
        GRANT_ACCESS,
        inherit,
    )?);
    Ok(())
}

fn prefix_apply(kind: &'static str) -> impl FnOnce(KernelError) -> KernelError {
    move |err| match err {
        KernelError::Apply(msg) => KernelError::Apply(format!("{kind} failed: {msg}")),
        other => other,
    }
}

fn inheritable_std_handle(std_id: Dword, write: bool) -> Result<CloseOnDrop, KernelError> {
    // SAFETY: GetStdHandle is always valid to call.
    let parent = unsafe { GetStdHandle(std_id) };
    if !parent.is_null() && parent != INVALID_HANDLE_VALUE {
        let current = unsafe { GetCurrentProcess() };
        let mut dup = ptr::null_mut();
        // SAFETY: `current` is this process; `parent` is a live std handle.
        let ok = unsafe {
            DuplicateHandle(
                current,
                parent,
                current,
                &mut dup,
                0,
                1,
                DUPLICATE_SAME_ACCESS,
            )
        };
        if ok == 0 {
            return open_nul(write);
        }
        return Ok(CloseOnDrop(dup));
    }
    open_nul(write)
}

fn open_nul(write: bool) -> Result<CloseOnDrop, KernelError> {
    let name = wide_os(OsStr::new("NUL"));
    let mut sa = SecurityAttributes {
        n_length: std::mem::size_of::<SecurityAttributes>() as Dword,
        lp_security_descriptor: ptr::null_mut(),
        b_inherit_handle: 1,
    };
    let access = if write { GENERIC_WRITE } else { GENERIC_READ };
    // SAFETY: `name` is NUL-terminated; `sa` lives for the call.
    let handle = unsafe {
        CreateFileW(
            name.as_ptr(),
            access,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            (&raw mut sa).cast(),
            OPEN_EXISTING,
            0,
            ptr::null_mut(),
        )
    };
    if handle.is_null() || handle == INVALID_HANDLE_VALUE {
        return Err(last_error("CreateFileW"));
    }
    Ok(CloseOnDrop(handle))
}

fn spawn_prepared(
    mut prepared: Prepared,
    cmd: &mut Command,
    timeout: Option<Duration>,
    capture: StdioCapture,
) -> Result<(KernelApply, ExitStatus, Option<std::process::Output>, bool), KernelError> {
    let result = spawn_prepared_child(&mut prepared, cmd, timeout, capture);
    let restore = restore_guards(&mut prepared.acl_guards);
    match (result, restore) {
        (Ok((applied, status, output, timed_out)), Ok(())) => {
            Ok((applied, status, output, timed_out))
        }
        // Deadline plus restore failure must stay Timeout (unit variant).
        (Ok((_, _, _, true)), restore) => combine_spawn_restore(Err(KernelError::Timeout), restore)
            .map(|(applied, status)| (applied, status, None, true)),
        (result, restore) => combine_spawn_restore(
            result.map(|(applied, status, _, _)| (applied, status)),
            restore,
        )
        .map(|(applied, status)| (applied, status, None, false)),
    }
}

fn spawn_prepared_child(
    prepared: &mut Prepared,
    cmd: &mut Command,
    timeout: Option<Duration>,
    capture: StdioCapture,
) -> Result<(KernelApply, ExitStatus, Option<std::process::Output>, bool), KernelError> {
    let (app, mut cmdline, cwd) = match prepared.helper.as_deref() {
        Some(helper) => wrap_command_line(helper, cmd)?,
        None => command_line(cmd)?,
    };
    let mut debug_pipe = false;
    if let Ok(program) = resolve_program(cmd.get_program()) {
        debug_pipe = msys_dll_beside(&program).is_some();
        allow_msys_shared_dirs(
            &program,
            prepared._sid.0,
            prepared._world.0,
            &mut prepared.acl_guards,
        );
    }
    let mut env_block = environment_block(cmd);
    let std_in = inheritable_std_handle(STD_INPUT_HANDLE, false)?;
    let piped = matches!(capture, StdioCapture::Collect | StdioCapture::Forward);
    let (std_out, stdout_read) = if piped {
        inheritable_pipe(true)?
    } else {
        (inheritable_std_handle(STD_OUTPUT_HANDLE, true)?, None)
    };
    let (std_err, stderr_read) = if piped {
        inheritable_pipe(true)?
    } else {
        (inheritable_std_handle(STD_ERROR_HANDLE, true)?, None)
    };
    let forward_dst = if capture == StdioCapture::Forward {
        Some((
            duplicate_std_handle(STD_OUTPUT_HANDLE, true)?,
            duplicate_std_handle(STD_ERROR_HANDLE, true)?,
        ))
    } else {
        None
    };
    let mut startup = StartupInfoW {
        cb: std::mem::size_of::<StartupInfoW>() as Dword,
        lp_reserved: ptr::null_mut(),
        lp_desktop: ptr::null_mut(),
        lp_title: ptr::null_mut(),
        dw_x: 0,
        dw_y: 0,
        dw_x_size: 0,
        dw_y_size: 0,
        dw_x_count_chars: 0,
        dw_y_count_chars: 0,
        dw_fill_attribute: 0,
        dw_flags: STARTF_USESTDHANDLES,
        w_show_window: 0,
        cb_reserved2: 0,
        lp_reserved2: ptr::null_mut(),
        h_std_input: std_in.0,
        h_std_output: std_out.0,
        h_std_error: std_err.0,
    };
    let mut info = ProcessInformation {
        h_process: ptr::null_mut(),
        h_thread: ptr::null_mut(),
        dw_process_id: 0,
        dw_thread_id: 0,
    };
    let cwd_ptr = cwd.as_ref().map_or(ptr::null(), |c| c.as_ptr());
    // SAFETY: token is a primary write-restricted token; buffers are NUL-terminated
    // and live for the call. cmdline is writable as CreateProcessAsUserW requires.
    let created = unsafe {
        CreateProcessAsUserW(
            prepared.token.0,
            app.as_ptr(),
            cmdline.as_mut_ptr(),
            ptr::null_mut(),
            ptr::null_mut(),
            1,
            CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT,
            env_block.as_mut_ptr().cast(),
            cwd_ptr,
            &mut startup,
            &mut info,
        )
    };
    if created == 0 {
        return Err(last_error("CreateProcessAsUserW"));
    }
    drop((std_in, std_out, std_err));
    let process = CloseOnDrop(info.h_process);
    let thread = CloseOnDrop(info.h_thread);
    // Drain capture pipes before the child runs so a large write cannot
    // fill the pipe and block WaitForSingleObject.
    let forward_stop = Arc::new(AtomicBool::new(false));
    let forward_threads = Arc::new(Mutex::new(Vec::<CloseOnDrop>::new()));
    let (stdout_drain, stderr_drain, stdout_fwd, stderr_fwd) = match (capture, forward_dst) {
        (StdioCapture::Collect, _) => (
            stdout_read.map(drain_pipe),
            stderr_read.map(drain_pipe),
            None,
            None,
        ),
        (StdioCapture::Forward, Some((parent_out, parent_err))) => (
            None,
            None,
            stdout_read.map(|h| {
                drain_forward(
                    h,
                    parent_out,
                    Arc::clone(&forward_stop),
                    Arc::clone(&forward_threads),
                )
            }),
            stderr_read.map(|h| {
                drain_forward(
                    h,
                    parent_err,
                    Arc::clone(&forward_stop),
                    Arc::clone(&forward_threads),
                )
            }),
        ),
        (StdioCapture::Forward, None) | (StdioCapture::Inherit, _) => (None, None, None, None),
    };
    // SAFETY: `job` is our job object; `process` is the new suspended process.
    let assigned = unsafe { AssignProcessToJobObject(prepared.job.0, process.0) };
    if assigned == 0 {
        // SAFETY: process is still suspended; terminate so it never runs unsandboxed.
        unsafe {
            TerminateProcess(process.0, 1);
        }
        let _ = join_drain(stdout_drain);
        let _ = join_drain(stderr_drain);
        join_copy(stdout_fwd);
        join_copy(stderr_fwd);
        return Err(last_error("AssignProcessToJobObject"));
    }
    relax_child_bno(process.0, prepared._sid.0, prepared._world.0);
    // CreateProcessAsUser duplicates the token. Lock that copy, not the
    // handle we passed in, or MSYS still replaces the default DACL.
    if let Err(err) = lock_suspended_token(process.0, prepared._sid.0) {
        unsafe {
            TerminateProcess(process.0, 1);
        }
        let _ = join_drain(stdout_drain);
        let _ = join_drain(stderr_drain);
        join_copy(stdout_fwd);
        join_copy(stderr_fwd);
        return Err(err);
    }
    if let Err(err) = deny_process_write_dac(process.0) {
        unsafe {
            TerminateProcess(process.0, 1);
        }
        let _ = join_drain(stdout_drain);
        let _ = join_drain(stderr_drain);
        join_copy(stdout_fwd);
        join_copy(stderr_fwd);
        return Err(err);
    }
    // `sigproc_init` runs from the MSYS `DllMain`, before the entry point.
    // Patch `NtCreateNamedPipeFile` while the process is still suspended.
    if debug_pipe {
        if let Err(err) = install_ntdll_pipe_hook(process.0, prepared._sid.0) {
            eprintln!("workpen: pipe hook skipped: {err}");
        }
    }
    // SAFETY: thread is the primary thread of the suspended process.
    let resumed = unsafe { ResumeThread(thread.0) };
    if resumed == Dword::MAX {
        unsafe {
            TerminateProcess(process.0, 1);
        }
        let _ = join_drain(stdout_drain);
        let _ = join_drain(stderr_drain);
        join_copy(stdout_fwd);
        join_copy(stderr_fwd);
        return Err(last_error("ResumeThread"));
    }
    // INFINITE is 0xFFFF_FFFF. Cap finite waits one below that.
    let wait_ms = match timeout {
        None => INFINITE,
        Some(d) => d.as_millis().min(u32::MAX as u128 - 1) as Dword,
    };
    // SAFETY: process handle stays valid until we return.
    let started = std::time::Instant::now();
    let wait = unsafe { WaitForSingleObject(process.0, wait_ms) };
    let mut timed_out = wait == WAIT_TIMEOUT;
    if timed_out {
        drop(std::mem::replace(
            &mut prepared.job,
            CloseOnDrop(ptr::null_mut()),
        ));
        // SAFETY: job close requests KILL_ON_JOB_CLOSE.
        let mut reap = unsafe { WaitForSingleObject(process.0, 5_000) };
        if reap != WAIT_OBJECT_0 {
            unsafe {
                TerminateProcess(process.0, 1);
            }
            reap = unsafe { WaitForSingleObject(process.0, 5_000) };
        }
        if reap != WAIT_OBJECT_0 {
            return Err(KernelError::Timeout);
        }
    } else if wait == WAIT_FAILED || wait != WAIT_OBJECT_0 {
        return Err(last_error("WaitForSingleObject"));
    }
    let mut code: Dword = 1;
    // SAFETY: process has exited; exit code pointer is valid.
    let got = unsafe { GetExitCodeProcess(process.0, &mut code) };
    if got == 0 {
        let _ = join_drain(stdout_drain);
        let _ = join_drain(stderr_drain);
        let _ = finish_forward(
            timed_out,
            &forward_stop,
            &forward_threads,
            stdout_fwd,
            stderr_fwd,
            started,
            timeout,
        );
        if timed_out {
            return Err(KernelError::Timeout);
        }
        return Err(last_error("GetExitCodeProcess"));
    }
    let applied = if prepared.wfp_skipped {
        KernelApply::WfpSkipped
    } else {
        KernelApply::Applied
    };
    let output = if capture == StdioCapture::Collect {
        Some(std::process::Output {
            status: ExitStatus::from_raw(code),
            stdout: join_drain(stdout_drain),
            stderr: join_drain(stderr_drain),
        })
    } else {
        drop((stdout_drain, stderr_drain));
        timed_out |= finish_forward(
            timed_out,
            &forward_stop,
            &forward_threads,
            stdout_fwd,
            stderr_fwd,
            started,
            timeout,
        );
        None
    };
    Ok((applied, ExitStatus::from_raw(code), output, timed_out))
}

fn inheritable_pipe(
    write_for_child: bool,
) -> Result<(CloseOnDrop, Option<CloseOnDrop>), KernelError> {
    let mut sa = SecurityAttributes {
        n_length: std::mem::size_of::<SecurityAttributes>() as Dword,
        lp_security_descriptor: ptr::null_mut(),
        b_inherit_handle: 1,
    };
    let mut read = ptr::null_mut();
    let mut write = ptr::null_mut();
    // SAFETY: sa lives for the call; out handles are written by CreatePipe.
    let ok = unsafe { CreatePipe(&mut read, &mut write, &mut sa, 0) };
    if ok == 0 {
        return Err(last_error("CreatePipe"));
    }
    let read = CloseOnDrop(read);
    let write = CloseOnDrop(write);
    if write_for_child {
        // Parent keeps the read end; do not inherit it into the child.
        // SAFETY: read is a live pipe handle we own.
        let cleared = unsafe { SetHandleInformation(read.0, HANDLE_FLAG_INHERIT, 0) };
        if cleared == 0 {
            return Err(last_error("SetHandleInformation"));
        }
        Ok((write, Some(read)))
    } else {
        let cleared = unsafe { SetHandleInformation(write.0, HANDLE_FLAG_INHERIT, 0) };
        if cleared == 0 {
            return Err(last_error("SetHandleInformation"));
        }
        Ok((read, Some(write)))
    }
}

fn read_all(handle: CloseOnDrop) -> Vec<u8> {
    let mut out = Vec::new();
    let mut buf = [0u8; 4096];
    loop {
        let mut n: Dword = 0;
        // SAFETY: handle is a readable pipe; buf is valid.
        let ok = unsafe {
            ReadFile(
                handle.0,
                buf.as_mut_ptr(),
                buf.len() as Dword,
                &mut n,
                ptr::null_mut(),
            )
        };
        if ok == 0 || n == 0 {
            break;
        }
        out.extend_from_slice(&buf[..n as usize]);
    }
    out
}

fn drain_pipe(handle: CloseOnDrop) -> std::thread::JoinHandle<Vec<u8>> {
    std::thread::spawn(move || read_all(handle))
}

fn drain_forward(
    src: CloseOnDrop,
    dst: CloseOnDrop,
    stop: Arc<AtomicBool>,
    threads: Arc<Mutex<Vec<CloseOnDrop>>>,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || copy_pipe(src, dst, &stop, &threads))
}

fn register_forward_thread(threads: &Mutex<Vec<CloseOnDrop>>) {
    let mut dup = ptr::null_mut();
    // SAFETY: GetCurrentThread is a pseudo-handle. DuplicateHandle makes
    // a real handle this thread owns; the pseudo-handle must not be closed.
    let ok = unsafe {
        DuplicateHandle(
            GetCurrentProcess(),
            GetCurrentThread(),
            GetCurrentProcess(),
            &mut dup,
            0,
            0,
            DUPLICATE_SAME_ACCESS,
        )
    };
    if ok == 0 {
        return;
    }
    let mut guard = threads.lock().unwrap_or_else(|err| err.into_inner());
    guard.push(CloseOnDrop(dup));
}

fn forward_done(
    stdout_fwd: &Option<std::thread::JoinHandle<()>>,
    stderr_fwd: &Option<std::thread::JoinHandle<()>>,
) -> bool {
    let stdout_done = match stdout_fwd {
        None => true,
        Some(handle) => handle.is_finished(),
    };
    let stderr_done = match stderr_fwd {
        None => true,
        Some(handle) => handle.is_finished(),
    };
    stdout_done && stderr_done
}

fn finish_forward(
    timed_out: bool,
    stop: &AtomicBool,
    threads: &Mutex<Vec<CloseOnDrop>>,
    stdout_fwd: Option<std::thread::JoinHandle<()>>,
    stderr_fwd: Option<std::thread::JoinHandle<()>>,
    started: std::time::Instant,
    timeout: Option<Duration>,
) -> bool {
    let mut forced = timed_out;
    if let Some(limit) = timeout {
        let deadline = started + limit;
        while !forward_done(&stdout_fwd, &stderr_fwd) {
            if std::time::Instant::now() >= deadline {
                forced = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }
    if forced {
        stop.store(true, Ordering::Relaxed);
        // Cancel is a no-op unless the thread is already inside ReadFile
        // or WriteFile. Repeat it until the copy is done so a check of
        // `stop` that lost the race still unblocks.
        for _ in 0..500 {
            let registered = {
                let guard = threads.lock().unwrap_or_else(|err| err.into_inner());
                for handle in guard.iter() {
                    // SAFETY: handle is the duplicated copy thread.
                    unsafe {
                        CancelSynchronousIo(handle.0);
                    }
                }
                guard.len()
            };
            let stdout_done = match &stdout_fwd {
                None => true,
                Some(handle) => handle.is_finished(),
            };
            let stderr_done = match &stderr_fwd {
                None => true,
                Some(handle) => handle.is_finished(),
            };
            if (stdout_done && stderr_done) || registered == 0 {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
    }
    join_copy(stdout_fwd);
    join_copy(stderr_fwd);
    forced
}

fn join_drain(handle: Option<std::thread::JoinHandle<Vec<u8>>>) -> Vec<u8> {
    handle.and_then(|h| h.join().ok()).unwrap_or_default()
}

fn join_copy(handle: Option<std::thread::JoinHandle<()>>) {
    if let Some(h) = handle {
        let _ = h.join();
    }
}

fn duplicate_std_handle(std_id: Dword, write: bool) -> Result<CloseOnDrop, KernelError> {
    // SAFETY: GetStdHandle is always valid to call.
    let parent = unsafe { GetStdHandle(std_id) };
    if parent.is_null() || parent == INVALID_HANDLE_VALUE {
        return open_nul(write);
    }
    let current = unsafe { GetCurrentProcess() };
    let mut dup = ptr::null_mut();
    // SAFETY: parent is this process's std handle; inherit=0 so the child
    // does not also get this copy (it has the pipe write end).
    let ok = unsafe {
        DuplicateHandle(
            current,
            parent,
            current,
            &mut dup,
            0,
            0,
            DUPLICATE_SAME_ACCESS,
        )
    };
    if ok == 0 {
        return open_nul(write);
    }
    Ok(CloseOnDrop(dup))
}

fn copy_pipe(
    src: CloseOnDrop,
    dst: CloseOnDrop,
    stop: &AtomicBool,
    threads: &Mutex<Vec<CloseOnDrop>>,
) {
    register_forward_thread(threads);
    if stop.load(Ordering::Relaxed) {
        return;
    }
    let mut buf = [0u8; 16 * 1024];
    loop {
        if stop.load(Ordering::Relaxed) {
            break;
        }
        let mut n: Dword = 0;
        // SAFETY: src is a readable pipe we own.
        let ok = unsafe {
            ReadFile(
                src.0,
                buf.as_mut_ptr(),
                buf.len() as Dword,
                &mut n,
                ptr::null_mut(),
            )
        };
        if ok == 0 || n == 0 || stop.load(Ordering::Relaxed) {
            break;
        }
        let mut wrote: Dword = 0;
        // SAFETY: dst is a duplicated parent std handle we own.
        let ok = unsafe { WriteFile(dst.0, buf.as_ptr(), n, &mut wrote, ptr::null_mut()) };
        if ok == 0 {
            break;
        }
    }
}

fn dest_deny_paths(policy: &KernelPolicy) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    for deny in policy.dest_denies() {
        if !paths.iter().any(|p| p == &deny.path) {
            paths.push(deny.path.clone());
        }
    }
    paths
}

fn deny_dest_aces(paths: &[PathBuf], sid: Handle) -> Result<Vec<AclRestore>, KernelError> {
    let mut guards = Vec::with_capacity(paths.len());
    for path in paths {
        if !path.exists() {
            continue;
        }
        match deny_dest_ace(path, sid) {
            Ok(guard) => guards.push(guard),
            Err(err) => {
                let _ = restore_guards(&mut guards);
                return Err(err);
            }
        }
    }
    Ok(guards)
}

#[cfg(test)]
thread_local! {
    static TEST_ACE_FAIL_ON: std::cell::RefCell<Option<PathBuf>> =
        const { std::cell::RefCell::new(None) };
}

#[cfg(test)]
pub(super) fn fail_next_ace_on(path: PathBuf) {
    TEST_ACE_FAIL_ON.with(|c| *c.borrow_mut() = Some(path));
}

fn deny_dest_ace(path: &Path, sid: Handle) -> Result<AclRestore, KernelError> {
    #[cfg(test)]
    if TEST_ACE_FAIL_ON.with(|c| {
        let hit = c.borrow().as_ref().is_some_and(|p| p.as_path() == path);
        if hit {
            *c.borrow_mut() = None;
        }
        hit
    }) {
        return Err(KernelError::Apply("test dest-deny ACE fail".into()));
    }
    let inherit = if path.is_dir() {
        SUB_CONTAINERS_AND_OBJECTS_INHERIT
    } else {
        NO_INHERITANCE
    };
    set_acl_entry(path, sid, GENERIC_ALL, DENY_ACCESS, inherit)
}

fn rw_grant_paths(policy: &KernelPolicy) -> Vec<PathBuf> {
    let mut paths = Vec::new();
    for grant in policy.grants() {
        if grant.access == KernelAccess::ReadWrite && !paths.iter().any(|p| p == &grant.path) {
            paths.push(grant.path.clone());
        }
    }
    paths
}

fn grant_write_aces(paths: &[PathBuf], sid: Handle) -> Result<Vec<AclRestore>, KernelError> {
    let mut guards = Vec::with_capacity(paths.len());
    for path in paths {
        match grant_write_ace(path, sid) {
            Ok(guard) => guards.push(guard),
            Err(err) => {
                let _ = restore_guards(&mut guards);
                return Err(err);
            }
        }
    }
    Ok(guards)
}

fn grant_write_ace(path: &Path, sid: Handle) -> Result<AclRestore, KernelError> {
    set_acl_entry(
        path,
        sid,
        GENERIC_ALL,
        GRANT_ACCESS,
        SUB_CONTAINERS_AND_OBJECTS_INHERIT,
    )
}

fn set_acl_entry(
    path: &Path,
    sid: Handle,
    permissions: Dword,
    mode: u32,
    inheritance: Dword,
) -> Result<AclRestore, KernelError> {
    set_named_ace(
        &wide_path(path),
        SE_FILE_OBJECT,
        sid,
        permissions,
        mode,
        inheritance,
    )
}

fn set_named_ace(
    wide: &[u16],
    object_type: u32,
    sid: Handle,
    permissions: Dword,
    mode: u32,
    inheritance: Dword,
) -> Result<AclRestore, KernelError> {
    let mut wide = wide.to_vec();
    let mut owner = ptr::null_mut();
    let mut group = ptr::null_mut();
    let mut dacl = ptr::null_mut();
    let mut sacl = ptr::null_mut();
    let mut sd = ptr::null_mut();
    // SAFETY: `wide` is a NUL-terminated path; out pointers are written by the API.
    let got = unsafe {
        GetNamedSecurityInfoW(
            wide.as_ptr(),
            object_type,
            DACL_SECURITY_INFORMATION,
            &mut owner,
            &mut group,
            &mut dacl,
            &mut sacl,
            &mut sd,
        )
    };
    if got != 0 {
        return Err(win32_error("GetNamedSecurityInfoW", got));
    }
    let sd = LocalMem(sd);
    let mut entry = ExplicitAccessW {
        grf_access_permissions: permissions,
        grf_access_mode: mode,
        grf_inheritance: inheritance,
        trustee: TrusteeW {
            p_multiple_trustee: ptr::null_mut(),
            multiple_trustee_operation: NO_MULTIPLE_TRUSTEE,
            trustee_form: TRUSTEE_IS_SID,
            trustee_type: TRUSTEE_IS_WELL_KNOWN_GROUP,
            ptstr_name: sid,
        },
    };
    let mut new_acl = ptr::null_mut();
    // SAFETY: `entry` lives for the call; `dacl` is the current DACL inside `sd`.
    let set = unsafe { SetEntriesInAclW(1, &mut entry, dacl, &mut new_acl) };
    if set != 0 {
        return Err(win32_error("SetEntriesInAclW", set));
    }
    let new_acl = LocalMem(new_acl);
    // SAFETY: `wide` is a writable NUL-terminated path; `new_acl` is a valid ACL.
    let applied = unsafe {
        SetNamedSecurityInfoW(
            wide.as_mut_ptr(),
            object_type,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            new_acl.0,
            ptr::null_mut(),
        )
    };
    if applied != 0 {
        return Err(win32_error("SetNamedSecurityInfoW", applied));
    }
    Ok(AclRestore {
        path: wide,
        object_type,
        _sd: sd,
        dacl,
        restored: false,
    })
}

fn open_current_process_token() -> Result<CloseOnDrop, KernelError> {
    let mut process_token = ptr::null_mut();
    // SAFETY: current process handle is valid.
    let opened =
        unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_PRIMARY_MASK, &mut process_token) };
    if opened == 0 {
        return Err(last_error("OpenProcessToken"));
    }
    Ok(CloseOnDrop(process_token))
}

fn create_restricted_token(process_token: Handle, sid: Handle) -> Result<CloseOnDrop, KernelError> {
    let restrict = SidAndAttributes { sid, attributes: 0 };
    let mut restricted = ptr::null_mut();
    // SAFETY: `process_token` is an open process token; `restrict` lives for the call.
    let ok = unsafe {
        CreateRestrictedToken(
            process_token,
            DISABLE_MAX_PRIVILEGE | WRITE_RESTRICTED,
            0,
            ptr::null(),
            0,
            ptr::null(),
            1,
            &restrict,
            &mut restricted,
        )
    };
    if ok == 0 {
        return Err(last_error("CreateRestrictedToken"));
    }
    Ok(CloseOnDrop(restricted))
}

fn duplicate_primary_token(token: Handle) -> Result<CloseOnDrop, KernelError> {
    let mut primary = ptr::null_mut();
    // SAFETY: `token` is an open token; we request a primary token.
    let dup = unsafe {
        DuplicateTokenEx(
            token,
            TOKEN_PRIMARY_MASK,
            ptr::null_mut(),
            SECURITY_IMPERSONATION,
            TOKEN_PRIMARY,
            &mut primary,
        )
    };
    if dup == 0 {
        return Err(last_error("DuplicateTokenEx"));
    }
    Ok(CloseOnDrop(primary))
}

fn create_write_restricted_token(sid: Handle) -> Result<CloseOnDrop, KernelError> {
    let process_token = open_current_process_token()?;
    let restricted = create_restricted_token(process_token.0, sid)?;
    let primary = duplicate_primary_token(restricted.0)?;
    if let Err(err) = grant_token_default_dacl(primary.0, sid) {
        eprintln!("workpen: token default DACL skipped: {err}");
    }
    Ok(primary)
}

fn lock_suspended_token(process: Handle, restricted: Handle) -> Result<(), KernelError> {
    let mut raw = ptr::null_mut();
    // READ_CONTROL | WRITE_DAC, plus the rights SetTokenInformation needs.
    // The child has not run, so this open still sees the kernel's default
    // token DACL. MSYS later opens the same token with MAXIMUM_ALLOWED.
    let opened = unsafe {
        OpenProcessToken(
            process,
            TOKEN_QUERY | TOKEN_ADJUST_DEFAULT | 0x0006_0000,
            &mut raw,
        )
    };
    if opened == 0 {
        return Err(last_error("OpenProcessToken child"));
    }
    let token = CloseOnDrop(raw);
    grant_token_default_dacl(token.0, restricted)?;
    deny_token_adjust_default(token.0)
}

fn deny_token_adjust_default(token: Handle) -> Result<(), KernelError> {
    let user = token_user_sid(token)?;
    let world = WorldSid::new().map_err(|_| KernelError::Apply("world SID".into()))?;
    let mut acl_words = vec![0u32; 64];
    let acl = acl_words.as_mut_ptr().cast::<u8>();
    // Deny the rights MSYS uses to replace the default DACL, and the
    // rights that would put TOKEN_ADJUST_DEFAULT back on this token.
    let deny_mask = TOKEN_ADJUST_DEFAULT | 0x0004_0000 | 0x0008_0000;
    let allow_mask = 0x000F_01FF & !deny_mask;
    let ready = unsafe {
        InitializeAcl(acl, (acl_words.len() * 4) as Dword, 2) != 0
            && AddAccessDeniedAce(acl, 2, deny_mask, world.0) != 0
            && AddAccessAllowedAce(acl, 2, allow_mask, user.as_ptr().cast_mut().cast()) != 0
    };
    if !ready {
        return Err(last_error("token DACL"));
    }
    let set = unsafe {
        SetSecurityInfo(
            token,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            acl.cast(),
            ptr::null_mut(),
        )
    };
    if set != 0 {
        return Err(win32_error("SetSecurityInfo token", set));
    }
    Ok(())
}

fn deny_process_write_dac(process: Handle) -> Result<(), KernelError> {
    // MSYS replaces the process DACL with `sec_user`, which has no
    // S-1-5-12. `shared.5` still opens because that call passes an
    // explicit null DACL. `sec_none` does not. Deny WRITE_DAC so the
    // replacement fails and MSYS continues.
    let user = current_user_sid()?;
    let world = WorldSid::new().map_err(|_| KernelError::Apply("world SID".into()))?;
    let mut acl_words = vec![0u32; 64];
    let acl = acl_words.as_mut_ptr().cast::<u8>();
    let deny = 0x0004_0000u32;
    let allow = 0x001F_FFFF & !deny;
    let ready = unsafe {
        InitializeAcl(acl, (acl_words.len() * 4) as Dword, 2) != 0
            && AddAccessDeniedAce(acl, 2, deny, world.0) != 0
            && AddAccessAllowedAce(acl, 2, allow, user.as_ptr().cast_mut().cast()) != 0
    };
    if !ready {
        return Err(last_error("process DACL"));
    }
    let set = unsafe {
        SetSecurityInfo(
            process,
            SE_KERNEL_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            acl.cast(),
            ptr::null_mut(),
        )
    };
    if set != 0 {
        return Err(win32_error("SetSecurityInfo process", set));
    }
    Ok(())
}

fn create_kill_job() -> Result<CloseOnDrop, KernelError> {
    // SAFETY: unnamed job; attributes are NULL.
    let job = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null()) };
    if job.is_null() || job == INVALID_HANDLE_VALUE {
        return Err(last_error("CreateJobObjectW"));
    }
    let job = CloseOnDrop(job);
    let mut info = JobobjectExtendedLimitInformation {
        basic_limit_information: JobobjectBasicLimitInformation {
            per_process_user_time_limit: 0,
            per_job_user_time_limit: 0,
            limit_flags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
            minimum_working_set_size: 0,
            maximum_working_set_size: 0,
            active_process_limit: 0,
            affinity: 0,
            priority_class: 0,
            scheduling_class: 0,
        },
        io_info: IoCounters {
            read_operation_count: 0,
            write_operation_count: 0,
            other_operation_count: 0,
            read_transfer_count: 0,
            write_transfer_count: 0,
            other_transfer_count: 0,
        },
        process_memory_limit: 0,
        job_memory_limit: 0,
        peak_process_memory_used: 0,
        peak_job_memory_used: 0,
    };
    // SAFETY: `info` matches JobObjectExtendedLimitInformation.
    let set = unsafe {
        SetInformationJobObject(
            job.0,
            JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
            (&raw mut info).cast(),
            std::mem::size_of::<JobobjectExtendedLimitInformation>() as Dword,
        )
    };
    if set == 0 {
        return Err(last_error("SetInformationJobObject"));
    }
    let mut ui = JobobjectBasicUiRestrictions {
        ui_restrictions_class: UI_RESTRICTIONS,
    };
    let ui_set = unsafe {
        SetInformationJobObject(
            job.0,
            JOB_OBJECT_BASIC_UI_RESTRICTIONS,
            (&raw mut ui).cast(),
            std::mem::size_of::<JobobjectBasicUiRestrictions>() as Dword,
        )
    };
    if ui_set == 0 {
        return Err(last_error("SetInformationJobObject UI"));
    }
    Ok(job)
}

fn environment_block(cmd: &mut Command) -> Vec<u16> {
    let pairs = super::child_env_pairs(cmd);
    let mut out = Vec::new();
    for (key, value) in pairs {
        out.extend(key.encode_wide());
        out.push(u16::from(b'='));
        out.extend(value.encode_wide());
        out.push(0);
    }
    if out.is_empty() {
        out.push(0);
    }
    out.push(0);
    out
}

fn wrap_command_line(
    helper: &Path,
    cmd: &Command,
) -> Result<(Vec<u16>, Vec<u16>, Option<Vec<u16>>), KernelError> {
    let (_orig_app, orig_line, cwd) = command_line(cmd)?;
    let mut line = Vec::new();
    append_quoted(&mut line, helper.as_os_str());
    line.extend_from_slice(&[0x20, 0x2d, 0x2d, 0x20]);
    let orig = orig_line
        .last()
        .is_some_and(|c| *c == 0)
        .then(|| &orig_line[..orig_line.len() - 1])
        .unwrap_or(orig_line.as_slice());
    line.extend_from_slice(orig);
    line.push(0);
    Ok((wide_path(helper), line, cwd))
}

fn command_line(cmd: &Command) -> Result<(Vec<u16>, Vec<u16>, Option<Vec<u16>>), KernelError> {
    let program = resolve_program(cmd.get_program())?;
    let mut line = Vec::new();
    append_quoted(&mut line, OsStr::new(&program));
    for arg in cmd.get_args() {
        line.push(0x20);
        append_quoted(&mut line, arg);
    }
    line.push(0);
    let cwd = cmd.get_current_dir().map(wide_path);
    Ok((wide_path(Path::new(&program)), line, cwd))
}

fn resolve_program(program: &OsStr) -> Result<PathBuf, KernelError> {
    let path = Path::new(program);
    if path.components().count() > 1 || path.is_absolute() {
        if path.exists() {
            return Ok(path.to_path_buf());
        }
        return Err(KernelError::Apply(format!(
            "{}: not found",
            program.to_string_lossy()
        )));
    }
    let name = wide_os(program);
    let ext: Vec<u16> = OsStr::new(".exe")
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let mut buf = vec![0u16; 32768];
    // SAFETY: `name` and `ext` are NUL-terminated; `buf` is the output.
    let n = unsafe {
        SearchPathW(
            ptr::null(),
            name.as_ptr(),
            ext.as_ptr(),
            buf.len() as Dword,
            buf.as_mut_ptr(),
            ptr::null_mut(),
        )
    };
    if n == 0 || n as usize >= buf.len() {
        if path.exists() {
            return Ok(path.to_path_buf());
        }
        return Err(KernelError::Apply(format!(
            "{}: not found",
            program.to_string_lossy()
        )));
    }
    Ok(PathBuf::from(OsString::from_wide(&buf[..n as usize])))
}

fn append_quoted(out: &mut Vec<u16>, arg: &OsStr) {
    let wide: Vec<u16> = arg.encode_wide().collect();
    let needs_quotes = wide
        .iter()
        .any(|&c| c == 0x20 || c == 0x09 || c == 0x22 || c == 0);
    if !needs_quotes && !wide.is_empty() {
        out.extend_from_slice(&wide);
        return;
    }
    out.push(0x22);
    let mut slashes = 0usize;
    for &c in &wide {
        if c == 0x5c {
            slashes += 1;
            continue;
        }
        if c == 0x22 {
            out.extend(std::iter::repeat_n(0x5c, slashes * 2 + 1));
            out.push(0x22);
        } else {
            out.extend(std::iter::repeat_n(0x5c, slashes));
            out.push(c);
        }
        slashes = 0;
    }
    out.extend(std::iter::repeat_n(0x5c, slashes * 2));
    out.push(0x22);
}

#[cfg(test)]
mod ace_tests {
    use super::*;
    use std::os::windows::ffi::OsStrExt;
    use std::path::Path;

    const ACCESS_DENIED_ACE_TYPE: u8 = 0x01;
    const ACL_SIZE_INFORMATION: u32 = 2;

    #[repr(C)]
    #[allow(dead_code)]
    struct AceHeader {
        ace_type: u8,
        ace_flags: u8,
        ace_size: u16,
    }

    #[repr(C)]
    #[allow(dead_code)]
    struct AccessDeniedAce {
        header: AceHeader,
        mask: Dword,
        sid_start: Dword,
    }

    #[repr(C)]
    #[allow(dead_code)]
    struct AclSizeInformation {
        ace_count: Dword,
        acl_bytes_in_use: Dword,
        acl_bytes_free: Dword,
    }

    #[link(name = "advapi32")]
    unsafe extern "system" {
        fn GetAclInformation(
            p_acl: Handle,
            p_acl_information: *mut core::ffi::c_void,
            n_acl_information_length: Dword,
            dw_acl_information_class: u32,
        ) -> Bool;
        fn GetAce(p_acl: Handle, dw_ace_index: Dword, p_ace: *mut Handle) -> Bool;
        fn EqualSid(p_sid1: Handle, p_sid2: Handle) -> Bool;
    }

    fn dacl_has_deny_ace(path: &Path, sid: Handle) -> bool {
        let wide = wide_path(path);
        let mut owner = ptr::null_mut();
        let mut group = ptr::null_mut();
        let mut dacl = ptr::null_mut();
        let mut sacl = ptr::null_mut();
        let mut sd = ptr::null_mut();
        // SAFETY: `wide` is a NUL-terminated path; out pointers are written by the API.
        let got = unsafe {
            GetNamedSecurityInfoW(
                wide.as_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION,
                &mut owner,
                &mut group,
                &mut dacl,
                &mut sacl,
                &mut sd,
            )
        };
        assert_eq!(got, 0, "GetNamedSecurityInfoW first dest failed ({got})");
        let _sd = LocalMem(sd);
        if dacl.is_null() {
            return false;
        }
        let mut info = AclSizeInformation {
            ace_count: 0,
            acl_bytes_in_use: 0,
            acl_bytes_free: 0,
        };
        // SAFETY: `dacl` is the DACL inside `_sd`; `info` matches AclSizeInformation.
        let queried = unsafe {
            GetAclInformation(
                dacl,
                (&raw mut info).cast(),
                std::mem::size_of::<AclSizeInformation>() as Dword,
                ACL_SIZE_INFORMATION,
            )
        };
        assert_ne!(queried, 0, "GetAclInformation first dest");
        for i in 0..info.ace_count {
            let mut ace = ptr::null_mut();
            // SAFETY: `dacl` is valid for AceCount entries; `ace` is written by GetAce.
            let found = unsafe { GetAce(dacl, i, &mut ace) };
            assert_ne!(found, 0, "GetAce {i}");
            // SAFETY: GetAce returned a pointer into `dacl`.
            let header = unsafe { &*ace.cast::<AceHeader>() };
            if header.ace_type != ACCESS_DENIED_ACE_TYPE {
                continue;
            }
            // SAFETY: ACCESS_DENIED_ACE layout; SidStart is the SID bytes.
            let ace_sid =
                unsafe { (&raw const (*ace.cast::<AccessDeniedAce>()).sid_start) as Handle };
            // SAFETY: both pointers are SIDs (ACE SidStart and RestrictedSid).
            if unsafe { EqualSid(ace_sid, sid) } != 0 {
                return true;
            }
        }
        false
    }

    #[test]
    fn verbatim_system32_is_a_system_path() {
        let root = std::env::var("SystemRoot").expect("SystemRoot");
        let verbatim = format!(r"\\?\{root}\System32");
        assert!(
            super::is_system_path(Path::new(&verbatim)),
            "{verbatim} should match SystemRoot"
        );
        assert!(
            super::is_system_root_grant(Path::new(&verbatim)),
            "{verbatim} is a system read root"
        );
        let nested = format!(r"\\?\{root}\System32\drivers");
        assert!(
            !super::is_system_root_grant(Path::new(&nested)),
            "a subdirectory still needs its own ACE"
        );
        assert!(!super::is_system_path(Path::new(
            r"C:\workpen-not-a-system-dir"
        )));
    }

    #[test]
    fn deny_dest_aces_rolls_back_on_second_path_error() {
        let dir = tempfile::TempDir::new().expect("ws");
        let first = dir.path().join("a.env");
        let second = dir.path().join("b.env");
        std::fs::write(&first, "1").expect("first");
        std::fs::write(&second, "2").expect("second");
        let sid = RestrictedSid::new().expect("sid");
        fail_next_ace_on(second.clone());
        let err = match deny_dest_aces(&[first.clone(), second], sid.0) {
            Err(err) => err,
            Ok(_) => panic!("second ACE must fail"),
        };
        assert!(
            matches!(err, KernelError::Apply(_)),
            "mid-loop ACE fail is Apply: {err}"
        );
        assert!(
            !dacl_has_deny_ace(&first, sid.0),
            "first dest must not keep a leftover DENY ACE after rollback"
        );
        drop(sid);
    }

    #[test]
    fn msys_install_key_for_program_files_git() {
        let mut path: Vec<u16> =
            std::ffi::OsStr::new(r"\\?\C:\Program Files\Git\usr\bin\msys-2.0.dll")
                .encode_wide()
                .collect();
        normalize_msys_install_path(&mut path);
        let hash = hash_path_name(0, &path);
        assert_eq!(format!("{hash:016x}"), "1888ae32e00d56aa");
    }

    #[test]
    fn restricted_token_keeps_traverse_and_drops_admin_privileges() {
        let sid = RestrictedSid::new().expect("sid");
        let token = create_write_restricted_token(sid.0).expect("token");
        let traverse = privilege_enabled(token.0, "SeChangeNotifyPrivilege").expect("lookup");
        assert_eq!(
            traverse,
            Some(true),
            "SeChangeNotifyPrivilege must stay enabled, got {traverse:?}"
        );
        for name in [
            "SeDebugPrivilege",
            "SeBackupPrivilege",
            "SeRestorePrivilege",
            "SeTakeOwnershipPrivilege",
            "SeLoadDriverPrivilege",
            "SeTcbPrivilege",
        ] {
            let state =
                privilege_enabled(token.0, name).unwrap_or_else(|err| panic!("{name}: {err}"));
            assert_ne!(
                state,
                Some(true),
                "{name} must stay disabled, got {state:?}"
            );
        }
    }

    #[repr(C)]
    struct Luid {
        low_part: Dword,
        high_part: i32,
    }

    #[repr(C)]
    struct LuidAndAttributes {
        luid: Luid,
        attributes: Dword,
    }

    #[link(name = "advapi32")]
    unsafe extern "system" {
        fn LookupPrivilegeValueW(
            lp_system_name: *const u16,
            lp_name: *const u16,
            lp_luid: *mut Luid,
        ) -> Bool;
    }

    /// `Some(true)` enabled, `Some(false)` present but disabled, `None` absent.
    fn privilege_enabled(token: Handle, name: &str) -> Result<Option<bool>, KernelError> {
        const SE_PRIVILEGE_ENABLED: Dword = 0x0000_0002;
        let wide = wide_os(std::ffi::OsStr::new(name));
        let mut want = Luid {
            low_part: 0,
            high_part: 0,
        };
        // SAFETY: `wide` is a NUL-terminated privilege name.
        let looked = unsafe { LookupPrivilegeValueW(ptr::null(), wide.as_ptr(), &mut want) };
        if looked == 0 {
            return Err(last_error("LookupPrivilegeValueW"));
        }
        let mut bytes = 0u32;
        unsafe {
            GetTokenInformation(token, 3, ptr::null_mut(), 0, &mut bytes);
        }
        if bytes < 4 {
            return Err(last_error("GetTokenInformation TokenPrivileges"));
        }
        let len = bytes;
        let mut buf = vec![0u64; len.div_ceil(8) as usize];
        // SAFETY: `buf` is at least `len` bytes and 8-byte aligned.
        let ok = unsafe { GetTokenInformation(token, 3, buf.as_mut_ptr().cast(), len, &mut bytes) };
        if ok == 0 {
            return Err(last_error("GetTokenInformation TokenPrivileges"));
        }
        let raw = unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, bytes as usize) };
        let count = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]);
        let stride = std::mem::size_of::<LuidAndAttributes>();
        for i in 0..count as usize {
            let start = 4 + i * stride;
            let end = start + stride;
            if end > raw.len() {
                break;
            }
            // SAFETY: `start` is inside `raw`. The first privilege entry is at offset 4.
            let entry = unsafe { &*raw[start..].as_ptr().cast::<LuidAndAttributes>() };
            if entry.luid.low_part == want.low_part && entry.luid.high_part == want.high_part {
                return Ok(Some(entry.attributes & SE_PRIVILEGE_ENABLED != 0));
            }
        }
        Ok(None)
    }
}

#[cfg(test)]
mod env_block_tests {
    use super::environment_block;
    use std::process::Command;

    fn block_has_key(block: &[u16], key: &str) -> bool {
        let mut entry = Vec::new();
        for unit in block {
            if *unit == 0 {
                if entry.is_empty() {
                    break;
                }
                let text = String::from_utf16_lossy(&entry);
                if text
                    .split_once('=')
                    .is_some_and(|(name, _)| name.eq_ignore_ascii_case(key))
                {
                    return true;
                }
                entry.clear();
            } else {
                entry.push(*unit);
            }
        }
        false
    }

    #[test]
    fn env_remove_drops_an_inherited_name() {
        let Some((key, _)) = std::env::vars_os().find(|(name, _)| {
            let name = name.to_string_lossy();
            !name.eq_ignore_ascii_case("PATH") && !name.eq_ignore_ascii_case("SystemRoot")
        }) else {
            return;
        };
        let name = key.to_string_lossy().into_owned();
        let mut cmd = Command::new("cmd");
        for (inherited, _) in std::env::vars_os() {
            cmd.env_remove(inherited);
        }
        if let Some(path) = std::env::var_os("PATH") {
            cmd.env("PATH", path);
        }
        let block = environment_block(&mut cmd);
        assert!(
            !block_has_key(&block, &name),
            "{name} stayed in the child block after env_remove"
        );
        if std::env::var_os("PATH").is_some() {
            assert!(block_has_key(&block, "PATH"), "PATH was not restored");
        }
    }

    #[test]
    fn env_clear_drops_an_inherited_name() {
        let Some((key, _)) = std::env::vars_os().find(|(name, _)| {
            let name = name.to_string_lossy();
            !name.eq_ignore_ascii_case("PATH") && !name.eq_ignore_ascii_case("SystemRoot")
        }) else {
            return;
        };
        let name = key.to_string_lossy().into_owned();
        let mut cmd = Command::new("cmd");
        cmd.env_clear();
        if let Some(path) = std::env::var_os("PATH") {
            cmd.env("PATH", path);
        }
        if let Some(root) = std::env::var_os("SystemRoot") {
            cmd.env("SystemRoot", root);
        }
        let block = environment_block(&mut cmd);
        assert!(
            !block_has_key(&block, &name),
            "{name} stayed in the child block after env_clear"
        );
        if std::env::var_os("PATH").is_some() {
            assert!(block_has_key(&block, "PATH"), "PATH was not restored");
        }
        if std::env::var_os("SystemRoot").is_some() {
            assert!(
                block_has_key(&block, "SystemRoot"),
                "SystemRoot was not restored"
            );
        }
    }
}