puressh 0.2.2

A pure-Rust SSH (Secure Shell) protocol library, in the spirit of libssh, built on purecrypto.
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
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
//! `sshd` — puressh's SSH server daemon.
//!
//! ```text
//! sshd [-46DdeqTt] [-C connection_spec] [-f config] [-p port]... [-h host_key_file]... [-o option]...
//!      [-A authorized_keys_file] [-u allowed_user]... [--x11-forward] ...
//! ```
//!
//! Defaults follow OpenSSH so the binary can replace it: the configuration
//! is `/etc/ssh/sshd_config` (when present; `-f` overrides, `-o` options win
//! over the file), the host keys are `/etc/ssh/ssh_host_{rsa,ecdsa,ed25519,mldsa44_ed25519}_key`
//! (whichever load), the daemon listens on port 22 of every address (one
//! `IPV6_V6ONLY` socket per family), and any user may log in subject to
//! `AllowUsers` / `DenyUsers` and authentication. It always stays in the
//! foreground (`-D` / `-e` are accepted no-ops); `-t` checks the
//! configuration and host keys and exits; SIGHUP re-executes the daemon to
//! reload the configuration, unless the new configuration fails to load.
//!
//! Public keys are looked up **per user**, as OpenSSH does: `AuthorizedKeysFile`
//! (default `.ssh/authorized_keys .ssh/authorized_keys2`) names one or more
//! path templates, `%u` / `%h` / `%%` are expanded against the login user's
//! passwd entry, a relative path is taken under that user's home directory,
//! and the resulting files are read — while the daemon still holds root, so
//! `~/.ssh` may be mode 0700 — and StrictModes-checked against that user
//! (file and every ancestor owned by root or the user, none group/world
//! writable). `cert-authority` lines in a user's own file trust that CA for
//! that user only, and honour `principals="a,b"`.
//!
//! `-A FILE` is different and deliberately narrow: it names ONE global
//! `authorized_keys` file whose every key logs in as the single allowed user.
//! It is refused unless exactly one literal user is allowed (`-u USER`, or
//! one `AllowUsers` name with no wildcard / `@host`), because a shared file
//! plus several allowed users would let any listed key log in as any of
//! them. It exists for single-user / test deployments; production setups
//! should use `AuthorizedKeysFile`.
//!
//! Each accepted connection is handled by a freshly `fork()`ed child
//! process. The daemon parent keeps the listener and immediately returns
//! to `accept()`. Killing the daemon does **not** kill live sessions —
//! children are reparented to PID 1 and keep running. The child drops the
//! listener fd so the daemon can be restarted on the same port without
//! waiting on `SO_REUSEADDR` semantics.
//!
//! The parent tracks every live child (pid → peer IP, auth state) and
//! reaps in its accept loop, never from the signal handler. `MaxStartups`
//! (`--max-startups`) caps the number of children that have not yet
//! authenticated — each child reports userauth success over an inherited
//! pipe — and `--per-source-max` caps live children per peer IP for their
//! whole lifetime.
//!
//! Interactive shells (`pty-req` + `shell`) allocate a PTY with
//! `openpty()` and fork manually so the slave path is known up-front —
//! the PAM session is opened with `PAM_TTY = /dev/pts/N` *before* the
//! grandchild forks off into the user's shell. The grandchild's exit
//! status is reaped via `waitpid(WNOHANG)` and forwarded to the client
//! as `exit-status` / `exit-signal`.
//!
//! When the `pam` feature is on (default), every successful SSH
//! authentication is followed by `pam_acct_mgmt` + `pam_open_session`
//! against service `sshd` — `pam_env` contributions land in the user's
//! shell environment and `pam_close_session` runs at connection
//! teardown. Building with `--no-default-features` (or any combination
//! that omits `pam`) drops the libpam runtime dep entirely; the binary
//! still works but offers no session management.
//!
//! Windows builds compile but `main` prints "not supported" — every line
//! of the implementation lives behind `#[cfg(unix)]`.

#[cfg(not(unix))]
fn main() -> std::process::ExitCode {
    eprintln!("puressh sshd: only supported on Unix-like systems");
    std::process::ExitCode::from(2)
}

#[cfg(unix)]
fn main() -> std::process::ExitCode {
    imp::main()
}

#[cfg(unix)]
#[path = "sshd_log.rs"]
mod sshd_log;

#[cfg(unix)]
#[path = "tundev.rs"]
mod tundev;

#[cfg(all(target_os = "linux", target_env = "gnu"))]
#[path = "sshd_login.rs"]
mod sshd_login;

#[cfg(unix)]
mod imp {
    use crate::sshd_log;
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    use crate::sshd_login;
    use std::collections::HashMap;
    use std::ffi::OsStr;
    use std::net::IpAddr;
    use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::process::CommandExt;
    use std::process::{Command, ExitCode};
    use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::{Duration, Instant};

    use nix::errno::Errno;
    use nix::fcntl::{FcntlArg, FdFlag, OFlag, fcntl};
    use nix::libc;
    use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
    use nix::sys::signal::{SigHandler, Signal, kill, signal};
    use nix::sys::wait::{WaitPidFlag, WaitStatus, waitpid};
    use nix::unistd::{ForkResult, Pid, execvp, fork};

    use puressh::auth::{AuthAttempt, AuthDecision, Authenticator};
    use puressh::hostkey::HostKey;
    use puressh::key::{PrivateKey, PublicKey};
    use puressh::scp::{
        Receiver as ScpReceiver, ScpRecvOptions, ScpSendOptions, Sender as ScpSender,
    };
    use puressh::server::{
        AuthenticatorFactory, ChannelStream, CommandHandler, Config, ExecResult, ExecStreamHandler,
        HARD_BLOCKED_ENV_NAMES, PtySpec, SessionEnv, SessionOpenContext, ShellExitStatus,
        ShellHandler, ShellSession, SubsystemHandler, handle_session_with_addrs,
        handle_session_with_peer,
    };
    use puressh::sftp::{SftpServerOptions, SftpServerSession};

    const VERSION: &str = env!("CARGO_PKG_VERSION");

    const USAGE: &str = "usage: sshd [-46DdeqTt] [-C connection_spec] [-f configfile] [-p port]... \
                         [-b address]... \
                         [-h host_key_file]... [-c host_cert_file]... [-o option]... \
                         [-E log_file] [-g login_grace_time] [-A authorized_keys_file] \
                         [-u allowed_user]... [--no-sftp] [--sftp-read-only] \
                         [--sftp-root PATH] [--no-scp] [--no-agent-forward] \
                         [--x11-forward] [--no-strict-modes] [--debug-commands] \
                         [--accept-env GLOB]... [--login-grace-time SECONDS] \
                         [--max-startups N] [--per-source-max N] \
                         [--permit-root-login yes|no|prohibit-password]";

    // -------------------------------------------------------------------------
    // PAM session gate.
    //
    // The `pam` feature compiles the real implementation against
    // `pam-client2`; without the feature, a no-op stub provides the same
    // surface so the rest of the binary doesn't need feature-gates. Either
    // way `ensure(user, tty)` is the only entry point handlers use.
    //
    // Lifetime model: the `PamGate` is wrapped in `Arc` and shared across
    // `ShellCommandHandler` + `NixShellHandler`. Because each connection
    // runs in its own `fork()`ed child, the gate's state (the live PAM
    // context, the cached env list, the peer address) is COW-isolated per
    // connection — there's no cross-connection bleed even though the
    // daemon's parent process never opens any PAM session itself.
    // -------------------------------------------------------------------------
    // The real PAM gate compiles only when both the `pam` feature is enabled
    // AND we're targeting Linux — `pam-client2` itself is dep-gated to Linux
    // because it references Linux-PAM constants that OpenPAM (macOS / *BSD)
    // doesn't expose. Every other configuration (Linux without `pam`, macOS
    // with `--all-features`, etc.) falls through to the stub below.
    #[cfg(all(feature = "pam", target_os = "linux"))]
    mod pam_gate {
        use std::ffi::{CStr, CString};
        use std::os::unix::ffi::OsStrExt;
        use std::sync::mpsc::{Receiver, Sender, channel};
        use std::sync::{Arc, Mutex};
        use std::thread::JoinHandle;

        use pam_client2::conv_null::Conversation;
        use pam_client2::{Context, ConversationHandler, ErrorCode, Flag, SessionToken};
        use purecrypto::zeroize::Zeroizing;

        /// One step of a live keyboard-interactive PAM conversation, returned
        /// by [`KbdConversation::next`].
        pub enum KbdStep {
            /// PAM asked a prompt. `instruction` carries any `text_info` /
            /// `error_msg` the module emitted just before it (often the OTP
            /// challenge text). `echo` is true for a visible prompt.
            Prompt {
                /// Instruction / info text to show above the prompt.
                instruction: String,
                /// The prompt label (e.g. `"Password: "`, `"OTP: "`).
                prompt: String,
                /// Whether the client should echo the typed answer.
                echo: bool,
            },
            /// The PAM `authenticate()` + `acct_mgmt()` finished. `true` ⇒ both
            /// succeeded (accept); `false` ⇒ rejected.
            Done(bool),
        }

        /// A message sent FROM the worker thread (running PAM) TO the
        /// authenticator (driving the SSH wire).
        enum FromWorker {
            /// PAM wants an answer to this prompt.
            Prompt {
                instruction: String,
                prompt: String,
                echo: bool,
            },
            /// PAM finished with this overall verdict.
            Done(bool),
        }

        /// The reply the authenticator hands back for a prompt: the user's
        /// answer, wiped on drop. A `None` answer (channel closed / no
        /// response) is treated by the worker as a conversation error.
        type ToWorker = Zeroizing<Vec<u8>>;

        /// A keyboard-interactive PAM conversation in flight.
        ///
        /// The PAM `Context` lives on a dedicated worker thread (`handle`); its
        /// conversation callback blocks on `to_worker`, handing each prompt out
        /// over `from_worker` and waiting for the answer. The authenticator
        /// holds the channel ends + the join handle here. Dropping this struct
        /// (on disconnect, or when `LoginGraceTime` fires) closes `to_worker`,
        /// which unblocks the worker's conversation with a `RecvError` → PAM
        /// aborts → the thread exits and is joined.
        pub struct KbdConversation {
            from_worker: Receiver<FromWorker>,
            to_worker: Sender<ToWorker>,
            handle: Option<JoinHandle<()>>,
            /// Set once a terminal `Done` has been observed, so a stray extra
            /// `answer`/`next` cannot wedge on a dead worker.
            finished: bool,
        }

        /// The conversation handler that runs ON the worker thread. Each
        /// per-message PAM callback sends one prompt to the authenticator and
        /// blocks for its answer.
        struct BridgeConv {
            to_main: Sender<FromWorker>,
            from_main: Receiver<ToWorker>,
            /// `text_info` / `error_msg` text accumulated since the last
            /// prompt, attached to the next prompt's instruction.
            pending_info: String,
        }

        impl BridgeConv {
            /// Block until the authenticator supplies the answer to `prompt`.
            /// A closed channel (authenticator dropped the conversation) maps
            /// to a PAM conversation error so `authenticate()` aborts cleanly.
            fn ask(&mut self, prompt: &CStr, echo: bool) -> Result<CString, ErrorCode> {
                let instruction = core::mem::take(&mut self.pending_info);
                let prompt = String::from_utf8_lossy(prompt.to_bytes()).into_owned();
                self.to_main
                    .send(FromWorker::Prompt {
                        instruction,
                        prompt,
                        echo,
                    })
                    .map_err(|_| ErrorCode::CONV_ERR)?;
                let answer = self.from_main.recv().map_err(|_| ErrorCode::CONV_ERR)?;
                // The answer may not contain an interior NUL.
                CString::new(answer.to_vec()).map_err(|_| ErrorCode::CONV_ERR)
            }
        }

        impl ConversationHandler for BridgeConv {
            fn prompt_echo_on(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {
                self.ask(prompt, true)
            }
            fn prompt_echo_off(&mut self, prompt: &CStr) -> Result<CString, ErrorCode> {
                self.ask(prompt, false)
            }
            fn text_info(&mut self, msg: &CStr) {
                let s = String::from_utf8_lossy(msg.to_bytes());
                if !self.pending_info.is_empty() {
                    self.pending_info.push('\n');
                }
                self.pending_info.push_str(&s);
            }
            fn error_msg(&mut self, msg: &CStr) {
                // Surface errors as instruction text too (e.g. "Account
                // locked"); they precede the next prompt or are dropped if the
                // conversation ends.
                self.text_info(msg);
            }
        }

        impl KbdConversation {
            /// Pull the next step from the worker: either a prompt to send to
            /// the client, or the terminal verdict. After a `Done`, further
            /// calls return `Done` with the same verdict without blocking.
            pub fn next(&mut self) -> KbdStep {
                if self.finished {
                    return KbdStep::Done(false);
                }
                match self.from_worker.recv() {
                    Ok(FromWorker::Prompt {
                        instruction,
                        prompt,
                        echo,
                    }) => KbdStep::Prompt {
                        instruction,
                        prompt,
                        echo,
                    },
                    Ok(FromWorker::Done(ok)) => {
                        self.finished = true;
                        KbdStep::Done(ok)
                    }
                    // Worker died without a verdict ⇒ reject.
                    Err(_) => {
                        self.finished = true;
                        KbdStep::Done(false)
                    }
                }
            }

            /// Hand the user's answer for the outstanding prompt to the worker.
            /// Returns `false` if the worker is already gone.
            pub fn answer(&mut self, response: Zeroizing<Vec<u8>>) -> bool {
                if self.finished {
                    return false;
                }
                self.to_worker.send(response).is_ok()
            }
        }

        impl Drop for KbdConversation {
            fn drop(&mut self) {
                // Dropping `to_worker` closes the response channel; a worker
                // blocked in `recv()` wakes with `RecvError`, returns
                // CONV_ERR, and PAM `authenticate()` unwinds. Then join.
                // (Replace the sender with a fresh, immediately-dropped one to
                // force-close without needing `to_worker` to be an Option.)
                let (dead, _) = channel::<ToWorker>();
                drop(core::mem::replace(&mut self.to_worker, dead));
                if let Some(h) = self.handle.take() {
                    let _ = h.join();
                }
            }
        }

        /// A one-shot PAM conversation that answers every
        /// `PAM_PROMPT_ECHO_OFF` (the password prompt) with a fixed secret,
        /// held in a [`Zeroizing`] buffer so its bytes are wiped on drop.
        /// Echo-on prompts (username) and info/error messages are ignored —
        /// the username is already bound via `Context::new`, and we never
        /// surface PAM text to the network here. This is the
        /// non-interactive "verify this password" conversation used by the
        /// SSH `password` method, which is single-prompt by nature. A genuine
        /// multi-step PAM challenge (e.g. an OTP module that asks a second
        /// question) is driven instead by [`BridgeConv`] /
        /// [`KbdConversation`] over the `keyboard-interactive` method.
        struct PasswordConv {
            password: Zeroizing<Vec<u8>>,
        }

        impl ConversationHandler for PasswordConv {
            fn prompt_echo_on(&mut self, _prompt: &CStr) -> Result<CString, ErrorCode> {
                // Username/echo-on prompts: nothing to supply (the context
                // already carries the target user). Empty answer.
                CString::new(Vec::new()).map_err(|_| ErrorCode::CONV_ERR)
            }
            fn prompt_echo_off(&mut self, _prompt: &CStr) -> Result<CString, ErrorCode> {
                // The password may not contain an interior NUL.
                CString::new(self.password.to_vec()).map_err(|_| ErrorCode::CONV_ERR)
            }
            fn text_info(&mut self, _msg: &CStr) {}
            fn error_msg(&mut self, _msg: &CStr) {}
        }

        /// Holds the live PAM `Context` and the leaked session handle.
        /// Drop order matters: the leaked `Session` must be re-acquired
        /// (via `unleak_session`) so its own `Drop` calls
        /// `pam_close_session`, *then* the boxed context drops and calls
        /// `pam_end`.
        struct PamHolder {
            context: Box<Context<Conversation>>,
            token: Option<SessionToken>,
        }

        impl Drop for PamHolder {
            fn drop(&mut self) {
                if let Some(token) = self.token.take() {
                    // Re-attach the session to its context; the returned
                    // `Session` drops in place, closing the PAM session.
                    let _session = self.context.unleak_session(token);
                }
                // Box<Context<…>> drops next: pam_end.
            }
        }

        pub struct PamGate {
            service: &'static str,
            peer: Mutex<Option<String>>,
            envs: Mutex<Vec<(CString, CString)>>,
            inner: Mutex<Option<PamHolder>>,
            debug: bool,
            /// `UsePAM no`: no PAM account check or session.
            disabled: std::sync::atomic::AtomicBool,
        }

        impl PamGate {
            /// `service`: the PAM service (`PAMServiceName`, `sshd` by
            /// default).
            pub fn new(debug: bool, service: &'static str) -> Arc<Self> {
                Arc::new(Self {
                    service,
                    peer: Mutex::new(None),
                    envs: Mutex::new(Vec::new()),
                    inner: Mutex::new(None),
                    debug,
                    disabled: std::sync::atomic::AtomicBool::new(false),
                })
            }

            /// `UsePAM no`: [`Self::ensure`] then opens nothing.
            pub fn disable(&self) {
                self.disabled
                    .store(true, std::sync::atomic::Ordering::Relaxed);
            }

            /// Stash the peer address (used as `PAM_RHOST`). Should be
            /// called inside the per-connection child before any handler
            /// triggers `ensure`.
            pub fn set_peer(&self, peer: String) {
                *self.peer.lock().unwrap() = Some(peer);
            }

            /// Lazily open the PAM session for `user` with PAM_TTY set
            /// to `tty`. Strict: on failure, returns `Err` — the caller
            /// is expected to surface that as a CHANNEL_FAILURE or as
            /// `exit_status = 255`. Idempotent: subsequent calls return
            /// the same cached env list without re-opening.
            pub fn ensure(
                &self,
                user: &str,
                tty: &str,
            ) -> puressh::Result<Vec<(CString, CString)>> {
                if self.disabled.load(std::sync::atomic::Ordering::Relaxed) {
                    return Ok(Vec::new());
                }
                let mut guard = self.inner.lock().unwrap();
                if guard.is_some() {
                    return Ok(self.envs.lock().unwrap().clone());
                }

                let mut ctx = Box::new(
                    Context::new(self.service, Some(user), Conversation::new())
                        .map_err(|e| pam_err("pam_start", e))?,
                );
                if let Some(rhost) = self.peer.lock().unwrap().clone() {
                    ctx.set_rhost(Some(&rhost))
                        .map_err(|e| pam_err("set_rhost", e))?;
                }
                ctx.set_tty(Some(tty)).map_err(|e| pam_err("set_tty", e))?;
                ctx.acct_mgmt(Flag::NONE)
                    .map_err(|e| pam_err("acct_mgmt", e))?;

                let session = ctx
                    .open_session(Flag::NONE)
                    .map_err(|e| pam_err("open_session", e))?;

                // Snapshot the PAM env. `iter_tuples` yields
                // `(&OsStr, &OsStr)`; we keep `CString`s because the
                // post-fork shell needs `*const c_char` for `setenv`.
                let envs: Vec<(CString, CString)> = session
                    .envlist()
                    .iter_tuples()
                    .filter_map(|(k, v)| {
                        let k = CString::new(k.as_bytes()).ok()?;
                        let v = CString::new(v.as_bytes()).ok()?;
                        Some((k, v))
                    })
                    .collect();

                let token = session.leak();
                *self.envs.lock().unwrap() = envs.clone();
                *guard = Some(PamHolder {
                    context: ctx,
                    token: Some(token),
                });
                if self.debug {
                    eprintln!(
                        "sshd: PAM session opened (user={user}, tty={tty}, envs={})",
                        envs.len()
                    );
                }
                Ok(envs)
            }

            /// Verify `password` for `user` against PAM, *without* opening a
            /// session (that still happens later in `ensure`/
            /// `on_session_open`). A fresh, throw-away `Context` is created
            /// with a [`PasswordConv`] conversation that answers the password
            /// prompt; `authenticate()` + `acct_mgmt()` must both succeed. The
            /// context is dropped at the end of this call (running `pam_end`),
            /// so this never disturbs the cached session state.
            ///
            /// Runs in the per-connection forked child while still root, which
            /// is what PAM auth (e.g. reading `/etc/shadow`) requires; the
            /// privilege drop happens afterwards in `on_session_open`.
            ///
            /// MANUAL e2e (not a hermetic unit test — installing a PAM service
            /// file needs root + writes to `/etc/pam.d`, which CI can't do):
            ///   1. Create `/etc/pam.d/sshd` containing only
            ///      `auth required pam_permit.so` / `account required
            ///      pam_permit.so` and confirm any password authenticates;
            ///      swap `pam_permit.so` for `pam_deny.so` and confirm none do.
            ///   2. With the real system `sshd` service, confirm a correct
            ///      account password authenticates and a wrong one is rejected,
            ///      and that `PermitEmptyPasswords no` refuses an empty one.
            pub fn pam_check_password(
                &self,
                user: &str,
                password: Zeroizing<Vec<u8>>,
                rhost: Option<&str>,
            ) -> puressh::Result<()> {
                let conv = PasswordConv { password };
                let mut ctx = Context::new(self.service, Some(user), conv)
                    .map_err(|e| pam_err("pam_start", e))?;
                if let Some(rhost) = rhost {
                    ctx.set_rhost(Some(rhost))
                        .map_err(|e| pam_err("set_rhost", e))?;
                }
                ctx.authenticate(Flag::NONE)
                    .map_err(|e| pam_err("authenticate", e))?;
                ctx.acct_mgmt(Flag::NONE)
                    .map_err(|e| pam_err("acct_mgmt", e))?;
                // `ctx` (and the embedded `PasswordConv`, whose buffer is
                // `Zeroizing`) drops here — pam_end runs, no session opened.
                Ok(())
            }

            /// Begin a genuine multi-step keyboard-interactive PAM
            /// conversation for `user`. PAM `authenticate()` runs on a
            /// dedicated worker thread whose conversation callback bridges each
            /// prompt to the SSH `USERAUTH_INFO_REQUEST`/`_RESPONSE` rounds via
            /// channels (see [`KbdConversation`]). The returned handle is
            /// driven by [`KbdConversation::next`] / [`KbdConversation::answer`]
            /// and torn down on drop.
            ///
            /// Like [`Self::pam_check_password`], this opens **no** session —
            /// it only authenticates (`authenticate()` + `acct_mgmt()`); the
            /// session is opened later in `ensure`. A throw-away `Context`
            /// lives entirely on the worker thread, so its (`!Sync`) PAM handle
            /// never crosses back to the authenticator.
            ///
            /// MANUAL e2e against a real 2-prompt PAM service (not hermetic —
            /// installing a PAM service file needs root + writes to
            /// `/etc/pam.d`):
            ///   1. Install a second-factor PAM module that prompts after the
            ///      password — e.g. `pam_google_authenticator.so` — into
            ///      `/etc/pam.d/sshd`:
            ///        ```text
            ///        auth required pam_unix.so
            ///        auth required pam_google_authenticator.so
            ///        account required pam_unix.so
            ///        ```
            ///   2. Run sshd with `KbdInteractiveAuthentication yes`, connect
            ///      with `ssh -o PreferredAuthentications=keyboard-interactive`,
            ///      and confirm the client is asked the password FIRST, then the
            ///      `Verification code:` prompt, and that a correct code logs in
            ///      while a wrong one (or an empty password under
            ///      `PermitEmptyPasswords no`) is refused.
            ///   3. A simpler 2-prompt stand-in is `pam_listfile`/`pam_exec`
            ///      with a script that echoes a `PAM_PROMPT_ECHO_OFF` message;
            ///      the bridge issues each as its own `USERAUTH_INFO_REQUEST`.
            pub fn start_kbd_interactive(
                &self,
                user: &str,
                rhost: Option<&str>,
            ) -> KbdConversation {
                let (to_main, from_worker) = channel::<FromWorker>();
                let (to_worker, from_main) = channel::<ToWorker>();
                let service = self.service;
                let user = user.to_string();
                let rhost = rhost.map(str::to_string);

                let handle = std::thread::spawn(move || {
                    let conv = BridgeConv {
                        to_main: to_main.clone(),
                        from_main,
                        pending_info: String::new(),
                    };
                    // Build the context on THIS thread; the PAM handle never
                    // leaves it.
                    let mut ctx = match Context::new(service, Some(&user), conv) {
                        Ok(c) => c,
                        Err(_) => {
                            let _ = to_main.send(FromWorker::Done(false));
                            return;
                        }
                    };
                    if let Some(rhost) = rhost.as_deref()
                        && ctx.set_rhost(Some(rhost)).is_err()
                    {
                        let _ = to_main.send(FromWorker::Done(false));
                        return;
                    }
                    // authenticate() drives the conversation: each prompt
                    // blocks in BridgeConv::ask until the authenticator answers.
                    let ok =
                        ctx.authenticate(Flag::NONE).is_ok() && ctx.acct_mgmt(Flag::NONE).is_ok();
                    let _ = to_main.send(FromWorker::Done(ok));
                    // `ctx` drops here on the worker thread → pam_end.
                });

                KbdConversation {
                    from_worker,
                    to_worker,
                    handle: Some(handle),
                    finished: false,
                }
            }
        }

        fn pam_err<E: std::fmt::Display>(phase: &'static str, e: E) -> puressh::Error {
            puressh::Error::Io(std::io::Error::other(format!("PAM {phase}: {e}")))
        }

        #[cfg(test)]
        impl KbdConversation {
            /// Build a conversation backed by a scripted *fake* worker instead
            /// of a real PAM `Context`, for hermetic state-machine tests. The
            /// worker emits each `(instruction, prompt, echo)` in `script`,
            /// blocking for the answer after each (recording it into
            /// `received`), then emits `Done(verdict)`. This exercises the exact
            /// channel protocol `BridgeConv` + the real worker use, without
            /// requiring a multi-prompt PAM module to be installed.
            pub fn fake_for_test(
                script: Vec<(String, String, bool)>,
                verdict: bool,
                received: std::sync::Arc<Mutex<Vec<Vec<u8>>>>,
            ) -> Self {
                let (to_main, from_worker) = channel::<FromWorker>();
                let (to_worker, from_main) = channel::<ToWorker>();
                let handle = std::thread::spawn(move || {
                    for (instruction, prompt, echo) in script {
                        if to_main
                            .send(FromWorker::Prompt {
                                instruction,
                                prompt,
                                echo,
                            })
                            .is_err()
                        {
                            return;
                        }
                        match from_main.recv() {
                            Ok(answer) => received.lock().unwrap().push(answer.to_vec()),
                            // Authenticator dropped us (disconnect / grace
                            // timeout) — exit like the real worker would.
                            Err(_) => return,
                        }
                    }
                    let _ = to_main.send(FromWorker::Done(verdict));
                });
                KbdConversation {
                    from_worker,
                    to_worker,
                    handle: Some(handle),
                    finished: false,
                }
            }
        }
    }

    #[cfg(not(all(feature = "pam", target_os = "linux")))]
    mod pam_gate {
        use std::ffi::CString;
        use std::sync::Arc;

        /// Stub gate used when the `pam` feature is off, or when the
        /// target isn't Linux (the `pam-client2` dep is Linux-only — see
        /// the cfg gate on the real `pam_gate` module above). All
        /// operations are no-ops so the rest of the binary can ignore
        /// the feature state.
        pub struct PamGate;

        /// Stub mirror of the real [`KbdStep`]. On a non-PAM build a
        /// keyboard-interactive conversation can never start, so this is only
        /// ever observed as `Done(false)`. The `Prompt` variant exists purely
        /// for type parity with the real module's `kbd_pump` match arms, so it
        /// is never constructed here.
        #[allow(dead_code)]
        pub enum KbdStep {
            /// Never produced on this build (kept for type parity).
            Prompt {
                /// Instruction text.
                instruction: String,
                /// Prompt label.
                prompt: String,
                /// Echo flag.
                echo: bool,
            },
            /// Terminal verdict; always `false` here.
            Done(bool),
        }

        /// Stub mirror of the real `KbdConversation` for non-PAM builds. It
        /// always reports a rejecting `Done(false)` and accepts no answers.
        pub struct KbdConversation {
            done: bool,
        }

        impl KbdConversation {
            pub fn next(&mut self) -> KbdStep {
                self.done = true;
                KbdStep::Done(false)
            }
            pub fn answer(&mut self, _response: purecrypto::zeroize::Zeroizing<Vec<u8>>) -> bool {
                let _ = self.done;
                false
            }
        }

        impl PamGate {
            pub fn new(_debug: bool, _service: &'static str) -> Arc<Self> {
                Arc::new(PamGate)
            }
            pub fn set_peer(&self, _peer: String) {}
            pub fn disable(&self) {}
            pub fn ensure(
                &self,
                _user: &str,
                _tty: &str,
            ) -> puressh::Result<Vec<(CString, CString)>> {
                Ok(Vec::new())
            }
            /// No PAM backend compiled in: password verification always
            /// fails. The server additionally never advertises the
            /// password/keyboard-interactive methods on such a build (the
            /// method set is computed from `cfg!(all(feature="pam",
            /// target_os="linux"))`), so this is belt-and-braces. The buffer
            /// is dropped (and zeroized) here.
            pub fn pam_check_password(
                &self,
                _user: &str,
                _password: purecrypto::zeroize::Zeroizing<Vec<u8>>,
                _rhost: Option<&str>,
            ) -> puressh::Result<()> {
                Err(puressh::Error::Io(std::io::Error::other(
                    "password authentication unavailable: no PAM backend compiled",
                )))
            }
            /// No PAM backend: a keyboard-interactive conversation cannot run.
            /// Returns a stub that immediately rejects. The server also never
            /// advertises `keyboard-interactive` on such a build.
            pub fn start_kbd_interactive(
                &self,
                _user: &str,
                _rhost: Option<&str>,
            ) -> KbdConversation {
                KbdConversation { done: false }
            }
        }
    }

    struct Cli {
        /// `-f path`: the `sshd_config` to read. `None` ⇒ the OpenSSH default
        /// [`DEFAULT_CONFIG`] (CLI flags still win on scalars).
        config_file: Option<String>,
        /// `-o KEYWORD=value` / `-o "KEYWORD value"`: config lines that take
        /// precedence over the file (first value wins, as in OpenSSH).
        config_options: Vec<String>,
        /// `-p port`, repeatable. Empty ⇒ `Port` lines, else 22.
        ports: Vec<u16>,
        /// `-T`: print the effective configuration and exit.
        dump_config: bool,
        /// `-C spec` (repeatable): connection parameters (`user=`, `addr=`,
        /// …) whose `Match` blocks `-T` applies.
        connection_spec: Vec<String>,
        /// `-t`: check the configuration and host keys, then exit.
        test_only: bool,
        /// `-i`: serve one connection on stdin / stdout (inetd mode, and
        /// OpenSSH's `ProxyCommand sshd -i` testing setups).
        inetd: bool,
        /// `-D`: stay in the foreground. Without it (and without `-d`), the
        /// daemon detaches once it is listening, as OpenSSH's does.
        no_detach: bool,
        /// `-4` / `-6`.
        address_family: Option<puressh::config::ServerAddressFamily>,
        /// `-E file`: append diagnostics to `file` instead of stderr.
        log_file: Option<String>,
        /// `-e`: log to stderr instead of syslog.
        log_stderr: bool,
        /// `-q`: log nothing.
        quiet: bool,
        /// `-b ADDR`: bind to ADDR (host or `host:port`). Repeats are
        /// recognised; v1 uses only the first one and warns about extras
        /// until multi-address bind lands. Config `ListenAddress` lines
        /// fold into the same list.
        listen_addresses: Vec<String>,
        host_key_files: Vec<String>,
        host_certificate_files: Vec<String>,
        /// `-A FILE`: one global authorized_keys file for the single allowed
        /// user (see the module docs). `None` ⇒ per-user `AuthorizedKeysFile`.
        authorized_keys_file: Option<String>,
        allowed_users: Vec<String>,
        debug: bool,
        /// SFTP subsystem on by default; `--no-sftp` disables it.
        sftp: Option<bool>,
        /// Refuse any operation that would mutate the filesystem.
        sftp_read_only: Option<bool>,
        /// If set, refuse paths that escape this root.
        sftp_root: Option<String>,
        /// SCP support (in-process `scp -t/-f`) on by default; `--no-scp`
        /// disables it. With SCP off, an `exec scp …` request falls through
        /// to the buffered command handler — which refuses unknown commands.
        scp: Option<bool>,
        /// Agent forwarding on by default; `--no-agent-forward` disables
        /// it. When off, any client `auth-agent-req@openssh.com` is
        /// refused.
        agent_forward: Option<bool>,
        /// X11 forwarding is **off** by default (OpenSSH's default);
        /// `--x11-forward` (or `X11Forwarding yes`) enables it. When off,
        /// any client `x11-req` is refused. `--no-x11-forward` is still
        /// accepted and forces it off over the config.
        x11_forward: Option<bool>,
        /// `--no-strict-modes`: skip the 0o077 / 0o022 file-permission
        /// checks on host keys / authorized_keys.
        strict_modes: Option<bool>,
        /// `--debug-commands`: log full exec command lines (otherwise
        /// only the first whitespace token is logged in debug mode).
        debug_commands: bool,
        /// `--accept-env GLOB`: OpenSSH-style env name allowlist; can be
        /// repeated, supports `*`/`?` wildcards. Empty = drop everything.
        accept_env: Vec<String>,
        /// `--login-grace-time SECONDS`: pre-auth inactivity timeout
        /// applied to the connection's read side. 0 disables.
        login_grace_time: Option<u32>,
        /// `--max-startups N`: cap on concurrent *unauthenticated*
        /// connection children, as OpenSSH's `MaxStartups` (0 = unlimited).
        /// A child leaves the count once it reports authentication success
        /// to the parent (see `AUTH_NOTIFY_FD`).
        max_startups: Option<u32>,
        /// `--per-source-max N`: cap on simultaneous connections (for their
        /// whole lifetime, authenticated or not) from any single peer IP
        /// (0 = unlimited). `None` ⇒ `PerSourceMaxStartups`, else 10.
        per_source_max: Option<u32>,
        /// `--permit-root-login yes|no|prohibit-password`: whether the root
        /// account (uid 0) may authenticate. Default (config/built-in) is
        /// `prohibit-password`, which permits root by key since puressh has
        /// no password auth; `no` blocks root entirely.
        permit_root_login: Option<puressh::config::PermitRootLogin>,
    }

    /// OpenSSH precedence helper: returns the first `Some` of `cli`, `cfg`,
    /// otherwise `default`. The standard scalar-option resolution pattern is
    /// `pick(cli_flag, cfg_value, builtin_default)`.
    fn pick<T>(cli: Option<T>, cfg: Option<T>, default: T) -> T {
        cli.or(cfg).unwrap_or(default)
    }

    /// Read and parse a single `sshd_config`-format file, resolving any
    /// `Include` directives recursively. There is no default search path on
    /// the server side: distros disagree on where the file lives, and the
    /// user explicitly opts in via `-f`. Relative includes resolve against the
    /// directory of the file being parsed (and, for the system entry point at
    /// `/etc/ssh/...`, that is `/etc/ssh`).
    /// Resolve `-b` / `ListenAddress` specs into the addresses to listen on,
    /// with OpenSSH's syntax: `host`, `host:port`, `[v6]`, `[v6]:port`, or a
    /// bare IPv6 literal. A spec without a port listens on every port in
    /// `ports`. No spec ⇒ the wildcard address of each allowed family.
    fn listen_addrs(
        specs: &[String],
        ports: &[u16],
        af: Option<puressh::config::ServerAddressFamily>,
    ) -> Result<Vec<std::net::SocketAddr>, String> {
        use puressh::config::ServerAddressFamily as Af;
        use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
        let family_ok = |a: &SocketAddr| match af {
            Some(Af::Inet) => a.is_ipv4(),
            Some(Af::Inet6) => a.is_ipv6(),
            _ => true,
        };
        let mut out: Vec<SocketAddr> = Vec::new();
        let mut push = |a: SocketAddr| {
            if family_ok(&a) && !out.contains(&a) {
                out.push(a);
            }
        };
        if specs.is_empty() {
            for &p in ports {
                push(SocketAddr::from((Ipv6Addr::UNSPECIFIED, p)));
                push(SocketAddr::from((Ipv4Addr::UNSPECIFIED, p)));
            }
        }
        for spec in specs {
            let mut words = spec.split_whitespace();
            let addr = words.next().unwrap_or("");
            if let Some(extra) = words.next() {
                return Err(format!(
                    "ListenAddress {spec:?}: {extra} (routing domains) is not supported"
                ));
            }
            let bad_port = || format!("ListenAddress {spec:?}: bad port");
            // (host, explicit port)
            let (host, port): (&str, Option<u16>) = if let Some(rest) = addr.strip_prefix('[') {
                let (h, tail) = rest
                    .split_once(']')
                    .ok_or_else(|| format!("ListenAddress {spec:?}: unterminated '['"))?;
                let port = match tail.strip_prefix(':') {
                    Some(p) => Some(p.parse().map_err(|_| bad_port())?),
                    None if tail.is_empty() => None,
                    None => return Err(format!("ListenAddress {spec:?}: junk after ']'")),
                };
                (h, port)
            } else if addr.matches(':').count() == 1 {
                let (h, p) = addr.split_once(':').unwrap_or((addr, ""));
                (h, Some(p.parse().map_err(|_| bad_port())?))
            } else {
                (addr, None)
            };
            let want: Vec<u16> = match port {
                Some(p) => vec![p],
                None => ports.to_vec(),
            };
            for p in want {
                let resolved = (host, p)
                    .to_socket_addrs()
                    .map_err(|e| format!("ListenAddress {spec:?}: {e}"))?;
                for a in resolved {
                    push(a);
                }
            }
        }
        if out.is_empty() {
            return Err("no listen address left after AddressFamily filtering".into());
        }
        Ok(out)
    }

    /// Bind a listening TCP socket. IPv6 sockets are `IPV6_V6ONLY` (as in
    /// OpenSSH) so `[::]` and `0.0.0.0` coexist and IPv4 peers keep their
    /// IPv4 addresses for `AllowUsers` / `Match Address`.
    fn bind_listener(addr: std::net::SocketAddr) -> std::io::Result<std::net::TcpListener> {
        use nix::sys::socket::{
            AddressFamily, Backlog, SockFlag, SockType, SockaddrIn, SockaddrIn6, bind, listen,
            setsockopt, socket, sockopt,
        };
        let family = if addr.is_ipv6() {
            AddressFamily::Inet6
        } else {
            AddressFamily::Inet
        };
        let fd = socket(family, SockType::Stream, SockFlag::empty(), None)?;
        fcntl(&fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
        setsockopt(&fd, sockopt::ReuseAddr, &true)?;
        match addr {
            std::net::SocketAddr::V6(v6) => {
                setsockopt(&fd, sockopt::Ipv6V6Only, &true)?;
                bind(fd.as_raw_fd(), &SockaddrIn6::from(v6))?;
            }
            std::net::SocketAddr::V4(v4) => bind(fd.as_raw_fd(), &SockaddrIn::from(v4))?,
        }
        listen(&fd, Backlog::new(128).unwrap_or(Backlog::MAXCONN))?;
        Ok(std::net::TcpListener::from(fd))
    }

    /// The `sshd_config` read when `-f` is not given (OpenSSH's default).
    const DEFAULT_CONFIG: &str = "/etc/ssh/sshd_config";

    /// Host keys tried when neither `-h` nor `HostKey` names any (OpenSSH's
    /// defaults); missing files are skipped.
    const DEFAULT_HOST_KEYS: &[&str] = &[
        "/etc/ssh/ssh_host_rsa_key",
        "/etc/ssh/ssh_host_ecdsa_key",
        "/etc/ssh/ssh_host_ed25519_key",
        "/etc/ssh/ssh_host_mldsa44_ed25519_key",
    ];

    /// The effective configuration: `-o` options first (so they win, since
    /// the first obtained value is used), then the file (`-f`, or
    /// [`DEFAULT_CONFIG`] if it exists).
    fn load_effective_config(cli: &Cli) -> Result<puressh::config::SshServerConfig, String> {
        let mut lines = Vec::new();
        for o in &cli.config_options {
            let toks = puressh::config::tokenize(o).map_err(|e| format!("-o {o:?}: {e}"))?;
            if toks.len() != 1 || toks[0].keyword == "match" || toks[0].keyword == "include" {
                return Err(format!(
                    "-o {o:?}: expected a single `Keyword value` option"
                ));
            }
            lines.extend(toks);
        }
        let path = match cli.config_file.as_deref() {
            Some(p) => Some(std::path::PathBuf::from(p)),
            None => {
                let p = std::path::PathBuf::from(DEFAULT_CONFIG);
                p.exists().then_some(p)
            }
        };
        if let Some(path) = &path {
            lines.extend(
                puressh::config::tokenize_file_with_includes(path, 0)
                    .map_err(|e| format!("{}: {e}", path.display()))?,
            );
        }
        puressh::config::SshServerConfig::from_lines(lines).map_err(|e| match &path {
            Some(p) => format!("{}: {e}", p.display()),
            None => e.to_string(),
        })
    }

    /// Fill unset global options with OpenSSH's defaults where this daemon's
    /// built-in defaults differ (`Match` blocks can still override them).
    fn apply_openssh_defaults(g: &mut puressh::config::ServerOptions) {
        g.print_motd.get_or_insert(true);
        if g.max_startups.is_none() {
            // MaxStartups 10:30:100
            g.max_startups = Some(100);
            g.max_startups_early = Some((10, 30));
        }
    }

    /// `Type=notify` (as OpenSSH's units on Ubuntu are): tell systemd the
    /// daemon is listening by sending `READY=1` to `$NOTIFY_SOCKET`. A
    /// re-exec on SIGHUP sends it again, which systemd accepts.
    fn notify_ready() {
        use std::os::unix::net::UnixDatagram;
        let Some(path) = std::env::var_os("NOTIFY_SOCKET") else {
            return;
        };
        let Ok(sock) = UnixDatagram::unbound() else {
            return;
        };
        let msg = format!("READY=1\nMAINPID={}", std::process::id());
        let sent = match path.as_encoded_bytes().strip_prefix(b"@") {
            // An abstract socket (systemd's usual choice).
            #[cfg(any(target_os = "linux", target_os = "android"))]
            Some(name) => {
                use std::os::linux::net::SocketAddrExt;
                std::os::unix::net::SocketAddr::from_abstract_name(name)
                    .and_then(|a| sock.send_to_addr(msg.as_bytes(), &a))
            }
            #[cfg(not(any(target_os = "linux", target_os = "android")))]
            Some(_) => return,
            None => sock.send_to(msg.as_bytes(), &path),
        };
        if let Err(e) = sent {
            eprintln!("sshd: warning: could not notify systemd: {e}");
        }
    }

    /// `-T [-C spec]`: print the effective configuration like OpenSSH's
    /// `sshd -T`: lowercase keywords, every setting with its default, and
    /// the `Match` blocks selected by `-C` applied.
    /// Opens the tun / tap devices clients forward (`ssh -w`).
    struct TunDevices;

    impl puressh::server::TunHandler for TunDevices {
        fn open(
            &self,
            _user: &str,
            mode: u32,
            unit: u32,
        ) -> std::io::Result<(std::fs::File, String)> {
            use sshd_log::{Level, log};
            match crate::tundev::open(unit, mode) {
                Ok((dev, ifname)) => {
                    log(
                        Level::Debug1,
                        &format!("Tunnel forwarding using interface {ifname}"),
                    );
                    Ok((dev, ifname))
                }
                Err(e) => {
                    log(
                        Level::Debug1,
                        &format!("sys_tun_open: failed to configure tunnel (mode {mode}): {e}"),
                    );
                    Err(e)
                }
            }
        }
    }

    fn dump_config(cli: &Cli, cfg: &puressh::config::SshServerConfig) -> Result<i32, String> {
        use puressh::config::{
            Compression, ExecPolicy, MatchContext, PermitRootLogin, ServerAddressFamily as Af,
            ServerGatewayPorts as GatewayPorts, TcpForwarding,
        };

        // `-C user=…,addr=…` (any order, repeatable).
        let (mut user, mut host, mut addr, mut laddr, mut lport) = (None, None, None, None, None);
        let mut invalid_user = false;
        let mut rdomain = None;
        for spec in &cli.connection_spec {
            for kv in spec.split(',').filter(|kv| !kv.is_empty()) {
                if kv == "invalid-user" {
                    invalid_user = true;
                    continue;
                }
                let (k, v) = kv
                    .split_once('=')
                    .ok_or_else(|| format!("Invalid test mode specification {kv}"))?;
                match k.to_ascii_lowercase().as_str() {
                    "user" => user = Some(v.to_string()),
                    "host" => host = Some(v.to_string()),
                    "addr" => addr = Some(v.to_string()),
                    "laddr" => laddr = Some(v.to_string()),
                    "lport" => {
                        lport = Some(v.parse::<u16>().map_err(|_| format!("Invalid port {v}"))?)
                    }
                    "rdomain" => rdomain = Some(v.to_string()),
                    _ => return Err(format!("Invalid test mode specification {kv}")),
                }
            }
        }
        let opts = if cli.connection_spec.is_empty() {
            cfg.global.clone()
        } else {
            let groups = user.as_deref().map(lookup_user_groups);
            let mut ctx = MatchContext::default();
            ctx.host = host.as_deref().unwrap_or("");
            ctx.invalid_user = Some(invalid_user);
            ctx.rdomain = rdomain.as_deref();
            ctx.user = user.as_deref();
            ctx.groups = groups.as_deref();
            ctx.address = addr.as_deref();
            ctx.local_address = laddr.as_deref();
            ctx.local_port = lport;
            cfg.resolve(&ctx, ExecPolicy::Deny)
        };

        let mut out = String::new();
        let mut line = |k: &str, v: &str| {
            out.push_str(k);
            out.push(' ');
            out.push_str(v);
            out.push('\n');
        };
        let yn = |b: bool| if b { "yes" } else { "no" };
        let fwd = |f: Option<TcpForwarding>| match f {
            None | Some(TcpForwarding::All) => "yes",
            Some(TcpForwarding::No) => "no",
            Some(TcpForwarding::Local) => "local",
            Some(TcpForwarding::Remote) => "remote",
            Some(_) => "yes",
        };
        let list = |v: &Option<Vec<String>>, default: &[&str]| match v {
            Some(v) => v.join(","),
            None => default
                .iter()
                .filter(|a| !a.starts_with("kex-strict-"))
                .copied()
                .collect::<Vec<_>>()
                .join(","),
        };
        let none_or = |v: &Option<String>| v.clone().unwrap_or_else(|| "none".into());

        let ports: Vec<u16> = if !cli.ports.is_empty() {
            cli.ports.clone()
        } else if !opts.ports.is_empty() {
            opts.ports.clone()
        } else {
            vec![22]
        };
        for p in &ports {
            line("port", &p.to_string());
        }
        let af = cli.address_family.or(opts.address_family);
        line(
            "addressfamily",
            match af {
                Some(Af::Inet) => "inet",
                Some(Af::Inet6) => "inet6",
                _ => "any",
            },
        );
        let mut specs = cli.listen_addresses.clone();
        specs.extend(opts.listen_addresses.iter().cloned());
        for a in listen_addrs(&specs, &ports, af)? {
            line("listenaddress", &a.to_string());
        }
        let mut host_keys = cli.host_key_files.clone();
        host_keys.extend(opts.host_key_files.iter().cloned());
        if host_keys.is_empty() {
            host_keys = DEFAULT_HOST_KEYS.iter().map(|s| s.to_string()).collect();
        }
        for k in &host_keys {
            line("hostkey", k);
        }
        let mut certs = cli.host_certificate_files.clone();
        certs.extend(opts.host_certificate_files.iter().cloned());
        for c in &certs {
            line("hostcertificate", c);
        }
        if let Some(a) = &opts.host_key_agent {
            line("hostkeyagent", a);
        }
        line(
            "pamservicename",
            opts.pam_service_name.as_deref().unwrap_or("sshd"),
        );
        line(
            "usepam",
            yn(opts
                .use_pam
                .unwrap_or(cfg!(all(feature = "pam", target_os = "linux")))),
        );
        line(
            "logingracetime",
            &cli.login_grace_time
                .or(opts.login_grace_time)
                .unwrap_or(120)
                .to_string(),
        );
        line(
            "maxauthtries",
            &opts
                .max_auth_tries
                .unwrap_or(puressh::server::DEFAULT_MAX_AUTH_TRIES)
                .to_string(),
        );
        line("maxsessions", &opts.max_sessions.unwrap_or(10).to_string());
        let full = opts.max_startups.unwrap_or(100);
        match opts.max_startups_early {
            Some((start, rate)) => line("maxstartups", &format!("{start}:{rate}:{full}")),
            None => line("maxstartups", &format!("{full}:100:{full}")),
        }
        line(
            "persourcemaxstartups",
            &match opts.per_source_max_startups {
                None | Some(0) => "none".to_string(),
                Some(n) => n.to_string(),
            },
        );
        let (v4, v6) = opts.per_source_net_block_size.unwrap_or((32, 128));
        line("persourcenetblocksize", &format!("{v4}:{v6}"));
        let p = opts.per_source_penalties.clone().unwrap_or_default();
        line(
            "persourcepenalties",
            &if p.enabled {
                let f = |n: u32| format!("{n}.000000");
                let o = |deny: bool| if deny { "deny-all" } else { "permissive" };
                format!(
                    "crash:{} authfail:{} noauth:{} invaliduser:{} grace-exceeded:{} \
                     refuseconnection:{} max:{} min:{} max-sources4:{} max-sources6:{} \
                     overflow:{} overflow6:{}",
                    f(p.crash),
                    f(p.authfail),
                    f(p.noauth),
                    f(p.invalid_user),
                    f(p.grace_exceeded),
                    f(p.refuse_connection),
                    f(p.max),
                    f(p.min),
                    p.max_sources4,
                    p.max_sources6,
                    o(p.overflow_deny_all),
                    o(p.overflow6_deny_all)
                )
            } else {
                "no".to_string()
            },
        );
        line(
            "persourcepenaltyexemptlist",
            opts.per_source_penalty_exempt.as_deref().unwrap_or("none"),
        );
        line(
            "channeltimeout",
            &match &opts.channel_timeouts {
                Some(list) if !list.is_empty() => list
                    .iter()
                    .map(|(t, secs)| format!("{t}={secs}"))
                    .collect::<Vec<_>>()
                    .join(" "),
                _ => "none".to_string(),
            },
        );
        line("exposeauthinfo", yn(opts.expose_auth_info.unwrap_or(false)));
        line(
            "clientaliveinterval",
            &opts.client_alive_interval.unwrap_or(0).to_string(),
        );
        line(
            "clientalivecountmax",
            &opts.client_alive_count_max.unwrap_or(3).to_string(),
        );
        line(
            "unusedconnectiontimeout",
            &match opts.unused_connection_timeout {
                None | Some(0) => "none".to_string(),
                Some(t) => t.to_string(),
            },
        );
        line(
            "requiredrsasize",
            &opts
                .required_rsa_size
                .unwrap_or(DEFAULT_REQUIRED_RSA_SIZE)
                .to_string(),
        );
        line(
            "permitrootlogin",
            match cli.permit_root_login.or(opts.permit_root_login) {
                Some(PermitRootLogin::Yes) => "yes",
                Some(PermitRootLogin::No) => "no",
                _ => "without-password",
            },
        );
        line(
            "pubkeyauthentication",
            yn(opts.pubkey_authentication != Some(false)),
        );
        line(
            "passwordauthentication",
            yn(opts.password_authentication != Some(false)),
        );
        line(
            "kbdinteractiveauthentication",
            yn(opts.kbd_interactive_authentication != Some(false)),
        );
        line(
            "permitemptypasswords",
            yn(opts.permit_empty_passwords == Some(true)),
        );
        line(
            "strictmodes",
            yn(cli.strict_modes.or(opts.strict_modes).unwrap_or(true)),
        );
        line(
            "x11forwarding",
            yn(cli.x11_forward.or(opts.x11_forwarding).unwrap_or(false)),
        );
        line(
            "allowagentforwarding",
            yn(cli
                .agent_forward
                .or(opts.allow_agent_forwarding)
                .unwrap_or(true)),
        );
        line("allowtcpforwarding", fwd(opts.allow_tcp_forwarding));
        line(
            "allowstreamlocalforwarding",
            fwd(opts.allow_stream_local_forwarding),
        );
        line(
            "gatewayports",
            match opts.gateway_ports {
                Some(GatewayPorts::Yes) => "yes",
                Some(GatewayPorts::ClientSpecified) => "clientspecified",
                _ => "no",
            },
        );
        line(
            "disableforwarding",
            yn(opts.disable_forwarding == Some(true)),
        );
        line(
            "permittunnel",
            match opts.permit_tunnel.unwrap_or(0) {
                3 => "yes",
                1 => "point-to-point",
                2 => "ethernet",
                _ => "no",
            },
        );
        line("permittty", yn(opts.permit_tty != Some(false)));
        line("printmotd", yn(opts.print_motd.unwrap_or(true)));
        line("printlastlog", yn(opts.print_last_log.unwrap_or(true)));
        line(
            "compression",
            yn(!matches!(opts.compression, Some(Compression::No))),
        );
        line(
            "loglevel",
            puressh::config::server::LOG_LEVELS[usize::from(opts.log_level.unwrap_or(3).min(7))],
        );
        line(
            "syslogfacility",
            opts.syslog_facility.as_deref().unwrap_or("AUTH"),
        );
        match &opts.authorized_keys_file {
            Some(files) => line("authorizedkeysfile", &files.join(" ")),
            None => line(
                "authorizedkeysfile",
                &default_authorized_keys_files().join(" "),
            ),
        }
        line(
            "authorizedprincipalsfile",
            &none_or(&opts.authorized_principals_file),
        );
        let command = |c: &Option<Vec<String>>| match c {
            Some(c) if !c.is_empty() => c.join(" "),
            _ => "none".to_string(),
        };
        line(
            "authorizedkeyscommand",
            &command(&opts.authorized_keys_command),
        );
        line(
            "authorizedkeyscommanduser",
            &none_or(&opts.authorized_keys_command_user),
        );
        line(
            "authorizedprincipalscommand",
            &command(&opts.authorized_principals_command),
        );
        line(
            "authorizedprincipalscommanduser",
            &none_or(&opts.authorized_principals_command_user),
        );
        line("trustedusercakeys", &none_or(&opts.trusted_user_ca_keys));
        line(
            "revokedkeys",
            &none_or(
                &opts
                    .revoked_keys
                    .as_ref()
                    .filter(|v| !v.is_empty())
                    .map(|v| v.join(" ")),
            ),
        );
        line("banner", &none_or(&opts.banner));
        line("forcecommand", &none_or(&opts.force_command));
        line("chrootdirectory", &none_or(&opts.chroot_directory));
        line("permituserrc", yn(opts.permit_user_rc.unwrap_or(true)));
        line("tcpkeepalive", yn(opts.tcp_keep_alive.unwrap_or(true)));
        line(
            "permituserenvironment",
            opts.permit_user_environment.as_deref().unwrap_or("no"),
        );
        for e in &opts.set_env {
            line("setenv", e);
        }
        line(
            "xauthlocation",
            opts.xauth_location.as_deref().unwrap_or("/usr/bin/xauth"),
        );
        line(
            "pidfile",
            &if opts.pid_file_set {
                none_or(&opts.pid_file)
            } else {
                "/run/sshd.pid".to_string()
            },
        );
        match &opts.authentication_methods {
            Some(m) => line("authenticationmethods", &m.join(" ")),
            None => line("authenticationmethods", "any"),
        }
        let hostport = |hp: &Option<Vec<puressh::config::HostPort>>| match hp {
            None => "any".to_string(),
            Some(v) if v.is_empty() => "none".to_string(),
            // What `any` parses to.
            Some(v) if v.len() == 1 && v[0].host == "*" && v[0].port.is_none() => "any".to_string(),
            Some(v) => v
                .iter()
                .map(|h| match h.port {
                    Some(p) => format!("{}:{p}", h.host),
                    None => format!("{}:*", h.host),
                })
                .collect::<Vec<_>>()
                .join(" "),
        };
        line("permitopen", &hostport(&opts.permit_open));
        line("permitlisten", &hostport(&opts.permit_listen));
        let (bytes, secs) = opts
            .rekey_limit
            .map(|rk| (rk.max_bytes.unwrap_or(0), rk.max_seconds.unwrap_or(0)))
            .unwrap_or((0, 0));
        line("rekeylimit", &format!("{bytes} {secs}"));
        use puressh::hazmat::transport::kex::defaults;
        line("ciphers", &list(&opts.ciphers, defaults::CIPHERS));
        line("macs", &list(&opts.macs, defaults::MACS));
        line("kexalgorithms", &list(&opts.kex_algorithms, defaults::KEX));
        // Certificate algorithms first, as OpenSSH lists them.
        let with_certs: Vec<&str> = puressh::cert::CERT_KEY_NAMES
            .iter()
            .chain(defaults::HOST_KEY)
            .copied()
            .collect();
        line(
            "hostkeyalgorithms",
            &list(&opts.host_key_algorithms, &with_certs),
        );
        line(
            "pubkeyacceptedalgorithms",
            &list(&opts.pubkey_accepted_algorithms, &with_certs),
        );
        line(
            "casignaturealgorithms",
            &list(&opts.ca_signature_algorithms, defaults::HOST_KEY),
        );
        // Features this daemon does not have, shown with the value that
        // describes its behaviour (the config parser only accepts these).
        for (k, v) in [
            ("hostbasedauthentication", "no"),
            ("ignorerhosts", "yes"),
            ("gssapiauthentication", "no"),
            ("usedns", "no"),
            ("fingerprinthash", "SHA256"),
        ] {
            line(k, v);
        }
        let subsystems = opts.subsystems.clone().unwrap_or_default();
        if !subsystems.iter().any(|(n, _)| n == "sftp")
            && opts.subsystem_sftp != Some(false)
            && opts.sftp_enabled != Some(false)
        {
            line("subsystem", "sftp internal-sftp");
        }
        for (name, command) in &subsystems {
            line("subsystem", &format!("{name} {command}"));
        }
        for (k, v) in [
            ("allowusers", &opts.allow_users),
            ("denyusers", &opts.deny_users),
            ("allowgroups", &opts.allow_groups),
            ("denygroups", &opts.deny_groups),
            ("acceptenv", &opts.accept_env),
        ] {
            for item in v {
                line(k, item);
            }
        }
        print!("{out}");
        Ok(0)
    }

    fn parse_args(args: &[String]) -> Result<Cli, String> {
        let mut config_file: Option<String> = None;
        let mut config_options: Vec<String> = Vec::new();
        let mut ports: Vec<u16> = Vec::new();
        let mut dump_config = false;
        let mut connection_spec: Vec<String> = Vec::new();
        let mut test_only = false;
        let mut inetd = false;
        let mut no_detach = false;
        let mut log_stderr = false;
        let mut quiet = false;
        let mut address_family: Option<puressh::config::ServerAddressFamily> = None;
        let mut log_file: Option<String> = None;
        let mut listen_addresses: Vec<String> = Vec::new();
        let mut host_key_files: Vec<String> = Vec::new();
        let mut host_certificate_files: Vec<String> = Vec::new();
        let mut authorized_keys_file: Option<String> = None;
        let mut allowed_users: Vec<String> = Vec::new();
        let mut debug = false;
        let mut sftp: Option<bool> = None;
        let mut sftp_read_only: Option<bool> = None;
        let mut sftp_root: Option<String> = None;
        let mut scp: Option<bool> = None;
        let mut agent_forward: Option<bool> = None;
        let mut x11_forward: Option<bool> = None;
        let mut strict_modes: Option<bool> = None;
        let mut debug_commands = false;
        let mut accept_env: Vec<String> = Vec::new();
        let mut login_grace_time: Option<u32> = None;
        let mut max_startups: Option<u32> = None;
        let mut per_source_max: Option<u32> = None;
        let mut permit_root_login: Option<puressh::config::PermitRootLogin> = None;

        // OpenSSH's getopt: flags may be grouped (`-De`) and a value may
        // follow its option directly (`-E/path`, `-p2222`).
        const VALUE_OPTS: &str = "CEbcfghkopuA";
        const FLAG_OPTS: &str = "46DGQRTdeiqrtV";
        let mut split: Vec<String> = Vec::with_capacity(args.len());
        let mut j = 0;
        while j < args.len() {
            let a = &args[j];
            j += 1;
            let Some(rest) = a
                .strip_prefix('-')
                .filter(|r| !r.starts_with('-') && r.len() > 1)
            else {
                split.push(a.clone());
                continue;
            };
            let chars: Vec<char> = rest.chars().collect();
            let mut k = 0;
            while k < chars.len() {
                let c = chars[k];
                split.push(format!("-{c}"));
                if VALUE_OPTS.contains(c) {
                    let tail: String = chars[k + 1..].iter().collect();
                    if !tail.is_empty() {
                        split.push(tail);
                    }
                    break;
                }
                if !FLAG_OPTS.contains(c) {
                    // Not an OpenSSH option: report it as written.
                    split.truncate(split.len() - 1);
                    split.push(a.clone());
                    break;
                }
                k += 1;
            }
        }
        let args = &split[..];
        let mut i = 0;
        while i < args.len() {
            let a = &args[i];
            match a.as_str() {
                "-f" => {
                    i += 1;
                    let v = args.get(i).ok_or("-f requires a value")?.clone();
                    config_file = Some(v);
                }
                "-p" => {
                    i += 1;
                    let v = args.get(i).ok_or("-p requires a value")?;
                    ports.push(v.parse::<u16>().map_err(|_| "invalid port".to_string())?);
                }
                "-o" => {
                    i += 1;
                    let v = args.get(i).ok_or("-o requires a value")?.clone();
                    config_options.push(v);
                }
                "-t" => test_only = true,
                "-i" => inetd = true,
                "-T" => dump_config = true,
                "-C" => {
                    i += 1;
                    connection_spec.push(args.get(i).ok_or("-C requires a value")?.clone());
                }
                "-4" => address_family = Some(puressh::config::ServerAddressFamily::Inet),
                "-6" => address_family = Some(puressh::config::ServerAddressFamily::Inet6),
                "-c" => {
                    i += 1;
                    let v = args.get(i).ok_or("-c requires a value")?.clone();
                    host_certificate_files.push(v);
                }
                "-E" => {
                    i += 1;
                    log_file = Some(args.get(i).ok_or("-E requires a value")?.clone());
                }
                "-g" => {
                    i += 1;
                    let v = args.get(i).ok_or("-g requires a value")?;
                    login_grace_time = Some(
                        v.trim_end_matches('s')
                            .parse::<u32>()
                            .map_err(|_| "invalid -g (seconds)".to_string())?,
                    );
                }
                // `-e`: log to stderr rather than syslog; `-q`: log nothing.
                "-e" => log_stderr = true,
                "-q" => quiet = true,
                "-D" => no_detach = true,
                // OpenSSH compatibility no-ops: `-r` no re-exec, `-k`
                // obsolete key regeneration.
                "-r" => {}
                "-k" => i += 1,
                "-b" => {
                    i += 1;
                    let v = args.get(i).ok_or("-b requires a value")?.clone();
                    listen_addresses.push(v);
                }
                "-h" => {
                    i += 1;
                    let v = args.get(i).ok_or("-h requires a value")?.clone();
                    host_key_files.push(v);
                }
                "--host-certificate" => {
                    i += 1;
                    let v = args
                        .get(i)
                        .ok_or("--host-certificate requires a value")?
                        .clone();
                    host_certificate_files.push(v);
                }
                "-A" => {
                    i += 1;
                    let v = args.get(i).ok_or("-A requires a value")?.clone();
                    authorized_keys_file = Some(v);
                }
                "-u" => {
                    i += 1;
                    let v = args.get(i).ok_or("-u requires a value")?.clone();
                    // OpenSSH's `-u len` (utmp host-name length) is numeric
                    // and ignorable; anything else is puressh's allowed user.
                    if v.parse::<u32>().is_err() {
                        allowed_users.push(v);
                    }
                }
                "-d" => debug = true,
                "--no-sftp" => sftp = Some(false),
                "--sftp-read-only" => sftp_read_only = Some(true),
                "--sftp-root" => {
                    i += 1;
                    let v = args.get(i).ok_or("--sftp-root requires a value")?.clone();
                    sftp_root = Some(v);
                }
                "--no-scp" => scp = Some(false),
                "--no-agent-forward" => agent_forward = Some(false),
                "--x11-forward" => x11_forward = Some(true),
                "--no-x11-forward" => x11_forward = Some(false),
                "--no-strict-modes" => strict_modes = Some(false),
                "--debug-commands" => debug_commands = true,
                "--accept-env" => {
                    i += 1;
                    let v = args.get(i).ok_or("--accept-env requires a value")?.clone();
                    accept_env.push(v);
                }
                "--login-grace-time" => {
                    i += 1;
                    let v = args.get(i).ok_or("--login-grace-time requires a value")?;
                    login_grace_time = Some(
                        v.parse::<u32>()
                            .map_err(|_| "invalid --login-grace-time".to_string())?,
                    );
                }
                "--max-startups" => {
                    i += 1;
                    let v = args.get(i).ok_or("--max-startups requires a value")?;
                    max_startups = Some(
                        v.parse::<u32>()
                            .map_err(|_| "invalid --max-startups".to_string())?,
                    );
                }
                "--per-source-max" => {
                    i += 1;
                    let v = args.get(i).ok_or("--per-source-max requires a value")?;
                    per_source_max = Some(
                        v.parse::<u32>()
                            .map_err(|_| "invalid --per-source-max".to_string())?,
                    );
                }
                "--permit-root-login" => {
                    use puressh::config::PermitRootLogin;
                    i += 1;
                    let v = args.get(i).ok_or("--permit-root-login requires a value")?;
                    permit_root_login = Some(match v.to_ascii_lowercase().as_str() {
                        "yes" | "true" | "on" => PermitRootLogin::Yes,
                        "no" | "false" | "off" => PermitRootLogin::No,
                        "prohibit-password" | "without-password" => {
                            PermitRootLogin::ProhibitPassword
                        }
                        other => {
                            return Err(format!(
                                "invalid --permit-root-login {other:?} \
                                 (expected yes, no, or prohibit-password)"
                            ));
                        }
                    });
                }
                s if s.starts_with('-') => {
                    return Err(format!("unknown flag: {s}"));
                }
                _ => return Err(format!("unexpected argument: {a}")),
            }
            i += 1;
        }

        // `-h` validation moves to run() after config merge so a config file
        // that supplies `HostKey` is sufficient.
        Ok(Cli {
            config_file,
            config_options,
            ports,
            dump_config,
            connection_spec,
            test_only,
            inetd,
            no_detach,
            address_family,
            log_file,
            log_stderr,
            quiet,
            listen_addresses,
            host_key_files,
            host_certificate_files,
            authorized_keys_file,
            allowed_users,
            debug,
            sftp,
            sftp_read_only,
            sftp_root,
            scp,
            agent_forward,
            x11_forward,
            strict_modes,
            debug_commands,
            accept_env,
            login_grace_time,
            max_startups,
            per_source_max,
            permit_root_login,
        })
    }

    /// Load each `HostKey`, then for each `HostCertificate` path wrap the
    /// matching plain host key (paired by embedded-key equality) in a
    /// `CertHostKey` so KEX can advertise the certificate algorithm. The
    /// certificate-wrapped key is inserted *ahead of* the plain key it
    /// certifies, so `build_server_kexinit` advertises the cert name first.
    fn load_host_keys_with_certs(
        key_paths: &[String],
        cert_paths: &[String],
        strict_modes: bool,
        agent: Option<&str>,
    ) -> Result<Vec<Box<dyn HostKey + Send + Sync>>, String> {
        use puressh::cert::Certificate;
        use puressh::hostkey::CertHostKey;
        use std::sync::Arc;

        // Load plain keys as shared (Arc) signers, retaining their public blob
        // for cert pairing. Sharing lets the same key material back both the
        // plain host-key entry and a CertHostKey wrapper without re-reading the
        // private key file.
        struct Loaded {
            blob: Vec<u8>,
            key: Arc<dyn HostKey + Send + Sync>,
        }
        let mut loaded: Vec<Loaded> = Vec::new();
        for path in key_paths {
            // As in OpenSSH, a host key that cannot be used (missing file,
            // unsupported type such as DSA, bad permissions) is reported and
            // skipped; only having no usable key at all is fatal.
            let loaded_key = (|| -> Result<Box<dyn HostKey + Send>, String> {
                if strict_modes {
                    check_owner_mode(path, 0o077, "host key")?;
                }
                let pem = std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?;
                let priv_key = PrivateKey::parse_openssh_pem(&pem, None)
                    .map_err(|e| format!("parse {path}: {e}"))?;
                priv_key
                    .into_host_key()
                    .map_err(|e| format!("convert {path}: {e}"))
            })();
            // No private key there: with `HostKeyAgent`, its public key (the
            // file itself or `<path>.pub`) is signed for by the agent.
            let key: Arc<dyn HostKey + Send + Sync> = match loaded_key {
                // PrivateKey::into_host_key returns `Box<dyn HostKey + Send>` —
                // upgrade to `Send + Sync` by wrapping. Our concrete signers
                // (Ed25519, ECDSA, RSA) hold only `Sync`-safe types internally;
                // we expose this via a small thunk that just defers to the boxed
                // signer.
                Ok(hk) => Arc::from(SyncHostKey::wrap(hk)),
                Err(e) => match agent.map(|sock| AgentSocketHostKey::load(sock, path)) {
                    Some(Ok(k)) => Arc::new(k),
                    Some(Err(agent_err)) => {
                        eprintln!("sshd: warning: unable to load host key {path}: {agent_err}");
                        continue;
                    }
                    None => {
                        eprintln!("sshd: warning: unable to load host key: {e}");
                        continue;
                    }
                },
            };
            loaded.push(Loaded {
                blob: key.public_blob(),
                key,
            });
        }

        // Parse all host certificates up front, pairing by embedded-key
        // equality below.
        let mut certs: Vec<(Certificate, &'static str)> = Vec::new();
        for path in cert_paths {
            let text = std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?;
            let cert = Certificate::parse_openssh_line(&text)
                .map_err(|e| format!("{path}: parse host certificate: {e}"))?;
            if !matches!(cert.cert_type, puressh::cert::CertType::Host) {
                return Err(format!("{path}: not a host certificate"));
            }
            let cert_name = puressh::cert::cert_name_for_key_type(cert.embedded_algorithm())
                .ok_or_else(|| format!("{path}: unsupported certificate family"))?;
            certs.push((cert, cert_name));
        }

        // Build the output list. For each loaded key, if a certificate
        // certifies it, emit the CertHostKey first (so KEX advertises the cert
        // name ahead of the plain key), then the plain key.
        let mut out: Vec<Box<dyn HostKey + Send + Sync>> = Vec::new();
        for item in loaded {
            if let Some(pos) = certs
                .iter()
                .position(|(c, _)| c.embedded_pubkey_blob == item.blob)
            {
                let (cert, cert_name) = certs.remove(pos);
                let cert_key =
                    CertHostKey::new(Box::new(SharedSigner(item.key.clone())), &cert, cert_name)
                        .map_err(|e| format!("host certificate does not match its key: {e}"))?;
                out.push(Box::new(cert_key));
            }
            out.push(Box::new(SharedSigner(item.key)));
        }

        if let Some((_, name)) = certs.first() {
            return Err(format!(
                "HostCertificate present but no matching HostKey for {name}"
            ));
        }
        if out.is_empty() {
            return Err(format!("no usable host key among {key_paths:?}"));
        }
        Ok(out)
    }

    /// A host key whose private half is held by an `ssh-agent`
    /// (`HostKeyAgent`): each signature is one request on a fresh connection
    /// to the agent's socket (connections are never shared between the
    /// per-connection processes).
    struct AgentSocketHostKey {
        socket: String,
        blob: Vec<u8>,
        algorithm: &'static str,
        /// `SSH_AGENT_RSA_SHA2_*` for an RSA key (0: SHA-1).
        flags: u32,
        rsa: bool,
    }

    impl AgentSocketHostKey {
        /// The public key of host key `path` (the file, or `<path>.pub`),
        /// which the agent at `socket` must hold.
        fn load(socket: &str, path: &str) -> Result<Self, String> {
            let parse = |p: &str| {
                std::fs::read_to_string(p).ok().and_then(|t| {
                    t.lines()
                        .find(|l| !l.trim().is_empty())
                        .and_then(|l| PublicKey::parse_authorized_keys_line(l.trim()).ok())
                })
            };
            let public = parse(path)
                .or_else(|| parse(&format!("{path}.pub")))
                .ok_or_else(|| format!("{path}: no private or public key"))?;
            let blob = public.wire_blob();
            let mut agent = puressh::agent::Agent::connect(socket)
                .map_err(|e| format!("HostKeyAgent {socket}: {e}"))?;
            let held = agent
                .identities()
                .map_err(|e| format!("HostKeyAgent {socket}: {e}"))?
                .iter()
                .any(|i| i.key_blob == blob);
            if !held {
                return Err(format!("{path}: the agent does not hold this key"));
            }
            let rsa = public.algorithm() == "ssh-rsa";
            let (algorithm, flags) = if rsa {
                ("rsa-sha2-512", AGENT_RSA_SHA2_512)
            } else {
                (public.algorithm(), 0)
            };
            Ok(AgentSocketHostKey {
                socket: socket.to_string(),
                blob,
                algorithm,
                flags,
                rsa,
            })
        }
    }

    const AGENT_RSA_SHA2_256: u32 = 2;
    const AGENT_RSA_SHA2_512: u32 = 4;

    impl HostKey for AgentSocketHostKey {
        fn algorithm(&self) -> &'static str {
            self.algorithm
        }
        fn public_blob(&self) -> Vec<u8> {
            self.blob.clone()
        }
        fn sign(&self, msg: &[u8]) -> puressh::Result<Vec<u8>> {
            puressh::agent::Agent::connect(&self.socket)?.sign(&self.blob, msg, self.flags)
        }
        /// The same RSA key signing with the hash `algs` names.
        fn upgraded_for(&self, algs: &str) -> Option<Box<dyn HostKey>> {
            if !self.rsa {
                return None;
            }
            let listed = |n: &str| algs.split(',').any(|a| a.trim() == n);
            let (algorithm, flags) = if listed("rsa-sha2-512") {
                ("rsa-sha2-512", AGENT_RSA_SHA2_512)
            } else if listed("rsa-sha2-256") {
                ("rsa-sha2-256", AGENT_RSA_SHA2_256)
            } else if listed("ssh-rsa") && puressh::hostkey::allow_rsa_sha1() {
                ("ssh-rsa", 0)
            } else {
                return None;
            };
            (algorithm != self.algorithm).then(|| {
                Box::new(AgentSocketHostKey {
                    socket: self.socket.clone(),
                    blob: self.blob.clone(),
                    algorithm,
                    flags,
                    rsa: true,
                }) as Box<dyn HostKey>
            })
        }
    }

    /// A `HostKey` backed by a shared `Arc` signer, so one loaded private key
    /// can stand behind both a plain host-key entry and its `CertHostKey`.
    struct SharedSigner(std::sync::Arc<dyn HostKey + Send + Sync>);

    impl HostKey for SharedSigner {
        fn algorithm(&self) -> &'static str {
            self.0.algorithm()
        }
        fn public_blob(&self) -> Vec<u8> {
            self.0.public_blob()
        }
        fn sign(&self, msg: &[u8]) -> puressh::Result<Vec<u8>> {
            self.0.sign(msg)
        }
        fn upgraded_for(&self, algs: &str) -> Option<Box<dyn HostKey>> {
            self.0.upgraded_for(algs)
        }
    }

    /// Refuse to read `path` when its Unix mode shares any forbidden bit
    /// with `forbidden_mask` (e.g. `0o077` for host keys — "not readable
    /// by group or world"). Matches OpenSSH's `StrictModes`. The
    /// `--no-strict-modes` CLI flag short-circuits this check.
    ///
    /// Beyond the mode bits, this also enforces OpenSSH's ownership and
    /// ancestor-writability rules (`secure_filename`): the file must be
    /// owned by root (uid 0) or, when `allowed_uid` is set, the target
    /// user; and no path component from the file up to `/` may be group-
    /// or world-writable. A correctly-permissioned root- or owner-owned
    /// file in non-writable directories continues to pass unchanged.
    /// The ancestor walk + ownership check mirror `validate_chroot_dir`.
    ///
    /// `kind` is just a human label for the error message ("host key",
    /// "authorized_keys file").
    /// Checks on a server-wide file (host key, TrustedUserCAKeys): none of
    /// the `forbidden_mask` mode bits, and owned by root or by the user sshd
    /// runs as. Unlike [`check_mode_strict`], its directories are not
    /// checked; OpenSSH checks host keys no further.
    fn check_owner_mode(path: &str, forbidden_mask: u32, kind: &str) -> Result<(), String> {
        use std::os::unix::fs::MetadataExt;
        let md = std::fs::metadata(path).map_err(|e| format!("stat {path}: {e}"))?;
        let mode = md.mode() & 0o777;
        if mode & forbidden_mask != 0 {
            return Err(format!(
                "{kind} {path}: insecure mode 0o{mode:o} (must not have any of \
                 0o{forbidden_mask:o}); fix with `chmod 0{:o} {path}` or override with \
                 --no-strict-modes",
                mode & !forbidden_mask
            ));
        }
        let euid = nix::unistd::geteuid().as_raw();
        if md.uid() != 0 && md.uid() != euid {
            return Err(format!(
                "{kind} {path}: must be owned by root or uid {euid}, is uid {}; \
                 override with --no-strict-modes",
                md.uid()
            ));
        }
        Ok(())
    }

    fn check_mode_strict(
        path: &str,
        forbidden_mask: u32,
        kind: &str,
        allowed_uid: Option<nix::unistd::Uid>,
    ) -> Result<(), String> {
        use std::os::unix::fs::MetadataExt;
        let md = std::fs::metadata(path).map_err(|e| format!("stat {path}: {e}"))?;
        if !md.is_file() {
            return Err(format!("{kind} {path}: not a regular file"));
        }
        let mode = md.mode() & 0o777;
        if (mode as u32) & forbidden_mask != 0 {
            return Err(format!(
                "{kind} {path}: insecure mode 0o{mode:o} (must not have any of 0o{forbidden_mask:o}); \
                 fix with `chmod 0{:o} {path}` or override with --no-strict-modes",
                mode & !forbidden_mask & 0o777
            ));
        }
        // Ownership: the file must be owned by root, or by the target user
        // when one is known. A file owned by an untrusted third party is
        // rejected even if its mode bits look benign.
        let allowed = allowed_uid.map(|u| u.as_raw());
        if md.uid() != 0 && Some(md.uid()) != allowed {
            return Err(format!(
                "{kind} {path}: must be owned by root (uid 0){}, is uid {}; \
                 override with --no-strict-modes",
                allowed.map(|u| format!(" or uid {u}")).unwrap_or_default(),
                md.uid()
            ));
        }
        // Ancestor walk: no directory from the file up to / may be group-
        // or world-writable, otherwise a non-trusted user could swap the
        // file (or a parent dir) out from under us. Same logic as
        // validate_chroot_dir, but each component may be owned by root or
        // the target user (OpenSSH's secure_filename allows the owner).
        let mut cur = std::path::Path::new(path).parent();
        while let Some(p) = cur {
            // An empty parent ("" from a relative leaf) means we've run out
            // of components to check.
            if p.as_os_str().is_empty() {
                break;
            }
            let dmd = std::fs::metadata(p).map_err(|e| format!("stat {}: {e}", p.display()))?;
            if dmd.uid() != 0 && Some(dmd.uid()) != allowed {
                return Err(format!(
                    "{kind} {path}: ancestor {} is owned by uid {} (must be root{}); \
                     override with --no-strict-modes",
                    p.display(),
                    dmd.uid(),
                    allowed.map(|u| format!(" or uid {u}")).unwrap_or_default(),
                ));
            }
            if dmd.mode() & 0o022 != 0 {
                return Err(format!(
                    "{kind} {path}: ancestor {} is group/world-writable (mode 0o{:o}); \
                     override with --no-strict-modes",
                    p.display(),
                    dmd.mode() & 0o777
                ));
            }
            cur = p.parent();
        }
        Ok(())
    }

    struct SyncHostKey {
        inner: std::sync::Mutex<Box<dyn HostKey + Send>>,
        algorithm: &'static str,
        blob: Vec<u8>,
    }

    impl SyncHostKey {
        fn wrap(hk: Box<dyn HostKey + Send>) -> Box<dyn HostKey + Send + Sync> {
            let algorithm_str = hk.algorithm();
            let blob = hk.public_blob();
            Box::new(SyncHostKey {
                algorithm: algorithm_str,
                blob,
                inner: std::sync::Mutex::new(hk),
            })
        }
    }

    impl HostKey for SyncHostKey {
        fn algorithm(&self) -> &'static str {
            self.algorithm
        }
        fn public_blob(&self) -> Vec<u8> {
            self.blob.clone()
        }
        fn sign(&self, msg: &[u8]) -> puressh::Result<Vec<u8>> {
            let g = self
                .inner
                .lock()
                .map_err(|_| puressh::Error::Crypto("host-key mutex poisoned"))?;
            g.sign(msg)
        }
        fn upgraded_for(&self, algs: &str) -> Option<Box<dyn HostKey>> {
            self.inner.lock().ok()?.upgraded_for(algs)
        }
    }

    /// The parsed contents of one user's `authorized_keys` file(s).
    #[derive(Clone, Debug, Default)]
    struct AuthorizedKeys {
        /// Wire blobs of directly-authorized plain keys.
        blobs: Vec<Vec<u8>>,
        /// `cert-authority` lines: the CA key blob plus, when the line carries
        /// a `principals="a,b"` option, the principal patterns a certificate
        /// must match (replacing the login-user-must-be-a-principal rule).
        /// `None` ⇒ no `principals=` option on that line.
        cas: Vec<(Vec<u8>, Option<Vec<String>>)>,
        /// The options of each `blobs` line (same index; a missing entry is
        /// an unrestricted line).
        options: Vec<Arc<puressh::key::AuthorizedKeyOptions>>,
        /// The options of each `cas` line (same index, likewise).
        ca_options: Vec<Arc<puressh::key::AuthorizedKeyOptions>>,
    }

    impl AuthorizedKeys {
        fn append(&mut self, mut other: AuthorizedKeys) {
            // Keep the option lists aligned with their key lists.
            self.options.resize_with(self.blobs.len(), Default::default);
            self.ca_options
                .resize_with(self.cas.len(), Default::default);
            other
                .options
                .resize_with(other.blobs.len(), Default::default);
            other
                .ca_options
                .resize_with(other.cas.len(), Default::default);
            self.blobs.append(&mut other.blobs);
            self.cas.append(&mut other.cas);
            self.options.append(&mut other.options);
            self.ca_options.append(&mut other.ca_options);
        }
    }

    /// Whether an `authorized_keys` line applies to this connection: its
    /// `from=` patterns (addresses, `*`/`?` globs, CIDRs, `!` to exclude)
    /// admit the client, and its `expiry-time=` has not passed.
    fn key_line_applies(
        opts: &puressh::key::AuthorizedKeyOptions,
        peer: Option<&str>,
        debug: bool,
    ) -> bool {
        if let Some(from) = &opts.from {
            let Some(ip) = peer.and_then(parse_peer_ip) else {
                return false;
            };
            let ip_s = ip.to_string();
            let mut admitted = false;
            for pat in from.split(',').map(str::trim).filter(|p| !p.is_empty()) {
                let (negated, p) = match pat.strip_prefix('!') {
                    Some(p) => (true, p),
                    None => (false, pat),
                };
                let hit = if p.contains('/') {
                    cidr_matches(p, ip)
                } else {
                    puressh::config::host_matches(&[puressh::config::HostPattern::parse(p)], &ip_s)
                };
                if hit && negated {
                    admitted = false;
                    break;
                }
                admitted |= hit;
            }
            if !admitted {
                if debug {
                    eprintln!("sshd: authorized_keys: from=\"{from}\" does not admit {ip_s}");
                }
                return false;
            }
        }
        if let Some(exp) = &opts.expiry_time {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs() as i64)
                .unwrap_or(0);
            let offset = {
                let tt = now as libc::time_t;
                // SAFETY: `tm` is plain data; localtime_r fills it or fails.
                let mut tm: libc::tm = unsafe { std::mem::zeroed() };
                if unsafe { libc::localtime_r(&tt, &mut tm) }.is_null() {
                    0
                } else {
                    tm.tm_gmtoff as i64
                }
            };
            match puressh::sshsig::parse_time(exp, offset) {
                Some(t) if now < t => {}
                _ => {
                    if debug {
                        eprintln!("sshd: authorized_keys: key expired (expiry-time {exp})");
                    }
                    return false;
                }
            }
        }
        true
    }

    /// The OpenSSH default `AuthorizedKeysFile` list, relative to the login
    /// user's home directory.
    fn default_authorized_keys_files() -> Vec<String> {
        vec![
            ".ssh/authorized_keys".to_string(),
            ".ssh/authorized_keys2".to_string(),
        ]
    }

    /// Parse an `authorized_keys` file: directly-authorized keys, plus the CA
    /// keys (and any `principals=` restriction) from `cert-authority` lines.
    /// Lines that fail the strict option-aware parser are logged and skipped.
    ///
    /// Under StrictModes the file must be owned by root or `owner_uid` (the
    /// login user, for a per-user file; `None` for the global `-A` file), not
    /// group/world writable, and every ancestor directory must satisfy the
    /// same rule — so a user cannot plant keys in another user's file, and a
    /// writable `~` or `~/.ssh` cannot be used to swap the file out.
    fn load_authorized_keys_and_cas(
        path: &str,
        strict_modes: bool,
        owner_uid: Option<nix::unistd::Uid>,
    ) -> Result<AuthorizedKeys, String> {
        if strict_modes {
            check_mode_strict(path, 0o022, "authorized_keys file", owner_uid)?;
        }
        let body = std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?;
        Ok(parse_authorized_keys(&body, path))
    }

    /// Parse `authorized_keys` lines (a file's or an `AuthorizedKeysCommand`'s
    /// output); `source` names them in warnings about skipped lines.
    fn parse_authorized_keys(body: &str, source: &str) -> AuthorizedKeys {
        let mut out = AuthorizedKeys::default();
        for (idx, line) in body.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            match PublicKey::parse_authorized_keys_line_with_options(trimmed) {
                Ok((blob, opts)) => {
                    if opts.cert_authority {
                        // The option parser yields an empty list both for a
                        // missing `principals=` and for `principals=""`; the
                        // latter must restrict (to nothing), never widen, so
                        // the raw line is consulted for the option's presence.
                        let restricted =
                            !opts.principals.is_empty() || trimmed.contains("principals=");
                        let principals = restricted.then(|| opts.principals.clone());
                        out.cas.push((blob, principals));
                        out.ca_options.push(Arc::new(opts));
                    } else {
                        out.blobs.push(blob);
                        out.options.push(Arc::new(opts));
                    }
                }
                Err(e) => {
                    eprintln!("sshd: skipping {source} line {}: {e}", idx + 1);
                }
            }
        }
        out
    }

    /// Knock keys (a user's authorized keys), read on demand: the knock state
    /// asks for a user's keys only when a well-formed knock names that user,
    /// and caches the answer for 60 s. Any user may knock unless `KnockUsers`
    /// narrows it; users outside it are refused without touching the disk.
    /// Who may actually log in is still decided by the usual access checks
    /// and authentication on the rendezvous connection.
    #[derive(Clone)]
    #[cfg_attr(not(feature = "knock"), allow(dead_code))]
    struct KnockKeys {
        /// `KnockUsers`, or `None` for any user.
        users: Option<Vec<String>>,
        /// `-A` mode: the one user the global file authorizes, and its keys.
        global: Option<(String, Arc<AuthorizedKeys>)>,
        files: Vec<String>,
        strict_modes: bool,
        debug: bool,
    }

    /// Plain keys only: certificate authorities are not knock material, a
    /// knock names a concrete key.
    #[cfg(feature = "knock")]
    impl puressh::knock::KnockKeySource for KnockKeys {
        fn keys_for(&mut self, user: &str) -> Vec<Vec<u8>> {
            if let Some(users) = &self.users
                && !users.iter().any(|u| u == user)
            {
                return Vec::new();
            }
            let keys = match &self.global {
                Some((only, g)) if only == user => g.blobs.clone(),
                Some(_) => Vec::new(),
                None => {
                    load_user_authorized_keys(user, &self.files, self.strict_modes, self.debug)
                        .blobs
                }
            };
            if self.debug {
                eprintln!("sshd: knock: loaded {} key(s) for {user}", keys.len());
            }
            keys
        }
    }

    /// `KnockListen` value → `host:port`, defaulting the port to the SSH one.
    #[cfg(feature = "knock")]
    fn knock_listen_addr(spec: &str, port: u16) -> String {
        if spec.starts_with('[') {
            if spec.contains("]:") {
                spec.to_string()
            } else {
                format!("{spec}:{port}")
            }
        } else if spec.contains("::") || spec.matches(':').count() > 1 {
            format!("[{spec}]:{port}")
        } else if spec.contains(':') {
            spec.to_string()
        } else {
            format!("{spec}:{port}")
        }
    }

    /// The daemon's knock sockets (`docs/knock.md`): UDP knock servers whose
    /// rendezvous connections join the accept loop. Empty when `KnockListen`
    /// is unset; a no-op shell when built without the `knock` feature.
    struct KnockFrontend {
        #[cfg(feature = "knock")]
        servers: Vec<puressh::knock::KnockServer>,
    }

    #[cfg(feature = "knock")]
    impl KnockFrontend {
        /// Bind one knock server per `KnockListen` address, signing ACCEPTs
        /// with the daemon's plain host keys.
        fn bind(
            g: &puressh::config::ServerOptions,
            port: u16,
            keys: KnockKeys,
            host_key_files: &[String],
            debug: bool,
        ) -> Result<Self, String> {
            let servers = Self::bind_servers(g, port, &keys, host_key_files, debug)?;
            Ok(Self { servers })
        }

        fn bind_servers(
            g: &puressh::config::ServerOptions,
            port: u16,
            keys: &KnockKeys,
            host_key_files: &[String],
            debug: bool,
        ) -> Result<Vec<puressh::knock::KnockServer>, String> {
            use puressh::knock::{
                KnockHostKey, KnockServer, KnockServerConfig, KnockState, unix_ms,
            };
            if g.knock_listen.is_empty() {
                return Ok(Vec::new());
            }
            let mut host_keys: Vec<KnockHostKey> = Vec::new();
            for path in host_key_files {
                // Unusable keys were already reported by the main loader.
                let Ok(pem) = std::fs::read_to_string(path) else {
                    continue;
                };
                if let Ok(key) =
                    PrivateKey::parse_openssh_pem(&pem, None).and_then(|k| k.into_host_key_sync())
                {
                    host_keys.push(Arc::from(key));
                }
            }
            let mut cfg = KnockServerConfig::default();
            if let Some(w) = g.knock_window {
                cfg.window_secs = w as u16;
            }
            if let Some(s) = g.knock_clock_skew {
                cfg.clock_skew_ms = s as u64 * 1000;
            }
            if let Some(n) = g.knock_max_pending {
                cfg.max_pending = n;
            }
            match &keys.users {
                Some(u) => eprintln!("sshd: knock: users {u:?} may knock; keys read on demand"),
                None => eprintln!("sshd: knock: any user may knock; keys read on demand"),
            }
            let mut out = Vec::new();
            for spec in &g.knock_listen {
                let addr = knock_listen_addr(spec, port);
                let state =
                    KnockState::new(cfg.clone(), keys.clone(), host_keys.clone(), unix_ms());
                let mut ks = KnockServer::bind(&addr, state)
                    .map_err(|e| format!("knock: bind udp {addr}: {e}"))?;
                if let Some((lo, hi)) = g.knock_ports {
                    ks.set_port_range(lo, hi);
                }
                if debug {
                    ks.set_logger(|ev| eprintln!("sshd: knock: {ev:?}"));
                }
                eprintln!("sshd: knock listening on udp {addr}");
                out.push(ks);
            }
            Ok(out)
        }

        fn next_wakeup(&self) -> Option<std::time::Instant> {
            self.servers.iter().filter_map(|k| k.next_wakeup()).min()
        }

        fn poll_fds(&self) -> Vec<std::os::fd::BorrowedFd<'_>> {
            self.servers.iter().flat_map(|k| k.poll_fds()).collect()
        }

        /// Rendezvous connections that presented their token, with the
        /// knock's user.
        fn process(&mut self) -> Vec<(std::net::TcpStream, std::net::SocketAddr, String)> {
            let mut out = Vec::new();
            for ks in &mut self.servers {
                out.extend(ks.process().into_iter().map(|c| (c.stream, c.peer, c.user)));
            }
            out
        }
    }

    #[cfg(not(feature = "knock"))]
    impl KnockFrontend {
        fn bind(
            g: &puressh::config::ServerOptions,
            _port: u16,
            _keys: KnockKeys,
            _host_key_files: &[String],
            _debug: bool,
        ) -> Result<Self, String> {
            if !g.knock_listen.is_empty() {
                return Err("KnockListen: this sshd was built without the `knock` feature".into());
            }
            Ok(Self {})
        }

        fn next_wakeup(&self) -> Option<std::time::Instant> {
            None
        }

        fn poll_fds(&self) -> Vec<std::os::fd::BorrowedFd<'_>> {
            Vec::new()
        }

        fn process(&mut self) -> Vec<(std::net::TcpStream, std::net::SocketAddr, String)> {
            Vec::new()
        }
    }

    /// OpenSSH's default `RequiredRSASize`.
    const DEFAULT_REQUIRED_RSA_SIZE: u32 = 1024;

    /// Bit length of the modulus of an `ssh-rsa` key blob; `None` for any
    /// other key type (or a malformed blob, which never authenticates).
    fn rsa_modulus_bits(blob: &[u8]) -> Option<usize> {
        match PublicKey::parse_wire_blob(blob).ok()? {
            PublicKey::Rsa { n, .. } => {
                let n: Vec<u8> = n.into_iter().skip_while(|b| *b == 0).collect();
                let lead = *n.first()?;
                Some((n.len() - 1) * 8 + (8 - lead.leading_zeros() as usize))
            }
            _ => None,
        }
    }

    /// Expand every `AuthorizedKeysFile` template for `user` and read the
    /// files that exist, StrictModes-checked against `user`'s uid. Any
    /// failure (unknown user, bad template, StrictModes refusal,
    /// unreadable file) contributes no keys — never a wider set. A file
    /// that simply does not exist is silently skipped, as in OpenSSH.
    fn load_user_authorized_keys(
        user: &str,
        authorized_keys_files: &[String],
        strict_modes: bool,
        debug: bool,
    ) -> AuthorizedKeys {
        let mut out = AuthorizedKeys::default();
        let info = match lookup_user(user) {
            Ok(i) => i,
            Err(e) => {
                if debug {
                    eprintln!("sshd: AuthorizedKeysFile: user lookup failed for {user}: {e}");
                }
                return out;
            }
        };
        for template in authorized_keys_files {
            let path = match expand_pct_tokens(template, &info) {
                Ok(p) => p,
                Err(e) => {
                    if debug {
                        eprintln!("sshd: AuthorizedKeysFile: bad path template {template:?}: {e}");
                    }
                    continue;
                }
            };
            let path = if path.starts_with('/') {
                path
            } else {
                let home = if info.home_str.is_empty() {
                    "/"
                } else {
                    info.home_str.as_str()
                };
                format!("{}/{path}", home.trim_end_matches('/'))
            };
            // A glob names every matching file, as in OpenSSH.
            let paths = puressh::config::glob_paths(&path);
            if paths.is_empty() && debug {
                eprintln!("sshd: AuthorizedKeysFile {path}: not present");
            }
            for path in paths {
                let path = path.to_string_lossy();
                match load_authorized_keys_and_cas(&path, strict_modes, Some(info.uid)) {
                    Ok(set) => {
                        if debug {
                            eprintln!(
                                "sshd: AuthorizedKeysFile {path}: {} key(s), {} cert-authority \
                                 line(s)",
                                set.blobs.len(),
                                set.cas.len()
                            );
                        }
                        out.append(set);
                    }
                    Err(e) => {
                        if debug {
                            eprintln!("sshd: AuthorizedKeysFile {path}: {e}");
                        }
                    }
                }
            }
        }
        out
    }

    /// The longest an `AuthorizedKeysCommand` / `AuthorizedPrincipalsCommand`
    /// may run (OpenSSH bounds it only by LoginGraceTime).
    const AUTH_COMMAND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
    /// The most output read from such a command.
    const AUTH_COMMAND_OUTPUT_MAX: usize = 4 << 20;

    /// Expand the `%` tokens of one command argument; `%%` is a literal `%`.
    /// A token the command kind does not define refuses the command, as
    /// OpenSSH refuses the configuration.
    fn expand_command_arg(arg: &str, tokens: &[(char, String)]) -> Result<String, String> {
        let mut out = String::with_capacity(arg.len());
        let mut chars = arg.chars();
        while let Some(c) = chars.next() {
            if c != '%' {
                out.push(c);
                continue;
            }
            match chars.next() {
                Some('%') => out.push('%'),
                Some(t) => match tokens.iter().find(|(k, _)| *k == t) {
                    Some((_, v)) => out.push_str(v),
                    None => return Err(format!("unknown token %{t}")),
                },
                None => return Err("trailing %".into()),
            }
        }
        Ok(out)
    }

    /// A key or certificate blob as command tokens: its SHA256 fingerprint,
    /// base64 encoding and type name.
    fn blob_tokens(blob: &[u8]) -> (String, String, String) {
        use purecrypto::hash::{Digest, Sha256};
        let b64 = purecrypto::der::base64_encode(&Sha256::digest(blob));
        let fp = format!("SHA256:{}", b64.trim_end_matches('='));
        let kind = blob
            .get(..4)
            .map(|l| u32::from_be_bytes([l[0], l[1], l[2], l[3]]) as usize)
            .and_then(|n| blob.get(4..4 + n))
            .and_then(|t| std::str::from_utf8(t).ok())
            .unwrap_or("")
            .to_string();
        (fp, purecrypto::der::base64_encode(blob), kind)
    }

    /// The tokens every authorization command knows: `%C` (client address
    /// and port, server address and port), `%D` (routing domain, none here),
    /// `%h`, `%U` and `%u` (the login user's home, uid and name).
    fn connection_tokens(info: &UserInfo) -> Vec<(char, String)> {
        let endpoints = conn_addrs()
            .map(|(peer, local)| {
                let (lip, lport) =
                    local.map_or((String::new(), 0), |l| (l.ip().to_string(), l.port()));
                format!("{} {} {lip} {lport}", peer.ip(), peer.port())
            })
            .unwrap_or_default();
        vec![
            ('C', endpoints),
            ('D', String::new()),
            ('h', info.home_str.clone()),
            ('U', info.uid.as_raw().to_string()),
            ('u', info.name.clone()),
        ]
    }

    /// Run an `AuthorizedKeysCommand` / `AuthorizedPrincipalsCommand` as
    /// OpenSSH does. `argv[0]` must be an absolute path to a regular file
    /// that, with every directory above it, is owned by root (or by this
    /// daemon's own user when it is not root) and writable by nobody else;
    /// StrictModes off skips that check. The command runs as `run_as`
    /// (`*CommandUser`, required) with the minimal environment OpenSSH gives
    /// it, stdin from `/dev/null` and stderr discarded unless debugging. Its
    /// output counts only when it exits with status 0 within
    /// [`AUTH_COMMAND_TIMEOUT`].
    fn run_auth_command(
        kind: &str,
        argv: &[String],
        run_as: Option<&str>,
        strict_modes: bool,
        debug: bool,
    ) -> Option<String> {
        use std::io::Read;
        use std::os::unix::process::CommandExt;
        let fail = |msg: String| {
            eprintln!("sshd: {kind}: {msg}");
            None
        };
        let program = argv.first()?;
        let Some(run_as) = run_as else {
            return fail(format!("no {kind}User specified, skipping"));
        };
        let info = match lookup_user(run_as) {
            Ok(i) => i,
            Err(e) => return fail(format!("{kind}User {run_as}: {e}")),
        };
        if strict_modes
            && let Err(e) = check_mode_strict(program, 0o022, kind, Some(nix::unistd::geteuid()))
        {
            return fail(e);
        }
        let switch = !already_matches(&info);
        if switch && !nix::unistd::geteuid().is_root() {
            return fail(format!("cannot run as {run_as} without root privileges"));
        }
        if debug {
            eprintln!("sshd: {kind}: running {argv:?} as {run_as}");
        }
        let mut cmd = std::process::Command::new(program);
        cmd.args(&argv[1..])
            .env_clear()
            .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
            .env("USER", &info.name)
            .env("LOGNAME", &info.name)
            .env("HOME", &info.home_str)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(if debug {
                std::process::Stdio::inherit()
            } else {
                std::process::Stdio::null()
            });
        if let Ok(lang) = std::env::var("LANG") {
            cmd.env("LANG", lang);
        }
        if switch {
            let (uid, gid, name_c) = (info.uid, info.gid, info.name_c.clone());
            // SAFETY: runs in the forked child before exec, calling only the
            // same set*id/initgroups sequence as the session drop below.
            unsafe {
                cmd.pre_exec(move || {
                    setgroups_clear().map_err(to_io)?;
                    nix::unistd::setgid(gid).map_err(to_io)?;
                    initgroups_libc(&name_c, gid).map_err(to_io)?;
                    nix::unistd::setuid(uid).map_err(to_io)?;
                    verify_post_setuid(uid, gid).map_err(to_io)?;
                    Ok(())
                });
            }
        }
        let mut child = match cmd.spawn() {
            Ok(c) => c,
            Err(e) => return fail(format!("{program}: {e}")),
        };
        let mut stdout = child.stdout.take()?;
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let mut buf = Vec::new();
            let r = (&mut stdout)
                .take(AUTH_COMMAND_OUTPUT_MAX as u64 + 1)
                .read_to_end(&mut buf);
            let _ = tx.send(r.map(|_| buf));
        });
        let out = match rx.recv_timeout(AUTH_COMMAND_TIMEOUT) {
            Ok(Ok(buf)) if buf.len() <= AUTH_COMMAND_OUTPUT_MAX => Some(buf),
            Ok(Ok(_)) => {
                eprintln!("sshd: {kind}: {program}: output too long");
                None
            }
            Ok(Err(e)) => {
                eprintln!("sshd: {kind}: {program}: read: {e}");
                None
            }
            Err(_) => {
                eprintln!("sshd: {kind}: {program}: timed out");
                None
            }
        };
        if out.is_none() {
            let _ = child.kill();
        }
        let status = child.wait();
        let out = out?;
        match status {
            Ok(st) if st.success() => Some(String::from_utf8_lossy(&out).into_owned()),
            Ok(st) => fail(format!("{program} returned {st}")),
            Err(e) => fail(format!("{program}: wait: {e}")),
        }
    }

    /// Parse `AuthorizedPrincipalsFile` / `AuthorizedPrincipalsCommand` lines:
    /// a principal name, optionally preceded by `authorized_keys` options
    /// (OpenSSH takes the last field as the name). Lines whose options do not
    /// parse are skipped.
    fn parse_principals(body: &str, source: &str) -> Vec<AuthorizedPrincipal> {
        let mut out = Vec::new();
        for (idx, line) in body.lines().enumerate() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let (opts, name) = match line.rfind([' ', '\t']) {
                None => (Default::default(), line),
                Some(i) => match puressh::key::AuthorizedKeyOptions::parse(line[..i].trim()) {
                    Ok(o) => (o, line[i + 1..].trim()),
                    Err(e) => {
                        eprintln!("sshd: skipping {source} line {}: {e}", idx + 1);
                        continue;
                    }
                },
            };
            out.push(AuthorizedPrincipal {
                name: name.to_string(),
                options: Arc::new(opts),
            });
        }
        out
    }

    /// `AuthorizedKeysCommand` / `AuthorizedPrincipalsCommand` and the users
    /// they run as; an empty command is none.
    #[derive(Clone, Debug, Default)]
    struct AuthCommands {
        keys: Vec<String>,
        keys_user: Option<String>,
        principals: Vec<String>,
        principals_user: Option<String>,
    }

    impl AuthCommands {
        fn from_options(opts: &puressh::config::ServerOptions) -> Self {
            AuthCommands {
                keys: opts.authorized_keys_command.clone().unwrap_or_default(),
                keys_user: opts.authorized_keys_command_user.clone(),
                principals: opts
                    .authorized_principals_command
                    .clone()
                    .unwrap_or_default(),
                principals_user: opts.authorized_principals_command_user.clone(),
            }
        }
    }

    /// One line of an `AuthorizedPrincipalsFile` (or command output).
    #[derive(Clone, Debug)]
    struct AuthorizedPrincipal {
        name: String,
        options: Arc<puressh::key::AuthorizedKeyOptions>,
    }

    /// Whether a `-u` / `AllowUsers` token names exactly one literal user (no
    /// glob metacharacters, no negation, no `@host` half).
    fn is_literal_user_token(token: &str) -> bool {
        !token.is_empty() && !token.contains(['*', '?', '!', '@'])
    }

    /// The effective `AllowUsers` token list for a connection: CLI `-u`
    /// tokens, then the config's (global + matched `Match` blocks). When
    /// nothing is configured the historical puressh default applies — only
    /// the daemon's own user (`$USER`) may log in — and if even that is
    /// unknown the list is a never-matching pattern, i.e. nobody. (An empty
    /// list would mean "no restriction" downstream, which must never happen
    /// by accident.)
    fn effective_allow_users(
        cli: &[String],
        cfg: &[String],
        default_user: Option<&str>,
    ) -> Vec<String> {
        let mut out: Vec<String> = cli.to_vec();
        out.extend(cfg.iter().cloned());
        // Nothing configured ⇒ the default user if one is given, else no
        // restriction at all (an empty list allows everyone).
        if out.is_empty()
            && let Some(u) = default_user
        {
            out.push(u.to_string());
        }
        out
    }

    /// Load and parse a binary KRL (`ssh-keygen -k`). A configured but
    /// unreadable / unparsable file is a hard error — failing closed beats
    /// silently running with no revocation.
    /// Every `RevokedKeys` file, combined.
    fn load_krls(paths: &[String], debug: bool) -> Result<puressh::krl::Krl, String> {
        let mut all = puressh::krl::Krl::new();
        for path in paths {
            all.merge(load_krl(path, debug)?);
        }
        Ok(all)
    }

    /// One `RevokedKeys` file: a binary KRL, or a list of public keys (a
    /// certificate's line revokes its key), as OpenSSH reads either.
    fn load_krl(path: &str, debug: bool) -> Result<puressh::krl::Krl, String> {
        let bytes = std::fs::read(path).map_err(|e| format!("RevokedKeys {path}: {e}"))?;
        let krl = if bytes.starts_with(b"SSHKRL\n\0") {
            puressh::krl::Krl::parse(&bytes)
                .map_err(|e| format!("RevokedKeys {path}: parse failed: {e}"))?
        } else {
            let text = String::from_utf8_lossy(&bytes);
            let mut krl = puressh::krl::Krl::new();
            for line in text.lines().map(str::trim) {
                if line.is_empty() || line.starts_with('#') {
                    continue;
                }
                if let Ok(k) = PublicKey::parse_authorized_keys_line(line) {
                    krl.revoke_key(&k.wire_blob());
                } else if let Ok(c) = puressh::cert::Certificate::parse_openssh_line(line) {
                    krl.revoke_key(c.embedded_pubkey_blob());
                } else {
                    return Err(format!("RevokedKeys {path}: unreadable key line"));
                }
            }
            krl
        };
        if debug {
            eprintln!(
                "sshd: loaded RevokedKeys from {path} ({} bytes, empty={})",
                bytes.len(),
                krl.is_empty()
            );
        }
        Ok(krl)
    }

    /// Load a file of CA public keys (one `authorized_keys`-style key per line),
    /// returning their wire blobs. Used for `TrustedUserCAKeys`.
    fn load_ca_keys_file(path: &str, strict_modes: bool) -> Result<Vec<Vec<u8>>, String> {
        if strict_modes {
            check_owner_mode(path, 0o022, "TrustedUserCAKeys file")?;
        }
        let body = std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?;
        let mut out = Vec::new();
        for (idx, line) in body.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            match PublicKey::parse_authorized_keys_line(trimmed) {
                Ok(k) => out.push(k.wire_blob()),
                Err(e) => eprintln!("sshd: skipping TrustedUserCAKeys line {}: {e}", idx + 1),
            }
        }
        Ok(out)
    }

    /// Load an `AuthorizedPrincipalsFile` (see [`parse_principals`]).
    fn load_principals_file(
        path: &str,
        strict_modes: bool,
        owner_uid: Option<nix::unistd::Uid>,
    ) -> Result<Vec<AuthorizedPrincipal>, String> {
        if strict_modes {
            check_mode_strict(path, 0o022, "AuthorizedPrincipalsFile", owner_uid)?;
        }
        let body = std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))?;
        Ok(parse_principals(&body, path))
    }

    /// Longest peer-controlled string echoed into a log line.
    const LOG_FIELD_MAX: usize = 128;

    /// Make a peer-controlled string safe to print in a log line: every
    /// control byte (`< 0x20` and `0x7f`) becomes `?` so a client cannot forge
    /// log lines / move the terminal cursor with embedded `\n`, `\r`, or
    /// escape sequences, and the result is truncated to [`LOG_FIELD_MAX`]
    /// characters (with a `…` marker) so a multi-kilobyte username cannot
    /// flood the log.
    fn sanitize_log(s: &str) -> String {
        let mut out = String::with_capacity(s.len().min(LOG_FIELD_MAX + 1));
        for (i, c) in s.chars().enumerate() {
            if i >= LOG_FIELD_MAX {
                out.push('…');
                break;
            }
            if c.is_control() {
                out.push('?');
            } else {
                out.push(c);
            }
        }
        out
    }

    /// Longest username accepted on the wire, in bytes. POSIX login names are
    /// far shorter (`LOGIN_NAME_MAX` is 256 on Linux including the NUL); a
    /// longer one cannot name a real account and is refused up front.
    const USERNAME_MAX: usize = 255;

    /// Whether a username received in a USERAUTH_REQUEST is acceptable at all:
    /// non-empty, at most [`USERNAME_MAX`] bytes, and free of control
    /// characters (which could never be a passwd name and would otherwise be
    /// echoed into log lines). Rejected names never reach access control, the
    /// passwd lookup, or the debug logs unsanitised.
    fn valid_username(user: &str) -> bool {
        !user.is_empty() && user.len() <= USERNAME_MAX && !user.chars().any(|c| c.is_control())
    }

    /// Decode an SSH `string` (4-byte BE length + bytes) into UTF-8. Used for
    /// the inner payload of certificate critical options (`force-command`,
    /// `source-address`), which are themselves length-prefixed strings.
    fn decode_ssh_string(data: &[u8]) -> Option<String> {
        if data.len() < 4 {
            return None;
        }
        let len = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
        if data.len() != 4 + len {
            return None;
        }
        std::str::from_utf8(&data[4..]).ok().map(|s| s.to_string())
    }

    /// Parse a peer descriptor (`"ip:port"`, `"[v6]:port"`, or a bare IP) into
    /// an `IpAddr`. Returns `None` if no IP can be recovered.
    fn parse_peer_ip(peer: &str) -> Option<std::net::IpAddr> {
        // Try the full socket-addr form first, then a bracketed v6, then bare.
        if let Ok(sa) = peer.parse::<std::net::SocketAddr>() {
            return Some(sa.ip());
        }
        if let Some(inner) = peer.strip_prefix('[').and_then(|s| s.split(']').next())
            && let Ok(ip) = inner.parse()
        {
            return Some(ip);
        }
        if let Some((host, _port)) = peer.rsplit_once(':')
            && let Ok(ip) = host.parse()
        {
            return Some(ip);
        }
        peer.parse().ok()
    }

    /// Does `ip` fall within `cidr` (e.g. `"10.0.0.0/8"`, `"192.168.1.5"`,
    /// `"2001:db8::/32"`)? A bare address with no `/` is treated as a `/32`
    /// (v4) or `/128` (v6) exact match. Address-family mismatches never match.
    fn cidr_matches(cidr: &str, ip: std::net::IpAddr) -> bool {
        use std::net::IpAddr;
        let (net_str, prefix_str) = match cidr.split_once('/') {
            Some((n, p)) => (n, Some(p)),
            None => (cidr, None),
        };
        let Ok(net) = net_str.parse::<IpAddr>() else {
            return false;
        };
        match (net, ip) {
            (IpAddr::V4(net), IpAddr::V4(ip)) => {
                let bits: u32 = match prefix_str {
                    Some(p) => match p.parse() {
                        Ok(b) if b <= 32 => b,
                        _ => return false,
                    },
                    None => 32,
                };
                let mask = if bits == 0 {
                    0
                } else {
                    u32::MAX << (32 - bits)
                };
                (u32::from(net) & mask) == (u32::from(ip) & mask)
            }
            (IpAddr::V6(net), IpAddr::V6(ip)) => {
                let bits: u32 = match prefix_str {
                    Some(p) => match p.parse() {
                        Ok(b) if b <= 128 => b,
                        _ => return false,
                    },
                    None => 128,
                };
                let net = u128::from(net);
                let ip = u128::from(ip);
                let mask = if bits == 0 {
                    0
                } else {
                    u128::MAX << (128 - bits)
                };
                (net & mask) == (ip & mask)
            }
            _ => false,
        }
    }

    /// A user→group-names resolver. Boxed so tests can inject a mock; the
    /// production value is [`lookup_user_groups`].
    type GroupLookup = Arc<dyn Fn(&str) -> Vec<String> + Send + Sync>;

    /// One `AllowUsers`/`DenyUsers` token. A bare token (`alice`, `!bob`,
    /// `dev-*`) constrains the username only; a `user@host` token additionally
    /// constrains the connection's peer address. OpenSSH negation (`!`) applies
    /// to the whole token and is stored separately from the globs so a `user`
    /// or `host` half can each carry the `*`/`?` grammar.
    #[derive(Clone)]
    struct UserHostPattern {
        /// True iff the token had a leading `!` (a match *excludes*).
        negated: bool,
        /// Username glob (the part before `@`, or the whole token).
        user: puressh::config::HostPattern,
        /// Host glob (the part after `@`), or `None` for a bare-user token.
        host: Option<puressh::config::HostPattern>,
    }

    impl UserHostPattern {
        /// Parse one whitespace-separated `AllowUsers`/`DenyUsers` token.
        fn parse(token: &str) -> Self {
            let (negated, body) = match token.strip_prefix('!') {
                Some(rest) => (true, rest),
                None => (false, token),
            };
            match body.split_once('@') {
                Some((user, host)) => UserHostPattern {
                    negated,
                    // The `!` already lives on the compound token; the inner
                    // globs are always positive patterns.
                    user: puressh::config::HostPattern::parse(user),
                    host: Some(puressh::config::HostPattern::parse(host)),
                },
                None => UserHostPattern {
                    negated,
                    user: puressh::config::HostPattern::parse(body),
                    host: None,
                },
            }
        }

        fn parse_all(tokens: &[String]) -> Vec<UserHostPattern> {
            tokens.iter().map(|t| UserHostPattern::parse(t)).collect()
        }

        /// True iff this token's positive globs match `(user, peer)`. The host
        /// half (if present) is matched against `peer`; a `user@host` token
        /// with no known peer address never matches.
        fn positive_match(&self, user: &str, peer: Option<&str>) -> bool {
            let user_ok = puressh::config::host_matches(core::slice::from_ref(&self.user), user);
            if !user_ok {
                return false;
            }
            match &self.host {
                None => true,
                Some(h) => match peer {
                    Some(p) => puressh::config::host_matches(core::slice::from_ref(h), p),
                    None => false,
                },
            }
        }
    }

    /// OpenSSH list semantics over [`UserHostPattern`]s: the list matches
    /// `(user, peer)` iff at least one positive token matches AND no negative
    /// token matches. An empty list never matches (the caller treats "empty
    /// AllowUsers" as "no restriction", handled separately).
    fn user_host_list_matches(
        patterns: &[UserHostPattern],
        user: &str,
        peer: Option<&str>,
    ) -> bool {
        let mut any_positive = false;
        let mut positive_hit = false;
        for p in patterns {
            if p.negated {
                if p.positive_match(user, peer) {
                    return false;
                }
            } else {
                any_positive = true;
                if p.positive_match(user, peer) {
                    positive_hit = true;
                }
            }
        }
        any_positive && positive_hit
    }

    struct LocalAuthenticator {
        /// No PAM: refuse locked or expired accounts ([`account_refusal`]).
        native_account_checks: bool,
        /// `AllowUsers` patterns (`user[@host]`, OpenSSH `Host`-style globs).
        /// Empty ⇒ the historical "current user only" default applied by the
        /// caller (it seeds this with the single resolved current user as a
        /// literal).
        allow_users: Vec<UserHostPattern>,
        /// `DenyUsers` patterns (`user[@host]`). Highest precedence.
        deny_users: Vec<UserHostPattern>,
        /// `AllowGroups` patterns (glob). Non-empty ⇒ the user must belong to
        /// a matching group.
        allow_groups: Vec<puressh::config::HostPattern>,
        /// `DenyGroups` patterns (glob).
        deny_groups: Vec<puressh::config::HostPattern>,
        /// `-A FILE`: the one global authorized_keys set, loaded at startup
        /// for the single allowed user. `None` ⇒ per-user files.
        global_authorized_keys: Option<Arc<AuthorizedKeys>>,
        /// `AuthorizedKeysFile` path templates in force for this connection
        /// (`%u`/`%h`/`%%` tokens; relative ⇒ under the user's home).
        authorized_keys_files: Vec<String>,
        /// The bound user's authorized keys, loaded lazily on the first
        /// publickey attempt (see [`Self::resolved_authorized_keys`]). `None`
        /// until then.
        authorized_keys: Option<AuthorizedKeys>,
        /// The options of the `authorized_keys` line that accepted the last
        /// publickey attempt, for [`Authenticator::key_restrictions`].
        accepted_options: Option<Arc<puressh::key::AuthorizedKeyOptions>>,
        /// CA public-key blobs from `TrustedUserCAKeys` (the file in force for
        /// this connection). A user cert signed by one of these is CA-trusted;
        /// principal authorization is checked separately. CAs from the user's
        /// own `authorized_keys` `cert-authority` lines live in
        /// `authorized_keys` and are trusted for that user only.
        trusted_user_ca_blobs: Vec<Vec<u8>>,
        /// Parsed `RevokedKeys` KRL in force for this connection (shared,
        /// read-only). `None` ⇒ no revocation list. A publickey / certificate
        /// the KRL covers is refused regardless of any other trust.
        revoked_keys: Option<Arc<puressh::krl::Krl>>,
        /// The parsed `sshd_config` plus the startup inputs needed to re-derive
        /// the access policy per connection from `Match` blocks
        /// (`on_user_resolved`). `None` ⇒ no config file / unit tests: the
        /// fields above stay at their global values.
        policy: Option<Arc<ConnPolicy>>,
        /// Set when the per-connection policy names a `TrustedUserCAKeys` /
        /// `RevokedKeys` file that was not preloaded at startup. Cannot happen
        /// for a config the daemon itself loaded; if it does, every attempt on
        /// this connection is refused rather than evaluated with a partial
        /// trust / revocation set.
        policy_broken: bool,
        /// `AuthorizedPrincipalsFile` path *template* (may contain `%u`/`%h`/
        /// `%%` tokens), or `None` when no file is configured. Resolved and
        /// loaded lazily per connection once the login user is known (the home
        /// directory needed for `%h` is only knowable then). See
        /// [`Self::resolved_principals`].
        authorized_principals_file: Option<String>,
        /// StrictModes ownership/permission check for the principals file.
        strict_modes: bool,
        /// Lazily-resolved `AuthorizedPrincipalsFile` contents for the bound
        /// user: `None` until first resolved; the inner `Option` is `None` when
        /// no file is configured (login user must itself be a cert principal,
        /// the OpenSSH default) or `Some(list)` of the file's lines.
        authorized_principals: Option<Option<Vec<AuthorizedPrincipal>>>,
        /// `AuthorizedKeysCommand` / `AuthorizedPrincipalsCommand` in force.
        auth_commands: AuthCommands,
        /// Their outputs on this connection, by expanded command line.
        command_cache: std::collections::BTreeMap<Vec<String>, Option<String>>,
        permit_root_login: puressh::config::PermitRootLogin,
        /// Shared PAM gate (per-connection, COW-isolated by `fork`). Used to
        /// verify passwords via `pam_check_password`. On a non-PAM build the
        /// stub always fails — but the binary also never advertises
        /// password/keyboard-interactive there, so this is belt-and-braces.
        pam: Arc<pam_gate::PamGate>,
        /// `PasswordAuthentication` enabled for this build/config (advertised).
        /// When false, a `password` attempt is rejected outright.
        password_enabled: bool,
        /// `KbdInteractiveAuthentication` enabled for this build/config.
        kbd_interactive_enabled: bool,
        /// Live multi-step keyboard-interactive PAM conversation, if one is in
        /// flight. The PAM `Context` runs on a worker thread; this holds the
        /// channel ends + join handle (see `pam_gate::KbdConversation`). `Some`
        /// between the first `keyboard-interactive` request and the terminal
        /// PAM verdict; reset to `None` on accept/reject so a fresh attempt
        /// starts a new conversation. Dropping it tears the worker down.
        kbd_conv: Option<pam_gate::KbdConversation>,
        /// True while the next keyboard-interactive answer would be the FIRST
        /// of a conversation, so the empty-password policy applies to it; reset
        /// once the opening answer is consumed, and re-armed when a new
        /// conversation starts.
        pending_first_prompt: bool,
        /// `PermitEmptyPasswords` — when false (the default), an empty password
        /// is rejected without ever consulting PAM.
        permit_empty_passwords: bool,
        /// `PubkeyAcceptedAlgorithms`: signature algorithms accepted for
        /// publickey auth. `None` ⇒ everything the auth layer verifies.
        pubkey_accepted: Option<Vec<String>>,
        /// `RequiredRSASize`: minimum RSA modulus bits for user keys.
        required_rsa_size: u32,
        /// Multi-factor chain set, resolved per-user from
        /// `AuthenticationMethods` (each inner Vec is one comma-chain of
        /// required methods). Empty ⇒ single-factor (any one advertised method
        /// suffices). Installed by `on_user_resolved`.
        chains: Vec<Vec<&'static str>>,
        /// Methods satisfied so far on this connection, in order. Used by
        /// `record_and_decide` to test chain completion. `none` never appears
        /// here.
        satisfied: Vec<&'static str>,
        /// The username bound to this connection once the first request is
        /// seen. A later attempt with a different username is rejected (OpenSSH
        /// terminates auth on a mid-userauth username change).
        bound_user: Option<String>,
        /// Per-connection memoization of `resolves_to_root(user)`. The
        /// passwd lookup happens at auth (login) time, not daemon startup,
        /// so it reflects the current database; the cache only avoids
        /// re-resolving the same username across this connection's repeated
        /// attempts (probe then signature, multiple offered keys).
        root_uid0_cache: std::collections::HashMap<String, bool>,
        /// Per-connection memoization of the user's group names (parallel to
        /// `root_uid0_cache`); resolved once, reused across attempts.
        group_cache: std::collections::HashMap<String, Vec<String>>,
        /// Group resolver (production: `lookup_user_groups`; tests: a mock).
        group_lookup: GroupLookup,
        /// Resolved peer address (IP/hostname) for this connection, used by the
        /// host half of `AllowUsers`/`DenyUsers` `user@host` patterns. `None`
        /// when the address is the unspecified placeholder (e.g. an in-process
        /// test transport); a `user@host` rule never matches a `None` peer.
        peer: Option<String>,
        debug: bool,
    }

    /// Why OpenSSH's non-PAM checks (`allowed_user`) refuse an account.
    #[derive(Debug, PartialEq, Eq)]
    #[cfg_attr(not(target_os = "linux"), allow(dead_code))] // checked on Linux only
    enum AccountRefusal {
        /// The shadow entry's account expiry date has passed.
        Expired,
        /// The password is locked (starts with `!`).
        Locked,
    }

    /// OpenSSH's account checks without PAM: an expired account (shadow
    /// `sp_expire`) or a locked password (`!` prefix, in the shadow entry
    /// when readable, else in the passwd entry).
    #[cfg(target_os = "linux")]
    fn account_refusal(user: &str) -> Option<AccountRefusal> {
        let name = std::ffi::CString::new(user).ok()?;
        let mut buf = vec![0 as libc::c_char; 16384];
        // SAFETY: getspnam_r fills `sp` with pointers into `buf`, which
        // outlives every use below; a null result means no (readable) entry.
        let shadow = unsafe {
            let mut sp: libc::spwd = std::mem::zeroed();
            let mut res: *mut libc::spwd = std::ptr::null_mut();
            libc::getspnam_r(
                name.as_ptr(),
                &mut sp,
                buf.as_mut_ptr(),
                buf.len(),
                &mut res,
            );
            (!res.is_null()).then(|| {
                let pwd = (!sp.sp_pwdp.is_null())
                    .then(|| std::ffi::CStr::from_ptr(sp.sp_pwdp).to_bytes().to_vec());
                (sp.sp_expire, pwd)
            })
        };
        if let Some((expire, _)) = &shadow {
            let today = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_secs() / 86400) as i64;
            #[allow(clippy::unnecessary_cast)] // `c_long` is `i32` on some targets
            if *expire != -1 && (*expire as i64) < today {
                return Some(AccountRefusal::Expired);
            }
        }
        let passwd = match shadow.and_then(|(_, p)| p) {
            Some(p) => p,
            None => {
                let mut pbuf = vec![0 as libc::c_char; 16384];
                // SAFETY: as above, for getpwnam_r and `pbuf`.
                unsafe {
                    let mut pw: libc::passwd = std::mem::zeroed();
                    let mut res: *mut libc::passwd = std::ptr::null_mut();
                    libc::getpwnam_r(
                        name.as_ptr(),
                        &mut pw,
                        pbuf.as_mut_ptr(),
                        pbuf.len(),
                        &mut res,
                    );
                    if res.is_null() || pw.pw_passwd.is_null() {
                        return None;
                    }
                    std::ffi::CStr::from_ptr(pw.pw_passwd).to_bytes().to_vec()
                }
            }
        };
        passwd.starts_with(b"!").then_some(AccountRefusal::Locked)
    }

    #[cfg(not(target_os = "linux"))]
    fn account_refusal(_user: &str) -> Option<AccountRefusal> {
        None
    }

    impl LocalAuthenticator {
        /// Apply the OpenSSH access precedence — DenyUsers → AllowUsers →
        /// DenyGroups → AllowGroups — returning `true` iff `user` is allowed.
        ///
        /// `AllowUsers`/`DenyUsers` `user@host` tokens additionally match the
        /// host half against this connection's resolved peer address.
        ///
        /// Group lookups are memoized per connection and resolved for *every*
        /// user uniformly (the caller never short-circuits on an
        /// already-failed user check), so the resolution cannot leak whether a
        /// user exists via timing.
        fn access_allowed(&mut self, user: &str) -> bool {
            let peer = self.peer.as_deref();
            // Resolve groups up front (uniform cost) so every branch below
            // sees the same work regardless of which check decides.
            let groups = match self.group_cache.get(user) {
                Some(g) => g.clone(),
                None => {
                    let g = (self.group_lookup)(user);
                    self.group_cache.insert(user.to_string(), g.clone());
                    g
                }
            };
            let in_group = |pats: &[puressh::config::HostPattern]| {
                groups
                    .iter()
                    .any(|g| puressh::config::host_matches(pats, g))
            };

            // 0. A knocked connection is bound to the knock's user.
            if knock_user().is_some_and(|k| k != user) {
                return false;
            }
            // OpenSSH says why an existing user is refused, once.
            let refuse = |why: &str| {
                sshd_log::with_conn(|c| {
                    if c.invalid_prefix().is_empty() && c.first("not allowed") {
                        let ip = peer.and_then(parse_peer_ip).map(sshd_log::addr_str);
                        sshd_log::info(&format!(
                            "User {user} from {} not allowed because {why}",
                            ip.unwrap_or_default()
                        ));
                    }
                });
                false
            };
            // Without PAM, OpenSSH's own account checks come first.
            if self.native_account_checks {
                match account_refusal(user) {
                    Some(AccountRefusal::Expired) => {
                        sshd_log::with_conn(|c| {
                            if c.first("account expired") {
                                sshd_log::info(&format!("Account {user} has expired"));
                            }
                        });
                        return false;
                    }
                    Some(AccountRefusal::Locked) => return refuse("account is locked"),
                    None => {}
                }
            }
            // 1. DenyUsers wins outright.
            if !self.deny_users.is_empty() && user_host_list_matches(&self.deny_users, user, peer) {
                return refuse("listed in DenyUsers");
            }
            // 2. AllowUsers: if set, the user must match one.
            if !self.allow_users.is_empty()
                && !user_host_list_matches(&self.allow_users, user, peer)
            {
                return refuse("not listed in AllowUsers");
            }
            // 3. DenyGroups: a matching group refuses.
            if !self.deny_groups.is_empty() && in_group(&self.deny_groups) {
                return refuse("a group is listed in DenyGroups");
            }
            // 4. AllowGroups: if set, the user must be in a matching group.
            if !self.allow_groups.is_empty() && !in_group(&self.allow_groups) {
                return refuse("none of user's groups are listed in AllowGroups");
            }
            true
        }

        /// `ROOT LOGIN REFUSED FROM …`, once, when PermitRootLogin refuses.
        fn log_root_refused(&self, denied: bool) {
            if denied {
                sshd_log::with_conn(|c| {
                    if c.first("root refused") {
                        sshd_log::info(&format!("ROOT LOGIN REFUSED FROM {}", c.peer()));
                    }
                });
            }
        }

        /// Memoized `resolves_to_root(user)` for this connection.
        fn is_root(&mut self, user: &str) -> bool {
            match self.root_uid0_cache.get(user) {
                Some(&r) => r,
                None => {
                    let r = resolves_to_root(user);
                    self.root_uid0_cache.insert(user.to_string(), r);
                    r
                }
            }
        }

        /// Trust decision for a verified user certificate: the CA must be in
        /// our trusted set, the login `user` must be an authorized principal,
        /// and any `source-address` critical option must admit the peer.
        ///
        /// The CA signature, cert type, validity and critical-option
        /// understanding were already enforced by the auth layer before this is
        /// reached; this is purely the trust + authorization gate.
        fn cert_trusted(
            &mut self,
            ci: &puressh::auth::CertInfo,
            user: &str,
            cert_blob: &[u8],
        ) -> bool {
            // 0. KRL revocation wins outright: a cert whose (CA, serial) or
            //    (CA, key-id) the KRL covers — or whose CA key itself is
            //    revoked as a plain key — is refused before any trust check.
            if let Some(krl) = self.revoked_keys.as_ref() {
                if krl.is_revoked_cert(&ci.ca_key_blob, ci.serial, &ci.key_id) {
                    if self.debug {
                        eprintln!(
                            "sshd: cert auth: certificate revoked by KRL (serial {}, key-id {:?})",
                            ci.serial, ci.key_id
                        );
                    }
                    return false;
                }
                if krl.is_revoked_key(&ci.ca_key_blob) {
                    if self.debug {
                        eprintln!("sshd: cert auth: signing CA key revoked by KRL");
                    }
                    return false;
                }
            }

            // 1 + 2. Is the signing CA trusted, and is the login user an
            //        authorized principal? Two independent routes, either of
            //        which suffices (OpenSSH tries authorized_keys first, then
            //        TrustedUserCAKeys):
            //
            //   a. a `cert-authority` line of the user's authorized_keys (or
            //      AuthorizedKeysCommand output) names this CA. With a
            //      `principals="..."` option the cert must carry a listed
            //      principal; without one, the login name, unless the cert
            //      lists no principals at all.
            //   b. the CA is in `TrustedUserCAKeys` and the cert lists
            //      principals: one of them must be in AuthorizedPrincipalsFile
            //      / AuthorizedPrincipalsCommand output when either is
            //      configured, otherwise the login name must be.
            //
            // Both routes are evaluated unconditionally so the cost does not
            // depend on which one decides.
            let peer = self.peer.clone();
            let debug = self.debug;
            let mut set = self.resolved_authorized_keys(user).clone();
            if let Some(more) = self.command_keys(user, cert_blob) {
                set.append(more);
            }
            let ca_line = set.cas.iter().enumerate().find(|(i, (blob, principals))| {
                *blob == ci.ca_key_blob
                    && set
                        .ca_options
                        .get(*i)
                        .is_none_or(|o| key_line_applies(o, peer.as_deref(), debug))
                    && match principals {
                        Some(list) => principals_match_option(list, &ci.valid_principals),
                        // A certificate without principals is refused, as
                        // OpenSSH refuses it.
                        None => ci.valid_principals.iter().any(|p| p == user),
                    }
            });
            let ca_opts = ca_line.map(|(i, _)| set.ca_options.get(i).cloned().unwrap_or_default());
            let global_trusted = self.trusted_user_ca_blobs.contains(&ci.ca_key_blob);
            let principal = self.cert_principal_line(ci, user, cert_blob);
            let global_ok = global_trusted && principal.is_some();
            if ca_opts.is_none() && !global_trusted {
                if self.debug {
                    eprintln!(
                        "sshd: cert auth: signing CA is not trusted for {user} (key-id {:?})",
                        ci.key_id
                    );
                }
                return false;
            }
            if ca_opts.is_none() && !global_ok {
                if self.debug {
                    eprintln!("sshd: cert auth: user {user} not an authorized principal");
                }
                return false;
            }
            // The options in force: the cert-authority line's, else those of
            // the principals line that matched.
            self.accepted_options = ca_opts.or_else(|| principal.flatten());

            // 3. source-address critical option (if present) must admit the peer.
            if let Some(data) = ci.critical_option("source-address") {
                let allowed_cidrs = decode_ssh_string(data);
                let peer_ip = self.peer.as_deref().and_then(parse_peer_ip);
                let ok = match (allowed_cidrs, peer_ip) {
                    (Some(list), Some(ip)) => list
                        .split(',')
                        .filter(|s| !s.is_empty())
                        .any(|cidr| cidr_matches(cidr.trim(), ip)),
                    // Option present but we can't determine the peer, or the
                    // option payload is malformed → fail closed.
                    _ => false,
                };
                if !ok {
                    if self.debug {
                        eprintln!("sshd: cert auth: peer not in source-address for {user}");
                    }
                    return false;
                }
            }
            true
        }

        /// The `TrustedUserCAKeys` principal rule. A certificate without
        /// principals is refused. With an AuthorizedPrincipalsFile or
        /// AuthorizedPrincipalsCommand, a line that applies to this
        /// connection must name one of the certificate's principals: returns
        /// `Some(Some(options))` of that line. Without either, the login name
        /// must be a principal: `Some(None)`.
        fn cert_principal_line(
            &mut self,
            ci: &puressh::auth::CertInfo,
            user: &str,
            cert_blob: &[u8],
        ) -> Option<Option<Arc<puressh::key::AuthorizedKeyOptions>>> {
            if ci.valid_principals.is_empty() {
                if self.debug {
                    eprintln!("sshd: cert auth: certificate lacks principal list");
                }
                return None;
            }
            let peer = self.peer.clone();
            let debug = self.debug;
            let mut lines = self.resolved_principals(user).clone();
            if let Some(more) = self.command_principals(user, ci, cert_blob) {
                lines.get_or_insert_with(Vec::new).extend(more);
            }
            match lines {
                None => ci
                    .valid_principals
                    .iter()
                    .any(|p| p == user)
                    .then_some(None),
                Some(lines) => lines
                    .into_iter()
                    .find(|l| {
                        ci.valid_principals.contains(&l.name)
                            && key_line_applies(&l.options, peer.as_deref(), debug)
                    })
                    .map(|l| Some(l.options)),
            }
        }

        /// `AuthorizedKeysCommand` output for `user` and the offered key or
        /// certificate `blob`, parsed; `None` when no command is configured
        /// or it fails. Runs are cached per expanded command line, so the
        /// probe and the signed attempt run it once.
        fn command_keys(&mut self, user: &str, blob: &[u8]) -> Option<AuthorizedKeys> {
            let template = self.auth_commands.keys.clone();
            if template.is_empty() {
                return None;
            }
            let info = lookup_user(user).ok()?;
            let (fp, b64, kind) = blob_tokens(blob);
            let mut tokens = connection_tokens(&info);
            tokens.extend([('f', fp), ('k', b64), ('t', kind)]);
            let mut argv = self.expand_command("AuthorizedKeysCommand", &template, &tokens)?;
            // No arguments: the user name, as OpenSSH has always passed it.
            if argv.len() == 1 {
                argv.push(info.name.clone());
            }
            let user_opt = self.auth_commands.keys_user.clone();
            let out = self.run_cached("AuthorizedKeysCommand", argv, user_opt)?;
            Some(parse_authorized_keys(&out, "AuthorizedKeysCommand output"))
        }

        /// `AuthorizedPrincipalsCommand` output for a certificate, parsed.
        fn command_principals(
            &mut self,
            user: &str,
            ci: &puressh::auth::CertInfo,
            cert_blob: &[u8],
        ) -> Option<Vec<AuthorizedPrincipal>> {
            let template = self.auth_commands.principals.clone();
            if template.is_empty() {
                return None;
            }
            let info = lookup_user(user).ok()?;
            let (fp, b64, kind) = blob_tokens(cert_blob);
            let (ca_fp, ca_b64, ca_kind) = blob_tokens(&ci.ca_key_blob);
            let mut tokens = connection_tokens(&info);
            tokens.extend([
                ('f', fp),
                ('k', b64),
                ('t', kind),
                ('F', ca_fp),
                ('K', ca_b64),
                ('T', ca_kind),
                ('i', ci.key_id.clone()),
                ('s', ci.serial.to_string()),
            ]);
            let argv = self.expand_command("AuthorizedPrincipalsCommand", &template, &tokens)?;
            let user_opt = self.auth_commands.principals_user.clone();
            let out = self.run_cached("AuthorizedPrincipalsCommand", argv, user_opt)?;
            Some(parse_principals(&out, "AuthorizedPrincipalsCommand output"))
        }

        /// Expand a command's arguments (not the program path).
        fn expand_command(
            &self,
            kind: &str,
            template: &[String],
            tokens: &[(char, String)],
        ) -> Option<Vec<String>> {
            let mut argv = vec![template[0].clone()];
            for arg in &template[1..] {
                match expand_command_arg(arg, tokens) {
                    Ok(a) => argv.push(a),
                    Err(e) => {
                        eprintln!("sshd: {kind}: {arg:?}: {e}");
                        return None;
                    }
                }
            }
            Some(argv)
        }

        /// [`run_auth_command`], once per connection for a given command line.
        fn run_cached(
            &mut self,
            kind: &str,
            argv: Vec<String>,
            run_as: Option<String>,
        ) -> Option<String> {
            if let Some(out) = self.command_cache.get(&argv) {
                return out.clone();
            }
            let out = run_auth_command(
                kind,
                &argv,
                run_as.as_deref(),
                self.strict_modes,
                self.debug,
            );
            self.command_cache.insert(argv, out.clone());
            out
        }

        /// The bound user's authorized keys, loaded on first use: the global
        /// `-A` set when one is configured, otherwise every
        /// `AuthorizedKeysFile` template expanded and read for `user`.
        fn resolved_authorized_keys(&mut self, user: &str) -> &AuthorizedKeys {
            if self.authorized_keys.is_none() {
                let set = match &self.global_authorized_keys {
                    Some(g) => (**g).clone(),
                    None => self.load_authorized_keys_for(user),
                };
                self.authorized_keys = Some(set);
            }
            // Safe: just populated above.
            self.authorized_keys.as_ref().unwrap()
        }

        /// Whether `blob` is authorized for `user` by a line that applies to
        /// this connection (`from=`, `expiry-time=`); that line's options are
        /// kept for [`Authenticator::key_restrictions`].
        fn key_authorized(&mut self, user: &str, blob: &[u8]) -> bool {
            let peer = self.peer.clone();
            let debug = self.debug;
            let find = |set: &AuthorizedKeys| {
                set.blobs
                    .iter()
                    .enumerate()
                    .find(|(i, b)| {
                        b.as_slice() == blob
                            && set
                                .options
                                .get(*i)
                                .is_none_or(|o| key_line_applies(o, peer.as_deref(), debug))
                    })
                    .map(|(i, _)| set.options.get(i).cloned().unwrap_or_default())
            };
            // The files first, then AuthorizedKeysCommand, as OpenSSH.
            let mut opts = find(self.resolved_authorized_keys(user));
            if opts.is_none()
                && let Some(set) = self.command_keys(user, blob)
            {
                opts = find(&set);
            }
            let ok = opts.is_some();
            self.accepted_options = opts;
            ok
        }

        /// [`load_user_authorized_keys`] with this connection's settings.
        fn load_authorized_keys_for(&self, user: &str) -> AuthorizedKeys {
            load_user_authorized_keys(
                user,
                &self.authorized_keys_files,
                self.strict_modes,
                self.debug,
            )
        }

        /// Re-derive the per-connection access policy from the `sshd_config`
        /// `Match` blocks that apply to `(user, groups, peer, local socket)`,
        /// replacing the global values this authenticator was built with.
        /// Called once, from `on_user_resolved`, before the first attempt is
        /// evaluated.
        fn apply_conn_policy(&mut self, pol: &ConnPolicy, user: &str) {
            let groups = match self.group_cache.get(user) {
                Some(g) => g.clone(),
                None => {
                    let g = (self.group_lookup)(user);
                    self.group_cache.insert(user.to_string(), g.clone());
                    g
                }
            };
            let opts = resolve_conn_options(&pol.config, user, &groups, self.peer.as_deref());

            self.allow_users = UserHostPattern::parse_all(&effective_allow_users(
                &pol.cli_allow_users,
                &opts.allow_users,
                pol.default_allow_user.as_deref(),
            ));
            self.deny_users = UserHostPattern::parse_all(&opts.deny_users);
            self.allow_groups = puressh::config::HostPattern::parse_all(&opts.allow_groups);
            self.deny_groups = puressh::config::HostPattern::parse_all(&opts.deny_groups);
            self.permit_root_login = pol
                .cli_permit_root_login
                .or(opts.permit_root_login)
                .unwrap_or(puressh::config::PermitRootLogin::ProhibitPassword);
            self.permit_empty_passwords = opts.permit_empty_passwords == Some(true);
            self.pubkey_accepted = opts.pubkey_accepted_algorithms.clone();
            self.required_rsa_size = opts.required_rsa_size.unwrap_or(DEFAULT_REQUIRED_RSA_SIZE);
            self.auth_commands = AuthCommands::from_options(&opts);
            self.command_cache.clear();
            self.authorized_principals_file = opts.authorized_principals_file;
            self.authorized_principals = None;
            if self.global_authorized_keys.is_none() {
                self.authorized_keys_files = opts
                    .authorized_keys_file
                    .unwrap_or_else(default_authorized_keys_files);
                self.authorized_keys = None;
            }
            self.trusted_user_ca_blobs = match &opts.trusted_user_ca_keys {
                None => Vec::new(),
                Some(path) => match pol.ca_files.get(path) {
                    Some(cas) => (**cas).clone(),
                    None => {
                        eprintln!("sshd: TrustedUserCAKeys {path}: not preloaded; refusing auth");
                        self.policy_broken = true;
                        Vec::new()
                    }
                },
            };
            self.revoked_keys = match &opts.revoked_keys {
                None => None,
                Some(paths) if paths.is_empty() => None,
                Some(path) => match pol.krls.get(path) {
                    Some(k) => Some(k.clone()),
                    None => {
                        eprintln!("sshd: RevokedKeys {path:?}: not preloaded; refusing auth");
                        self.policy_broken = true;
                        None
                    }
                },
            };
        }

        /// Resolve (and cache) the `AuthorizedPrincipalsFile` contents for the
        /// login `user`, expanding `%u`/`%h`/`%%` tokens in the configured path
        /// template against the user's passwd entry. Loaded at most once per
        /// connection.
        ///
        /// Returns a reference to the cached value: `None` ⇒ no file configured
        /// (the login user must itself be a cert principal — OpenSSH default);
        /// `Some(list)` ⇒ the principal names the file grants. A file that is
        /// configured but unreadable / fails StrictModes / has an unexpandable
        /// path resolves to `Some(vec![])` (no principals), which fails the
        /// authorization closed rather than silently widening it.
        fn resolved_principals(&mut self, user: &str) -> &Option<Vec<AuthorizedPrincipal>> {
            if self.authorized_principals.is_none() {
                let template = self
                    .authorized_principals_file
                    .clone()
                    .filter(|t| !t.eq_ignore_ascii_case("none"));
                let resolved = template.map(|t| self.load_principals_for(&t, user));
                self.authorized_principals = Some(resolved);
            }
            // Safe: just populated above.
            self.authorized_principals.as_ref().unwrap()
        }

        /// Expand a principals-file path template for `user` and load it,
        /// returning its lines (empty on any failure — fail closed).
        fn load_principals_for(&self, template: &str, user: &str) -> Vec<AuthorizedPrincipal> {
            let info = match lookup_user(user) {
                Ok(i) => i,
                Err(e) => {
                    if self.debug {
                        eprintln!(
                            "sshd: AuthorizedPrincipalsFile: user lookup failed for {user}: {e}"
                        );
                    }
                    return Vec::new();
                }
            };
            let path = match expand_pct_tokens(template, &info) {
                Ok(p) => p,
                Err(e) => {
                    if self.debug {
                        eprintln!("sshd: AuthorizedPrincipalsFile: bad path template: {e}");
                    }
                    return Vec::new();
                }
            };
            let path = if path.starts_with('/') {
                path
            } else {
                format!("{}/{path}", info.home_str.trim_end_matches('/'))
            };
            // A glob names every matching file, read in order, as in OpenSSH.
            let mut out = Vec::new();
            for file in puressh::config::glob_paths(&path) {
                let file = file.to_string_lossy();
                match load_principals_file(&file, self.strict_modes, Some(info.uid)) {
                    Ok(list) => out.extend(list),
                    Err(e) => {
                        if self.debug {
                            eprintln!("sshd: AuthorizedPrincipalsFile {file}: {e}");
                        }
                    }
                }
            }
            out
        }

        /// Bind / verify the connection username. Returns `false` if the client
        /// switched usernames mid-userauth (OpenSSH rejects this). The first
        /// call binds; subsequent calls must match.
        ///
        /// A syntactically invalid username (see [`valid_username`]) never
        /// binds and always returns `false`, so no later step logs or resolves
        /// it.
        fn check_user_binding(&mut self, user: &str) -> bool {
            if !valid_username(user) {
                if self.debug {
                    eprintln!(
                        "sshd: auth: refusing invalid username {:?}",
                        sanitize_log(user)
                    );
                }
                return false;
            }
            match &self.bound_user {
                None => {
                    self.bound_user = Some(user.to_string());
                    true
                }
                Some(bound) => bound == user,
            }
        }

        /// Decide whether an empty password may even be attempted, *before* any
        /// PAM call. Extracted as a pure, PAM-independent helper so the policy
        /// (empty password refused unless `PermitEmptyPasswords`) is unit-
        /// testable without a live PAM stack.
        ///
        /// `true` ⇒ the password is non-empty, or empty passwords are
        /// permitted, so the caller may proceed to verify it. `false` ⇒ reject
        /// without consulting the backend.
        fn empty_password_allowed(permit_empty: bool, password: &[u8]) -> bool {
            !password.is_empty() || permit_empty
        }

        /// Full password-verification path shared by the `password` and
        /// `keyboard-interactive` methods: access control + PermitRootLogin +
        /// empty-password policy + PAM.
        ///
        /// Timing uniformity: the PAM call (the dominant, shadow-hashing cost)
        /// runs for *every* attempt regardless of whether access control or the
        /// root gate would refuse the user — PAM returns USER_UNKNOWN/AUTH_ERR
        /// after a comparable delay for unknown users, so an attacker cannot
        /// distinguish "no such user / not allowed" from "wrong password" by
        /// wall-clock. The access/root verdicts only AND into the final result;
        /// the only short-circuit is the empty-password refusal, which is gated
        /// on the *client-supplied input* (an empty password), not on any
        /// per-user secret, so it leaks nothing about which users exist.
        /// Returns the chain-aware decision via `record_and_decide` on success,
        /// or `Reject`.
        fn verify_password(
            &mut self,
            user: &str,
            method: &'static str,
            password: purecrypto::zeroize::Zeroizing<Vec<u8>>,
        ) -> AuthDecision {
            // Mid-userauth username change ⇒ reject (don't leak which half
            // failed).
            if !self.check_user_binding(user) {
                if self.debug {
                    eprintln!("sshd: auth {method}: username changed mid-userauth, rejecting");
                }
                return AuthDecision::Reject;
            }

            // Empty-password refusal is input-dependent (not user-dependent), so
            // short-circuiting here introduces no user-enumeration oracle.
            if !Self::empty_password_allowed(self.permit_empty_passwords, &password) {
                if self.debug {
                    eprintln!("sshd: auth {method}: empty password refused for {user}");
                }
                return AuthDecision::Reject;
            }

            // Access control + root gate. Computed up front but applied *after*
            // the PAM call so the call always runs (uniform timing).
            let user_ok = self.access_allowed(user);
            let is_root = self.is_root(user);
            let root_denied = is_root && !self.permit_root_login.permits_password();
            self.log_root_refused(root_denied);

            let rhost = self.peer.clone();
            let pam_ok = self
                .pam
                .pam_check_password(user, password, rhost.as_deref())
                .is_ok();

            if pam_ok && user_ok && !root_denied {
                if self.debug {
                    eprintln!("sshd: auth {method}: accepted user {user}");
                }
                return self.record_and_decide(method);
            }
            if self.debug {
                if !pam_ok {
                    eprintln!("sshd: auth {method}: PAM rejected user {user}");
                } else if root_denied {
                    eprintln!(
                        "sshd: auth {method}: root login denied by PermitRootLogin for {user}"
                    );
                } else {
                    eprintln!("sshd: auth {method}: user {user} not in allowed set");
                }
            }
            AuthDecision::Reject
        }

        /// Pull the next step from the live keyboard-interactive PAM
        /// conversation and translate it into an [`AuthDecision`].
        ///
        /// - A `Prompt` becomes an `InteractiveRequest` carrying that single
        ///   prompt (and any instruction/info text PAM emitted before it). The
        ///   conversation stays open; the client's answer arrives in the next
        ///   `evaluate_interactive`.
        /// - A terminal `Done(ok)` ends the conversation: the worker is torn
        ///   down (by clearing `kbd_conv`). On `ok` the same access-control +
        ///   PermitRootLogin gates as the password path are ANDed in, and a
        ///   pass yields the chain-aware verdict via `record_and_decide`. Any
        ///   failure yields `Reject`.
        fn kbd_pump(&mut self, user: &str) -> AuthDecision {
            let step = match self.kbd_conv.as_mut() {
                Some(c) => c.next(),
                None => return AuthDecision::Reject,
            };
            match step {
                pam_gate::KbdStep::Prompt {
                    instruction,
                    prompt,
                    echo,
                } => AuthDecision::InteractiveRequest {
                    name: String::new(),
                    instruction,
                    prompts: vec![(prompt, echo)],
                },
                pam_gate::KbdStep::Done(ok) => {
                    // Conversation finished; drop the worker.
                    self.kbd_conv = None;
                    if !ok {
                        if self.debug {
                            eprintln!("sshd: auth keyboard-interactive: PAM rejected user {user}");
                        }
                        return AuthDecision::Reject;
                    }
                    // PAM accepted. AND in the access + root gates (the same
                    // ones the password path applies). Resolve both uniformly.
                    let user_ok = self.access_allowed(user);
                    let is_root = self.is_root(user);
                    let root_denied = is_root && !self.permit_root_login.permits_password();
                    self.log_root_refused(root_denied);
                    if user_ok && !root_denied {
                        if self.debug {
                            eprintln!("sshd: auth keyboard-interactive: accepted user {user}");
                        }
                        self.record_and_decide("keyboard-interactive")
                    } else {
                        if self.debug {
                            if root_denied {
                                eprintln!(
                                    "sshd: auth keyboard-interactive: root login denied by PermitRootLogin for {user}"
                                );
                            } else {
                                eprintln!(
                                    "sshd: auth keyboard-interactive: user {user} not in allowed set"
                                );
                            }
                        }
                        AuthDecision::Reject
                    }
                }
            }
        }

        /// Record a satisfied factor and decide whether authentication is
        /// complete given the per-user multi-factor chain set, enforcing
        /// **positional (listed) order** as OpenSSH does.
        ///
        /// - No chains configured ⇒ single-factor: any one method accepts.
        /// - The methods must be completed in the order the chain lists them: a
        ///   chain stays *alive* only while the ordered `satisfied` sequence is
        ///   a positional prefix of it. Completing a method that no alive chain
        ///   expects *next* is out-of-order and is rejected (the method is not
        ///   committed to `satisfied`).
        /// - When some alive chain is fully covered (its length equals the
        ///   satisfied length) ⇒ Accept.
        /// - Otherwise ⇒ PartialAccept whose `still_required` is the set of the
        ///   *next* methods (`chain[satisfied.len()]`) across every alive chain
        ///   — never the whole remaining set.
        ///
        /// `none` is never recorded and never appears in a parsed chain.
        fn record_and_decide(&mut self, method: &'static str) -> AuthDecision {
            // Single-factor: no chains ⇒ one success is enough.
            if self.chains.is_empty() {
                return AuthDecision::Accept;
            }

            if method == "none" {
                // `none` cannot advance a chain; re-offer the current step.
                return self.partial_or_reject_for_current();
            }

            // Tentatively extend the ordered satisfied sequence and require the
            // result to remain a positional prefix of at least one chain. If
            // not, the just-completed method was offered out of order (or isn't
            // part of any chain) ⇒ reject without committing it.
            let candidate_len = self.satisfied.len() + 1;
            let mut any_alive = false;
            for chain in &self.chains {
                if chain.len() >= candidate_len
                    && chain[..self.satisfied.len()] == self.satisfied[..]
                    && chain[self.satisfied.len()] == method
                {
                    any_alive = true;
                    break;
                }
            }
            if !any_alive {
                if self.debug {
                    eprintln!(
                        "sshd: auth: method {method} completed out of order for the configured \
                         AuthenticationMethods chain(s); rejecting"
                    );
                }
                return AuthDecision::Reject;
            }
            self.satisfied.push(method);

            self.partial_or_reject_for_current()
        }

        /// Given the current ordered `satisfied` prefix, decide Accept (some
        /// alive chain is fully covered) or PartialAccept with the next-needed
        /// methods across alive chains. A chain is *alive* iff `satisfied` is a
        /// positional prefix of it. Never returns Reject here (callers handle
        /// the out-of-order reject before committing).
        fn partial_or_reject_for_current(&self) -> AuthDecision {
            let is_alive = |chain: &[&'static str]| -> bool {
                chain.len() >= self.satisfied.len()
                    && chain[..self.satisfied.len()] == self.satisfied[..]
            };

            // Any alive chain fully covered ⇒ done.
            if self
                .chains
                .iter()
                .any(|c| is_alive(c) && c.len() == self.satisfied.len())
            {
                return AuthDecision::Accept;
            }

            // Offer only the *next* method of each alive chain (positional).
            let mut next: Vec<String> = Vec::new();
            for chain in &self.chains {
                if is_alive(chain) && chain.len() > self.satisfied.len() {
                    let s = chain[self.satisfied.len()].to_string();
                    if !next.contains(&s) {
                        next.push(s);
                    }
                }
            }
            AuthDecision::PartialAccept {
                still_required: next,
            }
        }

        /// Log an attempt's outcome as OpenSSH does: `Accepted …` (and the
        /// connection is authenticated), `Partial …`, `Failed …` — at INFO
        /// for an invalid user or a password, VERBOSE otherwise. A probe
        /// that a key is acceptable is not an outcome.
        fn log_decision(&mut self, note: &AttemptNote, decision: &AuthDecision) {
            let _ = self;
            sshd_log::with_conn(|c| {
                let peer = c.peer();
                let (user, key) = (&note.user, &note.key);
                match decision {
                    AuthDecision::Accept if !note.probe => {
                        sshd_log::info(&format!(
                            "Accepted {} for {user} from {peer} ssh2{key}",
                            note.method
                        ));
                    }
                    AuthDecision::PartialAccept { .. } if !note.probe => {
                        sshd_log::verbose(&format!(
                            "Partial {} for {user} from {peer} ssh2{key}",
                            note.method
                        ));
                    }
                    AuthDecision::Reject => {
                        let invalid = c.invalid_prefix();
                        let level = if sshd_log::failure_is_loud(c, note.method) {
                            sshd_log::Level::Info
                        } else {
                            sshd_log::Level::Verbose
                        };
                        if note.method != "none" {
                            c.failures += 1;
                        }
                        sshd_log::log(
                            level,
                            &format!(
                                "Failed {} for {invalid}{user} from {peer} ssh2{key}",
                                note.method
                            ),
                        );
                    }
                    _ => {}
                }
            });
            if matches!(decision, AuthDecision::Accept) && !note.probe {
                sshd_log::conn_authenticated();
            }
        }
    }

    /// What an auth attempt's log line names.
    struct AttemptNote {
        /// `none`, `password`, `publickey`, `keyboard-interactive/pam`.
        method: &'static str,
        user: String,
        /// A publickey query without a signature.
        probe: bool,
        /// `: ED25519 SHA256:…` for a key, empty otherwise.
        key: String,
    }

    impl AttemptNote {
        fn of(attempt: &AuthAttempt) -> Self {
            let (method, user, probe, key) = match attempt {
                AuthAttempt::None { user } => ("none", user, false, String::new()),
                AuthAttempt::Password { user, .. } => ("password", user, false, String::new()),
                AuthAttempt::KeyboardInteractive { user } => {
                    ("keyboard-interactive/pam", user, false, String::new())
                }
                AuthAttempt::PublicKey {
                    user,
                    public_blob,
                    probe_only,
                    cert,
                    ..
                } => (
                    "publickey",
                    user,
                    *probe_only,
                    key_description(public_blob, cert.as_ref()),
                ),
                _ => ("unknown", &String::new(), false, String::new()),
            };
            AttemptNote {
                method,
                user: user.clone(),
                probe,
                key,
            }
        }
    }

    /// A key as OpenSSH's auth log names it: `: ED25519 SHA256:…`, or for a
    /// certificate `: ED25519-CERT SHA256:… ID id (serial n) CA ED25519
    /// SHA256:…`.
    fn key_description(blob: &[u8], cert: Option<&puressh::auth::CertInfo>) -> String {
        fn label(kind: &str) -> &'static str {
            let plain = kind.split("-cert-v01@").next().unwrap_or(kind);
            match plain {
                "ssh-ed25519" => "ED25519",
                "ssh-rsa" | "rsa-sha2-256" | "rsa-sha2-512" => "RSA",
                k if k.starts_with("ecdsa-sha2-") => "ECDSA",
                k if k.starts_with("sk-ssh-ed25519") => "ED25519-SK",
                k if k.starts_with("sk-ecdsa") => "ECDSA-SK",
                k if k.starts_with("ssh-mldsa44-ed25519") => "MLDSA44-ED25519",
                _ => "UNKNOWN",
            }
        }
        match cert {
            None => {
                let (fp, _, kind) = blob_tokens(blob);
                format!(": {} {fp}", label(&kind))
            }
            Some(ci) => {
                let (fp, _, kind) = blob_tokens(&ci.embedded_pubkey_blob);
                let (ca_fp, _, ca_kind) = blob_tokens(&ci.ca_key_blob);
                format!(
                    ": {}-CERT {fp} ID {} (serial {}) CA {} {ca_fp}",
                    label(&kind),
                    ci.key_id,
                    ci.serial,
                    label(&ca_kind)
                )
            }
        }
    }

    impl Authenticator for LocalAuthenticator {
        fn continuable_methods(&self, offered: &[&'static str]) -> Vec<String> {
            if self.chains.is_empty() {
                return offered.iter().map(|m| (*m).into()).collect();
            }
            // The next method of each chain still consistent with what has
            // been satisfied, if the server offers it (OpenSSH's
            // authmethods_get with AuthenticationMethods).
            match self.partial_or_reject_for_current() {
                AuthDecision::PartialAccept { still_required } => still_required
                    .into_iter()
                    .filter(|m| offered.contains(&m.as_str()))
                    .collect(),
                _ => Vec::new(),
            }
        }

        fn key_restrictions(
            &mut self,
            _user: &str,
            _public_blob: &[u8],
        ) -> Option<puressh::auth::AuthCertCaps> {
            self.accepted_options
                .take()
                .filter(|o| !o.is_unrestricted())
                .map(|o| puressh::auth::AuthCertCaps::from_key_options(&o))
        }

        fn evaluate(&mut self, attempt: AuthAttempt) -> AuthDecision {
            let note = AttemptNote::of(&attempt);
            if !matches!(attempt, AuthAttempt::None { .. }) {
                AUTH_ATTEMPTED.store(true, Ordering::Relaxed);
            }
            let decision = (|| {
                if self.policy_broken {
                    return AuthDecision::Reject;
                }
                match attempt {
                    AuthAttempt::None { user } => {
                        if self.debug {
                            eprintln!("sshd: auth none rejected for user {}", sanitize_log(&user));
                        }
                        AuthDecision::Reject
                    }
                    AuthAttempt::PublicKey {
                        user,
                        algorithm,
                        public_blob,
                        probe_only,
                        verified,
                        cert,
                    } => {
                        // An invalid username, or a username switched
                        // mid-userauth, is refused before anything else. Both
                        // verdicts depend only on the client's own input (never on
                        // whether an account exists), so the early return leaks
                        // nothing. Every `{user}` logged below has passed this
                        // check and is therefore free of control characters.
                        if !self.check_user_binding(&user) {
                            if self.debug {
                                eprintln!(
                                    "sshd: auth publickey: username rejected or changed mid-userauth"
                                );
                            }
                            return AuthDecision::Reject;
                        }
                        // Always run *both* remaining checks unconditionally so an
                        // attacker can't distinguish "unknown user" from
                        // "known user / wrong key" via wall-clock timing.
                        // The access check (DenyUsers/AllowUsers/DenyGroups/
                        // AllowGroups, with a memoized group lookup) and the
                        // scan over the user's authorized keys (loaded once per
                        // connection) both run for every attempt so the paths
                        // stay uniform.
                        let user_ok = self.access_allowed(&user);
                        // For a certificate, "blob_ok" becomes: the CA is trusted,
                        // the login user is an authorized principal, and any
                        // source-address critical option admits this peer. (The
                        // auth layer already verified the CA signature, the cert
                        // type/validity, and that all critical options are
                        // understood, before producing a `verified` cert attempt.)
                        // KRL revocation applies uniformly to plain keys and to a
                        // certificate's full wire blob (OpenSSH's explicit-key /
                        // fingerprint sections can name a cert blob directly). For
                        // a certificate the key *embedded* in it is checked as
                        // well: revoking a plain key must also refuse every
                        // certificate wrapping that key (OpenSSH checks the
                        // embedded key, not just the cert). A revoked blob forces
                        // `blob_ok` false regardless of the authorized-keys /
                        // cert-trust verdict.
                        let blob_revoked = self
                            .revoked_keys
                            .as_ref()
                            .as_ref()
                            .map(|krl| {
                                krl.is_revoked_key(&public_blob)
                                    || cert.as_ref().is_some_and(|ci| {
                                        krl.is_revoked_key(&ci.embedded_pubkey_blob)
                                    })
                            })
                            .unwrap_or(false);
                        if blob_revoked && self.debug {
                            eprintln!(
                                "sshd: auth publickey: key/cert blob revoked by KRL for {user}"
                            );
                        }
                        // PubkeyAcceptedAlgorithms / RequiredRSASize: a policy on
                        // the key itself, folded into `blob_ok` (no early return,
                        // so timing stays uniform).
                        let alg_ok = self
                            .pubkey_accepted
                            .as_ref()
                            .is_none_or(|l| l.iter().any(|a| a == &algorithm));
                        let key_blob = cert.as_ref().map_or(public_blob.as_slice(), |ci| {
                            ci.embedded_pubkey_blob.as_slice()
                        });
                        let size_ok = rsa_modulus_bits(key_blob)
                            .is_none_or(|bits| bits >= self.required_rsa_size as usize);
                        if self.debug && !(alg_ok && size_ok) {
                            eprintln!(
                                "sshd: auth publickey: {} for {user}",
                                if alg_ok {
                                    "RSA key below RequiredRSASize"
                                } else {
                                    "algorithm not in PubkeyAcceptedAlgorithms"
                                }
                            );
                        }
                        let blob_ok = !blob_revoked
                            && alg_ok
                            && size_ok
                            && match &cert {
                                Some(ci) => self.cert_trusted(ci, &user, &public_blob),
                                None => self.key_authorized(&user, &public_blob),
                            };
                        // PermitRootLogin gate: if the requested user resolves to
                        // the root account (uid 0) and policy forbids it, deny
                        // regardless of key match. The username is resolved at
                        // login time (memoized per connection) rather than from a
                        // daemon-startup snapshot, so a uid-0 alias added after
                        // startup is still caught. Resolved for every requested
                        // user (not only allowed ones) so the lookup doesn't add a
                        // user-enumeration timing signal.
                        let is_root = self.is_root(&user);
                        let root_denied = is_root && !self.permit_root_login.permits_publickey();
                        self.log_root_refused(root_denied);
                        let allow = user_ok && blob_ok && !root_denied;

                        // probe_only attempts (no signature) only need
                        // user+blob to be acceptable so the client knows it
                        // can move on to the signed step.
                        if probe_only {
                            return if allow {
                                AuthDecision::Accept
                            } else {
                                if self.debug {
                                    if root_denied {
                                        eprintln!(
                                            "sshd: auth publickey probe: root login denied by PermitRootLogin for {user}"
                                        );
                                    } else if !user_ok {
                                        eprintln!(
                                            "sshd: auth publickey probe: user {user} not in allowed set"
                                        );
                                    } else {
                                        eprintln!(
                                            "sshd: auth publickey probe: key not in authorized_keys for {user}"
                                        );
                                    }
                                }
                                AuthDecision::Reject
                            };
                        }

                        if !(allow && verified) {
                            if self.debug {
                                if root_denied {
                                    eprintln!(
                                        "sshd: auth publickey: root login denied by PermitRootLogin for {user}"
                                    );
                                } else if !user_ok {
                                    eprintln!(
                                        "sshd: auth publickey: user {user} not in allowed set"
                                    );
                                } else if !blob_ok {
                                    eprintln!(
                                        "sshd: auth publickey: key not in authorized_keys for {user}"
                                    );
                                } else {
                                    eprintln!(
                                        "sshd: auth publickey: signature missing or unverified for {user}"
                                    );
                                }
                            }
                            return AuthDecision::Reject;
                        }
                        if self.debug {
                            eprintln!("sshd: auth publickey: verified user {user}");
                        }
                        // A verified user certificate's `force-command` critical
                        // option (and its default-deny extensions) are captured by
                        // the auth layer into `AuthCertCaps`, folded into the
                        // per-connection `EffectivePolicy`, and enforced by the
                        // server connection-phase dispatcher uniformly with the
                        // config `ForceCommand` / forwarding gates. Nothing to
                        // record here.
                        //
                        // A verified signature satisfies the `publickey` factor. In
                        // single-factor mode this Accepts; under a multi-factor
                        // chain it may PartialAccept and ask for the next factor.
                        self.record_and_decide("publickey")
                    }
                    AuthAttempt::Password { user, password } => {
                        if !self.password_enabled {
                            if self.debug {
                                eprintln!(
                                    "sshd: auth password rejected (disabled) for user {user}"
                                );
                            }
                            return AuthDecision::Reject;
                        }
                        // Copy the secret bytes into a zeroize-on-drop buffer; the
                        // source `SecretString` is itself zeroizing and drops at the
                        // end of this arm.
                        let pw = purecrypto::zeroize::Zeroizing::new(password.as_bytes().to_vec());
                        self.verify_password(&user, "password", pw)
                    }
                    AuthAttempt::KeyboardInteractive { user } => {
                        if !self.kbd_interactive_enabled {
                            if self.debug {
                                eprintln!(
                                    "sshd: auth keyboard-interactive rejected (disabled) for user {user}"
                                );
                            }
                            return AuthDecision::Reject;
                        }
                        // Bind the username now (so a later switch is caught).
                        if !self.check_user_binding(&user) {
                            if self.debug {
                                eprintln!(
                                    "sshd: auth keyboard-interactive: username changed mid-userauth"
                                );
                            }
                            return AuthDecision::Reject;
                        }
                        // Start a fresh PAM conversation on a worker thread. Any
                        // previous (abandoned) conversation is dropped here, tearing
                        // down its worker. The first `next()` blocks until PAM
                        // either asks a prompt (→ InteractiveRequest) or finishes
                        // immediately (e.g. pam_permit with no prompts → decide).
                        let rhost = self.peer.clone();
                        let conv = self.pam.start_kbd_interactive(&user, rhost.as_deref());
                        self.kbd_conv = Some(conv);
                        self.pending_first_prompt = true;
                        let user = user.clone();
                        self.kbd_pump(&user)
                    }
                    // An auth method this binary predates: never accept it.
                    _ => AuthDecision::Reject,
                }
            })();
            self.log_decision(&note, &decision);
            decision
        }

        fn evaluate_interactive(&mut self, user: &str, responses: Vec<String>) -> AuthDecision {
            let note = AttemptNote {
                method: "keyboard-interactive/pam",
                user: user.to_string(),
                probe: false,
                key: String::new(),
            };
            let decision = (|| {
                if !self.kbd_interactive_enabled || self.policy_broken {
                    return AuthDecision::Reject;
                }
                // Username must not change mid-conversation.
                if !self.check_user_binding(user) {
                    if self.debug {
                        eprintln!("sshd: auth keyboard-interactive: username changed mid-userauth");
                    }
                    self.kbd_conv = None;
                    return AuthDecision::Reject;
                }
                // Feed the answer (we issue one prompt per round, so exactly one
                // response is expected) into the running conversation, then pump
                // for the next step. The response strings come from
                // `UserauthInfoResponse`, whose Drop zeroizes its buffer; we copy
                // the answer into a zeroizing buffer first.
                let answer = responses
                    .first()
                    .map(|s| purecrypto::zeroize::Zeroizing::new(s.as_bytes().to_vec()))
                    .unwrap_or_default();

                // Empty-password policy: refuse an empty answer to the first prompt
                // unless PermitEmptyPasswords, mirroring the password path. This is
                // input-dependent (not user-dependent), so it leaks no user-
                // existence oracle. `pending_first_prompt` tracks whether this is
                // the opening answer.
                if self.pending_first_prompt && answer.is_empty() && !self.permit_empty_passwords {
                    if self.debug {
                        eprintln!(
                            "sshd: auth keyboard-interactive: empty password refused for {user}"
                        );
                    }
                    self.kbd_conv = None;
                    return AuthDecision::Reject;
                }
                self.pending_first_prompt = false;

                let conv = match self.kbd_conv.as_mut() {
                    Some(c) => c,
                    None => return AuthDecision::Reject,
                };
                if !conv.answer(answer) {
                    // Worker already gone (e.g. PAM aborted) ⇒ reject.
                    self.kbd_conv = None;
                    return AuthDecision::Reject;
                }
                let user = user.to_string();
                self.kbd_pump(&user)
            })();
            self.log_decision(&note, &decision);
            decision
        }

        fn on_user_resolved(&mut self, user: &str, methods: &[String]) {
            // Bind the username on first sight (the publickey/password arms also
            // bind, but this fires first via the server's re-resolve hook).
            let bound = self.check_user_binding(user);
            if bound {
                let valid = lookup_user(user).is_ok();
                if !valid {
                    INVALID_USER.store(true, Ordering::Relaxed);
                }
                sshd_log::conn_user(user, valid);
            }
            // Match-block access policy for this (user, peer, local socket):
            // AllowUsers/DenyUsers/AllowGroups/DenyGroups, PermitRootLogin,
            // PermitEmptyPasswords, AuthorizedKeysFile,
            // AuthorizedPrincipalsFile, TrustedUserCAKeys, RevokedKeys.
            if bound && let Some(pol) = self.policy.clone() {
                self.apply_conn_policy(&pol, user);
            }
            self.chains = parse_auth_method_chains(methods);
            if self.debug && bound && !self.chains.is_empty() {
                eprintln!(
                    "sshd: auth: multi-factor chains for {user}: {:?}",
                    self.chains
                );
            }
        }
    }

    /// Map a resolved `AuthenticationMethods` value (space-separated
    /// alternatives, each a comma-chain) into the internal chain set. Each
    /// factor is interned to a `&'static str` the rest of the machine compares
    /// by identity; `any` collapses to "no constraint" (an empty chain set, i.e.
    /// single-factor), and unknown tokens are dropped (the config parser already
    /// rejected genuinely-unknown ones, so this is defensive).
    fn parse_auth_method_chains(methods: &[String]) -> Vec<Vec<&'static str>> {
        let mut chains: Vec<Vec<&'static str>> = Vec::new();
        for alt in methods {
            if alt == "any" {
                // `any` means single-factor — clear any accumulated constraint
                // and stop (an empty chain set is the single-factor signal).
                return Vec::new();
            }
            let mut chain: Vec<&'static str> = Vec::new();
            for factor in alt.split(',').filter(|s| !s.is_empty()) {
                match factor {
                    "publickey" => chain.push("publickey"),
                    "password" => chain.push("password"),
                    "keyboard-interactive" => chain.push("keyboard-interactive"),
                    "none" => {} // never counts toward a chain
                    _ => {}      // unknown: defensively ignore
                }
            }
            if !chain.is_empty() {
                chains.push(chain);
            }
        }
        chains
    }

    /// Whether any of `list` (OpenSSH pattern-list entries, globs allowed)
    /// matches one of the certificate's principals. An empty certificate
    /// principal list never matches — a `principals=` option demands a named
    /// principal.
    fn principals_match_option(list: &[String], cert_principals: &[String]) -> bool {
        let pats = puressh::config::HostPattern::parse_all(list);
        cert_principals
            .iter()
            .any(|p| puressh::config::host_matches(&pats, p))
    }

    /// Startup inputs the authenticator (and the session-open hook) need to
    /// re-derive the access policy per connection from `Match` blocks.
    struct ConnPolicy {
        /// The whole parsed `sshd_config` (global + `Match` blocks).
        config: Arc<puressh::config::SshServerConfig>,
        /// CLI `-u` tokens: always in force, ahead of any config `AllowUsers`.
        cli_allow_users: Vec<String>,
        /// The daemon's own user, the only login allowed when no `AllowUsers`
        /// / `-u` applies. `None` if `$USER` is unknown (⇒ nobody).
        default_allow_user: Option<String>,
        /// `--permit-root-login`, which wins over every config block.
        cli_permit_root_login: Option<puressh::config::PermitRootLogin>,
        /// Every `TrustedUserCAKeys` file named anywhere in the config, loaded
        /// at startup, keyed by path.
        ca_files: HashMap<String, Arc<Vec<Vec<u8>>>>,
        /// Every `RevokedKeys` KRL named anywhere in the config, parsed at
        /// startup, keyed by path.
        krls: HashMap<Vec<String>, Arc<puressh::krl::Krl>>,
    }

    /// Per-connection socket addresses `(peer, local)`, recorded by the forked
    /// child before it enters the session loop. Fork's copy-on-write isolates
    /// the value per connection; the daemon parent never sets it. Read by the
    /// `Match LocalAddress` / `Match LocalPort` context and the session-open
    /// hook's peer lookup.
    static CONN_ADDRS: Mutex<Option<(std::net::SocketAddr, Option<std::net::SocketAddr>)>> =
        Mutex::new(None);

    /// Login name of the knock (`docs/knock.md`) that opened this
    /// connection's rendezvous, recorded by the forked child; `None` for a
    /// connection on the regular listener. A knocked connection may only log
    /// in as that user.
    static KNOCK_USER: Mutex<Option<String>> = Mutex::new(None);

    fn knock_user() -> Option<String> {
        KNOCK_USER.lock().ok().and_then(|g| g.clone())
    }

    /// `sshd -i`: the connection is stdin / stdout, not a socket.
    static INETD: AtomicBool = AtomicBool::new(false);

    /// `sshd -i`: serve one connection whose client is on stdin / stdout.
    /// A TCP socket there (inetd, systemd `Accept=yes`) is served as an
    /// accepted connection. Anything else (a pipe, as from a `ProxyCommand`)
    /// is bridged to a loopback connection, served as one from an unknown
    /// peer: like OpenSSH's, it matches no `from=` or `Match Address`.
    fn serve_inetd(cfg: Arc<puressh::server::Config>) -> Result<i32, String> {
        use std::io::{Read, Write};
        use std::os::fd::{FromRawFd, IntoRawFd};
        let io = |e: std::io::Error| format!("inetd: {e}");
        // SAFETY: fd 0 is open for the process's lifetime; the stream is
        // released again (not closed) unless it is used as the connection.
        let stdin_sock = unsafe { std::net::TcpStream::from_raw_fd(0) };
        if let Ok(peer) = stdin_sock.peer_addr() {
            if let Ok(mut g) = CONN_ADDRS.lock() {
                *g = Some((peer, stdin_sock.local_addr().ok()));
            }
            let result = handle_session_with_peer(stdin_sock, peer, cfg);
            return Ok(if result.is_ok() { 0 } else { 255 });
        }
        let _ = stdin_sock.into_raw_fd();
        INETD.store(true, Ordering::Relaxed);
        let l = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(io)?;
        let outer = std::net::TcpStream::connect(l.local_addr().map_err(io)?).map_err(io)?;
        let (inner, _) = l.accept().map_err(io)?;
        drop(l);
        // The bridge relays packets as they come: no Nagle delay.
        let _ = outer.set_nodelay(true);
        let peer = std::net::SocketAddr::from(([0, 0, 0, 0], 65535));
        let mut to_session = outer.try_clone().map_err(io)?;
        std::thread::spawn(move || {
            let mut stdin = std::io::stdin().lock();
            let mut buf = [0u8; 32 * 1024];
            loop {
                match stdin.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        if to_session.write_all(&buf[..n]).is_err() {
                            break;
                        }
                    }
                }
            }
            let _ = to_session.shutdown(std::net::Shutdown::Write);
        });
        let mut from_session = outer;
        let out = std::thread::spawn(move || {
            let mut stdout = std::io::stdout().lock();
            let mut buf = [0u8; 32 * 1024];
            loop {
                match from_session.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        if stdout
                            .write_all(&buf[..n])
                            .and_then(|()| stdout.flush())
                            .is_err()
                        {
                            break;
                        }
                    }
                }
            }
        });
        if let Ok(mut g) = CONN_ADDRS.lock() {
            *g = Some((peer, None));
        }
        let result = handle_session_with_addrs(inner, peer, None, cfg);
        let _ = out.join();
        Ok(if result.is_ok() { 0 } else { 255 })
    }

    fn conn_addrs() -> Option<(std::net::SocketAddr, Option<std::net::SocketAddr>)> {
        CONN_ADDRS.lock().ok().and_then(|g| *g)
    }

    /// The connection's peer IP in the textual form `Match Address` uses, or
    /// `None` when unknown / unspecified (then `Match Address` never matches).
    fn conn_peer_ip() -> Option<String> {
        conn_addrs()
            .map(|(peer, _)| peer.ip())
            .filter(|ip| !ip.is_unspecified())
            .map(|ip| ip.to_string())
    }

    /// Resolve the `sshd_config` policy for a connection once the login user
    /// is known: user, groups, peer address, and this child's local socket
    /// (for `Match LocalAddress` / `LocalPort`).
    fn resolve_conn_options(
        config: &puressh::config::SshServerConfig,
        user: &str,
        groups: &[String],
        peer_ip: Option<&str>,
    ) -> puressh::config::ServerOptions {
        let local = conn_addrs().and_then(|(_, local)| local);
        let local_ip = local.map(|a| a.ip().to_string());
        let mut ctx = puressh::config::MatchContext::default();
        ctx.user = Some(user);
        ctx.groups = Some(groups);
        ctx.address = peer_ip;
        // `Match host`: the client's address (OpenSSH's `UseDNS no`).
        ctx.host = peer_ip.unwrap_or("UNKNOWN");
        ctx.invalid_user = Some(lookup_user(user).is_err());
        ctx.local_address = local_ip.as_deref();
        ctx.local_port = local.map(|a| a.port());
        config.resolve(&ctx, puressh::config::ExecPolicy::Deny)
    }

    /// The `PermitRootLogin` in force for `user` on this connection: CLI flag
    /// > matched `Match` blocks > global > built-in `prohibit-password`.
    fn conn_permit_root_login(pol: &ConnPolicy, user: &str) -> puressh::config::PermitRootLogin {
        let groups = lookup_user_groups(user);
        let peer = conn_peer_ip();
        let opts = resolve_conn_options(&pol.config, user, &groups, peer.as_deref());
        pol.cli_permit_root_login
            .or(opts.permit_root_login)
            .unwrap_or(puressh::config::PermitRootLogin::ProhibitPassword)
    }

    #[derive(Clone)]
    struct LocalAuthFactory {
        /// No PAM: OpenSSH's own account checks apply (see
        /// [`account_refusal`]).
        native_account_checks: bool,
        allow_users: Arc<Vec<UserHostPattern>>,
        deny_users: Arc<Vec<UserHostPattern>>,
        allow_groups: Arc<Vec<puressh::config::HostPattern>>,
        deny_groups: Arc<Vec<puressh::config::HostPattern>>,
        /// `-A FILE`: the one global authorized_keys set. `None` ⇒ per-user.
        global_authorized_keys: Option<Arc<AuthorizedKeys>>,
        /// Global `AuthorizedKeysFile` templates (a `Match` block may replace
        /// them per connection).
        authorized_keys_files: Vec<String>,
        /// Trusted user-CA blobs from the global `TrustedUserCAKeys`.
        trusted_user_ca_blobs: Arc<Vec<Vec<u8>>>,
        /// Parsed global `RevokedKeys` KRL, shared read-only across connections.
        revoked_keys: Option<Arc<puressh::krl::Krl>>,
        /// Match-block policy inputs (see [`ConnPolicy`]).
        policy: Option<Arc<ConnPolicy>>,
        /// `AuthorizedPrincipalsFile` path *template* (may contain `%u`/`%h`/
        /// `%%`), shared across connections. `None` ⇒ no file configured. Each
        /// connection expands + loads it lazily for its own login user.
        authorized_principals_file: Option<String>,
        /// StrictModes for the principals file (and other strict checks).
        strict_modes: bool,
        permit_root_login: puressh::config::PermitRootLogin,
        group_lookup: GroupLookup,
        /// Shared PAM gate for password verification (see `LocalAuthenticator`).
        pam: Arc<pam_gate::PamGate>,
        password_enabled: bool,
        kbd_interactive_enabled: bool,
        permit_empty_passwords: bool,
        debug: bool,
    }

    impl LocalAuthFactory {
        fn build_inner(&self, peer: Option<&str>) -> Box<dyn Authenticator> {
            Box::new(LocalAuthenticator {
                native_account_checks: self.native_account_checks,
                allow_users: (*self.allow_users).clone(),
                deny_users: (*self.deny_users).clone(),
                allow_groups: (*self.allow_groups).clone(),
                deny_groups: (*self.deny_groups).clone(),
                global_authorized_keys: self.global_authorized_keys.clone(),
                authorized_keys_files: self.authorized_keys_files.clone(),
                authorized_keys: None,
                accepted_options: None,
                trusted_user_ca_blobs: (*self.trusted_user_ca_blobs).clone(),
                revoked_keys: self.revoked_keys.clone(),
                policy: self.policy.clone(),
                policy_broken: false,
                authorized_principals_file: self.authorized_principals_file.clone(),
                strict_modes: self.strict_modes,
                authorized_principals: None,
                auth_commands: AuthCommands::default(),
                command_cache: Default::default(),
                permit_root_login: self.permit_root_login,
                pam: self.pam.clone(),
                password_enabled: self.password_enabled,
                kbd_interactive_enabled: self.kbd_interactive_enabled,
                kbd_conv: None,
                pending_first_prompt: true,
                permit_empty_passwords: self.permit_empty_passwords,
                pubkey_accepted: None,
                required_rsa_size: DEFAULT_REQUIRED_RSA_SIZE,
                chains: Vec::new(),
                satisfied: Vec::new(),
                bound_user: None,
                root_uid0_cache: std::collections::HashMap::new(),
                group_cache: std::collections::HashMap::new(),
                group_lookup: self.group_lookup.clone(),
                peer: peer.map(str::to_string),
                debug: self.debug,
            })
        }
    }

    impl AuthenticatorFactory for LocalAuthFactory {
        fn build(&self) -> Box<dyn Authenticator> {
            self.build_inner(None)
        }

        fn build_with_peer(&self, peer: Option<&str>) -> Box<dyn Authenticator> {
            self.build_inner(peer)
        }
    }

    struct ShellCommandHandler {
        pam: Arc<pam_gate::PamGate>,
        debug: bool,
        /// When `false` (the default), debug-mode exec logs print only the
        /// first whitespace-separated token of the command — secrets passed
        /// on the command line (e.g. `mysql -p<pass>`, `curl
        /// https://u:p@host`) never reach stderr/journald.  `--debug-commands`
        /// opts in to full command logging for development.
        debug_commands: bool,
    }

    impl ShellCommandHandler {
        /// Everything needed to run `command` for `user`, short of spawning:
        /// logging, the passwd lookup, PAM session, environment and the
        /// privilege drop (in `pre_exec`). `Err` is a message for stderr.
        /// `command: None` runs the login shell itself (a `shell` request
        /// without a terminal), as OpenSSH: argv0 `-bash`, commands on stdin.
        fn prepare(
            &self,
            user: &str,
            env: &SessionEnv,
            command: Option<&str>,
        ) -> Result<Command, String> {
            // Both the config `ForceCommand` directive and a user certificate's
            // `force-command` critical option are applied uniformly by the
            // server connection-phase dispatcher (it rewrites `command` to the
            // forced one and injects `$SSH_ORIGINAL_COMMAND` into the session
            // env before this handler runs). The handler therefore sees the
            // already-forced command and the populated env — no separate
            // force-command path lives here.
            if self.debug
                && let Some(command) = command
            {
                if self.debug_commands {
                    eprintln!("sshd: exec by {user}: {}", sanitize_log(command));
                } else {
                    // Log only the first token (the program name) plus an
                    // argument count, so operators can see *what* ran
                    // without leaking secrets passed on the command line.
                    // Use char_indices so we never split inside a UTF-8
                    // codepoint and don't allocate a Vec to count args.
                    let name = command.split_whitespace().next().unwrap_or("");
                    let extra = command.split_whitespace().skip(1).count();
                    eprintln!(
                        "sshd: exec by {user}: {} (+{extra} args, redacted)",
                        sanitize_log(name)
                    );
                }
            }

            // Resolve the target user in /etc/passwd first — every
            // subsequent step (PAM open, env layering, setuid) depends
            // on these values. A missing user is a hard fail.
            let info = lookup_user(user).map_err(|e| format!("sshd: user lookup failed: {e}\n"))?;

            // Open the PAM session before spawning the child. `exec`
            // requests don't have a real tty, so we use "ssh" — matches
            // OpenSSH's behaviour for non-PTY channels. `ExecResult`
            // has no error channel, so PAM failure surfaces as exit
            // status 255 with the error message on stderr.
            let mut envs = self
                .pam
                .ensure(user, "ssh")
                .map_err(|e| format!("sshd: PAM session open failed: {e}\n"))?;
            apply_login_envs(&mut envs, &info);

            // Run the command via the user's login shell so that
            // /etc/passwd-configured shells (zsh, fish, …) are honoured.
            let mut cmd = Command::new(&info.shell_str);
            match command {
                Some(command) => {
                    cmd.args(["-c", command]);
                }
                None => {
                    cmd.arg0(OsStr::from_bytes(info.argv0_c.to_bytes()));
                }
            }
            cmd.env_clear();
            for (k, v) in &envs {
                cmd.env(
                    OsStr::from_bytes(k.to_bytes()),
                    OsStr::from_bytes(v.to_bytes()),
                );
            }
            // Layer the per-channel SSH `env` requests *over* PAM env so the
            // client's LANG / LC_* / TERM / user-supplied variables win.
            // RFC 4254 §6.4 makes this scope per-session-channel; the
            // dispatcher already discards the env on channel close.
            // safe_session_env enforces a defense-in-depth blocklist
            // (LD_PRELOAD/IFS/PATH/etc.) on top of the server's filter.
            for (k, v) in session_vars(env, &info.home_str) {
                cmd.env(k, v);
            }
            for (k, v) in connection_env(None) {
                cmd.env(k, v);
            }

            // Drop to the user inside the spawned child via pre_exec.
            // We can't use Command::uid()/.gid()/.current_dir() because
            // std calls them in the wrong order for `initgroups` — std
            // does setgid → setgroups([]) → setuid → chdir, blowing
            // away the supplementary groups we want and forcing chdir
            // after setuid. Do the whole dance ourselves.
            if !already_matches(&info) {
                let uid = info.uid;
                let gid = info.gid;
                let name_c = info.name_c.clone();
                let home_c = info.home_c.clone();
                // SAFETY: pre_exec runs in the post-fork child between
                // fork and exec. We only call POSIX-defined functions
                // (setgid, initgroups, setuid, chdir) — all used in
                // OpenSSH's drop-to-user path and considered safe in
                // the single-threaded post-fork window.
                unsafe {
                    cmd.pre_exec(move || {
                        // setgroups([]) → setgid → initgroups → setuid
                        // (see drop_to_user for the full rationale).
                        setgroups_clear().map_err(to_io)?;
                        nix::unistd::setgid(gid).map_err(to_io)?;
                        initgroups_libc(&name_c, gid).map_err(to_io)?;
                        nix::unistd::setuid(uid).map_err(to_io)?;
                        // Post-setuid sanity: the kernel can silently
                        // refuse setuid if we lack CAP_SETUID, leaving
                        // the child running as root.  Refuse to exec.
                        verify_post_setuid(uid, gid).map_err(to_io)?;
                        // chdir best-effort: a missing/unreadable home
                        // shouldn't refuse the exec — fall back to /.
                        if libc::chdir(home_c.as_ptr()) != 0 {
                            let _ = libc::chdir(c"/".as_ptr());
                        }
                        Ok(())
                    });
                }
            } else {
                // Same uid → still chdir for clean cwd semantics.
                cmd.current_dir(if std::path::Path::new(&info.home_str).is_dir() {
                    info.home_str.as_str()
                } else {
                    "/"
                });
            }
            // The rc files / xauth, as the user, in the home directory, with
            // the session's environment (std only installs it at exec).
            let vars: Vec<(String, String)> = cmd
                .get_envs()
                .filter_map(|(k, v)| Some((k.to_str()?.to_string(), v?.to_str()?.to_string())))
                .collect();
            if let Some(rc) = startup_rc(&info, env, false, Some(vars)) {
                // SAFETY: runs after the privilege drop above (closures run
                // in order); `run_startup_rc` is post-fork safe.
                unsafe {
                    cmd.pre_exec(move || {
                        run_startup_rc(&rc);
                        Ok(())
                    });
                }
            }
            Ok(cmd)
        }

        /// Run `command` streaming: channel data feeds its stdin (EOF
        /// closes it), its stdout and stderr go out as they are produced,
        /// then its exit status. This is what `ssh host command` (git,
        /// rsync, `tail -f`, `cat > file`) needs.
        fn run_streaming(
            &self,
            user: &str,
            env: &SessionEnv,
            command: Option<&str>,
            mut stream: ChannelStream,
        ) -> puressh::Result<()> {
            use puressh::server::ChannelEgress;
            use std::io::{Read, Write};
            let mut cmd = match self.prepare(user, env, command) {
                Ok(c) => c,
                Err(msg) => {
                    let _ = stream.write_stderr(msg.as_bytes());
                    let _ = stream.send_exit_status(255);
                    return Ok(());
                }
            };
            cmd.stdin(std::process::Stdio::piped());
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
            let mut child = match cmd.spawn() {
                Ok(c) => c,
                Err(e) => {
                    let _ = stream.write_stderr(format!("sshd: failed to spawn: {e}\n").as_bytes());
                    let _ = stream.send_exit_status(255);
                    return Ok(());
                }
            };
            let (rx, tx) = stream.into_raw();

            // channel → stdin. Not joined: it ends when the client sends EOF
            // or the channel goes away.
            if let Some(mut child_in) = child.stdin.take() {
                std::thread::spawn(move || {
                    while let Ok(Some(bytes)) = rx.recv() {
                        if child_in.write_all(&bytes).is_err() {
                            break;
                        }
                    }
                    // Dropping `child_in` closes the command's stdin.
                });
            }

            fn pump<R: Read + Send + 'static>(
                mut r: R,
                tx: std::sync::mpsc::SyncSender<ChannelEgress>,
                stderr: bool,
            ) -> std::thread::JoinHandle<()> {
                std::thread::spawn(move || {
                    let mut buf = vec![0u8; 32 * 1024];
                    loop {
                        match r.read(&mut buf) {
                            Ok(0) => break,
                            Ok(n) => {
                                let chunk = buf[..n].to_vec();
                                let msg = if stderr {
                                    ChannelEgress::Stderr(chunk)
                                } else {
                                    ChannelEgress::Data(chunk)
                                };
                                if tx.send(msg).is_err() {
                                    break;
                                }
                            }
                            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
                            Err(_) => break,
                        }
                    }
                })
            }
            let t_out = child.stdout.take().map(|o| pump(o, tx.clone(), false));
            let t_err = child.stderr.take().map(|e| pump(e, tx.clone(), true));
            if let Some(t) = t_out {
                let _ = t.join();
            }
            if let Some(t) = t_err {
                let _ = t.join();
            }
            if let Ok(status) = child.wait() {
                // A command killed by a signal has no exit status; the
                // client then reports 255, like OpenSSH.
                if let Some(code) = status.code() {
                    let _ = tx.send(ChannelEgress::ExitStatus(code as u32));
                }
            }
            let _ = tx.send(ChannelEgress::Eof);
            let _ = tx.send(ChannelEgress::Close);
            Ok(())
        }
    }

    impl CommandHandler for ShellCommandHandler {
        fn handle(&self, user: &str, env: &SessionEnv, command: &str) -> ExecResult {
            let mut cmd = match self.prepare(user, env, Some(command)) {
                Ok(c) => c,
                Err(msg) => return ExecResult::new(Vec::new(), msg.into_bytes(), 255),
            };

            // Spawn + manually drain so we can cap total buffered
            // output. `cmd.output()` would grow each stream
            // unboundedly — a long-running `find /` or `cat /dev/zero`
            // would let the daemon OOM. 16 MiB per stream is more than
            // any sane `ssh host cmd` produces; if a workload needs to
            // ship more, it should use SFTP / a streaming
            // ExecStreamHandler / a pty shell instead.
            const EXEC_BUFFER_CAP: usize = 16 * 1024 * 1024;
            cmd.stdin(std::process::Stdio::null());
            cmd.stdout(std::process::Stdio::piped());
            cmd.stderr(std::process::Stdio::piped());
            let mut child = match cmd.spawn() {
                Ok(c) => c,
                Err(e) => {
                    return ExecResult::new(
                        Vec::new(),
                        format!("sshd: failed to spawn: {e}\n").into_bytes(),
                        255,
                    );
                }
            };

            // Drain stdout and stderr on dedicated threads so a slow
            // reader on one doesn't deadlock the producer (kernel-pipe
            // backpressure → child blocks → other stream never read).
            let mut out_pipe = child.stdout.take().expect("stdout piped");
            let mut err_pipe = child.stderr.take().expect("stderr piped");
            let out_thr = std::thread::spawn(move || drain_capped(&mut out_pipe, EXEC_BUFFER_CAP));
            let err_thr = std::thread::spawn(move || drain_capped(&mut err_pipe, EXEC_BUFFER_CAP));

            let status = match child.wait() {
                Ok(s) => s,
                Err(e) => {
                    return ExecResult::new(
                        Vec::new(),
                        format!("sshd: wait failed: {e}\n").into_bytes(),
                        255,
                    );
                }
            };
            let (mut stdout_buf, stdout_overflow) = out_thr.join().unwrap_or_default();
            let (mut stderr_buf, stderr_overflow) = err_thr.join().unwrap_or_default();
            if stdout_overflow {
                stderr_buf.extend_from_slice(b"\nsshd: stdout exceeded 16 MiB cap (truncated)\n");
            }
            if stderr_overflow {
                stderr_buf.extend_from_slice(b"\nsshd: stderr exceeded 16 MiB cap (truncated)\n");
            }
            let code = status.code().unwrap_or(255);
            let code_u32 = if code < 0 { 255u32 } else { code as u32 };
            // If we capped, force a non-zero exit so the client knows
            // its command's output was lossy (matches the "abort the
            // channel beyond that" intent from finding #6).
            let final_code = if (stdout_overflow || stderr_overflow) && code_u32 == 0 {
                stdout_buf.clear();
                255u32
            } else {
                code_u32
            };
            ExecResult::new(stdout_buf, stderr_buf, final_code)
        }
    }

    /// Read from `r` until EOF, capping the returned buffer at `cap`
    /// bytes. Returns `(buf, overflowed)`: `overflowed` is true when at
    /// least one extra byte was on the wire — the caller treats this as
    /// "channel aborted".
    fn drain_capped<R: std::io::Read>(r: &mut R, cap: usize) -> (Vec<u8>, bool) {
        let mut buf = Vec::with_capacity(8 * 1024);
        let mut chunk = [0u8; 8 * 1024];
        let mut overflow = false;
        loop {
            match r.read(&mut chunk) {
                Ok(0) => break,
                Ok(n) => {
                    if buf.len() + n > cap {
                        let room = cap.saturating_sub(buf.len());
                        if room > 0 {
                            buf.extend_from_slice(&chunk[..room]);
                        }
                        overflow = true;
                        // Keep draining so the child's pipe doesn't
                        // back up — but discard everything past the
                        // cap. Without this the producer eventually
                        // blocks on PIPE-full and we hang in
                        // `child.wait()`.
                        continue;
                    }
                    buf.extend_from_slice(&chunk[..n]);
                }
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(_) => break,
            }
        }
        (buf, overflow)
    }

    /// `pre_exec` closures need a closed `io::Error`-returning path; nix
    /// errnos must be lifted here. Lives at module scope so the closure
    /// stays `'static`-friendly.
    fn to_io(e: Errno) -> std::io::Error {
        std::io::Error::from_raw_os_error(e as i32)
    }

    /// Apple targets dropped `nix::unistd::initgroups` (see the cfg gate at
    /// `nix-0.30/src/unistd.rs`), so we call the libc function directly. The
    /// signature is POSIX-stable across Linux and macOS; the gid type
    /// (`libc::gid_t`) matches `nix::unistd::Gid` byte-for-byte.
    ///
    /// SAFETY: `user` must be a valid NUL-terminated C string. The pre-fork
    /// callers all pass `info.name_c.as_ptr()` from a long-lived `CString`.
    fn initgroups_libc(user: &std::ffi::CStr, gid: nix::unistd::Gid) -> nix::Result<()> {
        // SAFETY: `user.as_ptr()` is a valid NUL-terminated string for the
        // duration of the call (CStr's invariant).
        let rc = unsafe { libc::initgroups(user.as_ptr(), gid.as_raw() as _) };
        if rc == 0 { Ok(()) } else { Err(Errno::last()) }
    }

    /// Drop every supplementary group from the calling process.
    ///
    /// `initgroups(user, gid)` reads /etc/group for the *target* user, but
    /// if we never explicitly clear the root daemon's supplementary groups
    /// first, certain libc implementations have historically retained
    /// extras across the call (and a misconfigured /etc/group can simply
    /// fail to assign new ones, leaving the daemon's groups intact in the
    /// child). Call `setgroups([])` immediately before `initgroups` so the
    /// post-setuid process is *guaranteed* to start from an empty
    /// supplementary group list — matching OpenSSH's behaviour.
    ///
    /// SAFETY: We're the only thread in the post-fork child (or we hold
    /// root in the pre-fork path); passing a 0-length list is well-defined
    /// across Linux and the BSDs.
    fn setgroups_clear() -> nix::Result<()> {
        // SAFETY: `count=0` with a null/dangling pointer is the documented
        // way to clear the supplementary group list on Linux and macOS.
        let rc = unsafe { libc::setgroups(0, core::ptr::null()) };
        if rc == 0 { Ok(()) } else { Err(Errno::last()) }
    }

    /// Confirm the calling process really dropped to `(uid, gid)`. Any
    /// mismatch on real/effective/saved uid or real/effective gid means
    /// the kernel call silently failed (or the binary lacks the necessary
    /// capability) — refuse to continue rather than running the user's
    /// shell with mixed privileges.
    fn verify_post_setuid(uid: nix::unistd::Uid, gid: nix::unistd::Gid) -> nix::Result<()> {
        // SAFETY: getresuid/getresgid only write to caller-owned locals.
        // On non-Linux platforms we fall back to geteuid/getuid/getegid/
        // getgid which are universally available.
        #[cfg(target_os = "linux")]
        {
            let mut ruid: libc::uid_t = 0;
            let mut euid: libc::uid_t = 0;
            let mut suid: libc::uid_t = 0;
            let mut rgid: libc::gid_t = 0;
            let mut egid: libc::gid_t = 0;
            let mut sgid: libc::gid_t = 0;
            // SAFETY: pointers refer to live stack locals.
            if unsafe { libc::getresuid(&mut ruid, &mut euid, &mut suid) } != 0 {
                return Err(Errno::last());
            }
            if unsafe { libc::getresgid(&mut rgid, &mut egid, &mut sgid) } != 0 {
                return Err(Errno::last());
            }
            let want_u = uid.as_raw();
            let want_g = gid.as_raw();
            if ruid != want_u || euid != want_u || suid != want_u {
                return Err(Errno::EPERM);
            }
            if rgid != want_g || egid != want_g || sgid != want_g {
                return Err(Errno::EPERM);
            }
            Ok(())
        }
        #[cfg(not(target_os = "linux"))]
        {
            // SAFETY: get{e,}{u,g}id never fail per POSIX.
            let ruid = unsafe { libc::getuid() };
            let euid = unsafe { libc::geteuid() };
            let rgid = unsafe { libc::getgid() };
            let egid = unsafe { libc::getegid() };
            if ruid != uid.as_raw() || euid != uid.as_raw() {
                return Err(Errno::EPERM);
            }
            if rgid != gid.as_raw() || egid != gid.as_raw() {
                return Err(Errno::EPERM);
            }
            Ok(())
        }
    }

    fn current_user() -> Result<String, String> {
        // The password database first: services and containers often run
        // without $USER.
        if let Ok(Some(u)) = nix::unistd::User::from_uid(nix::unistd::getuid()) {
            return Ok(u.name);
        }
        std::env::var("USER")
            .or_else(|_| std::env::var("LOGNAME"))
            .map_err(|_| "could not determine current user".into())
    }

    /// Defense-in-depth: scrub the per-channel SSH `env` list of any name
    /// in `HARD_BLOCKED_ENV_NAMES` before we layer it onto the child
    /// process's environment. The server's accept-env filter already runs
    /// upstream (see `puressh::server::env_name_accepted`), so under
    /// normal operation no blocked name should ever reach here. This is a
    /// belt-and-suspenders check: a future bug, a misconfigured custom
    /// `ChannelRequest::Env` interceptor, or a downstream caller that
    /// bypasses the server layer must not be able to slip
    /// LD_PRELOAD/IFS/PATH/etc. into the user's shell.
    ///
    /// Names with embedded NUL are dropped too — they can't safely make
    /// it into a `setenv`/`Command::env` call anyway.
    fn safe_session_env(env: &SessionEnv) -> Vec<(&str, &str)> {
        env.iter()
            .filter(|(k, v)| {
                !k.contains('\0') && !v.contains('\0') && !HARD_BLOCKED_ENV_NAMES.contains(k)
            })
            .collect()
    }

    /// The session's variables, layered as OpenSSH does: the client's
    /// (`AcceptEnv`) and `environment=` key options, then the user's
    /// `~/.ssh/environment` where `PermitUserEnvironment` allows, then the
    /// administrator's `SetEnv`, which wins. `home` is read as the user.
    fn session_vars(env: &SessionEnv, home: &str) -> Vec<(String, String)> {
        let mut vars: Vec<(String, String)> = safe_session_env(env)
            .into_iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let mut set = |k: &str, v: &str| {
            if k.is_empty() || k.contains('\0') || v.contains('\0') {
                return;
            }
            match vars.iter_mut().find(|(n, _)| n == k) {
                Some(slot) => slot.1 = v.to_string(),
                None => vars.push((k.to_string(), v.to_string())),
            }
        };
        if env.user_environment_enabled() {
            // OpenSSH's read_environment_file: NAME=value lines, comments
            // and blank lines skipped, at most 1000 entries.
            let path = format!("{home}/.ssh/environment");
            if let Ok(text) = std::fs::read_to_string(&path) {
                for line in text.lines().take(1000) {
                    let line = line.trim_start();
                    if line.is_empty() || line.starts_with('#') {
                        continue;
                    }
                    if let Some((k, v)) = line.split_once('=')
                        && env.user_environment_permits(k)
                        && !HARD_BLOCKED_ENV_NAMES.contains(&k)
                    {
                        set(k, v);
                    }
                }
            }
        }
        for (k, v) in env.admin_env() {
            set(k, v);
        }
        vars
    }

    /// Same filter as [`safe_session_env`], but on an owned `(String,
    /// String)` snapshot already in hand. Kept as a separate helper so
    /// the borrow-vs-owned call sites don't need to allocate twice.
    fn safe_owned_env(env: &[(String, String)]) -> Vec<(String, String)> {
        env.iter()
            .filter(|(k, v)| {
                !k.contains('\0')
                    && !v.contains('\0')
                    && !HARD_BLOCKED_ENV_NAMES.contains(&k.as_str())
            })
            .cloned()
            .collect()
    }

    // -------------------------------------------------------------------------
    // User lookup + drop-to-user plumbing.
    //
    // Authentication only proves the SSH peer holds a private key; it
    // doesn't switch identity. After PAM session-open succeeds we look
    // up the target user in `/etc/passwd` and drop our euid/egid before
    // executing the shell, so the user's processes really run as them
    // and not as whatever uid the daemon was launched with. Soft-mode:
    // when the daemon's already running as the target uid (e.g. an
    // unprivileged smoke test where `-u $USER`), the drop is a no-op.
    // -------------------------------------------------------------------------

    /// `XAuthLocation` (`None`: `none`), set once at startup.
    static XAUTH_LOCATION: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();

    /// What runs in the session process just before its shell or command,
    /// as OpenSSH's do_rc_files: `~/.ssh/rc` (through the user's shell,
    /// when allowed), else `/etc/ssh/sshrc`, each fed `proto cookie` of a
    /// forwarded X11 display on stdin; else, for X11, `xauth` adding the
    /// display's cookie. Built before the fork: running it only uses
    /// async-signal-safe calls.
    struct StartupRc {
        _strings: Vec<std::ffi::CString>,
        argv: Vec<*const libc::c_char>,
        /// `None`: the current environment (the pty child has set it up).
        envp: Option<Vec<*const libc::c_char>>,
        input: Vec<u8>,
    }

    // SAFETY: the pointers point into `_strings` (or into CStrings owned by
    // the same closure), which live as long as the plan and never move.
    unsafe impl Send for StartupRc {}
    unsafe impl Sync for StartupRc {}

    /// The plan for a session of `info` with `env` (`None`: nothing runs).
    /// `subsystem`: only `/etc/ssh/sshrc` applies, as in OpenSSH.
    fn startup_rc(
        info: &UserInfo,
        env: &SessionEnv,
        subsystem: bool,
        envp: Option<Vec<(String, String)>>,
    ) -> Option<StartupRc> {
        let x11 = env.x11_auth();
        let cookie_line = x11.map(|(proto, cookie, _)| format!("{proto} {cookie}\n"));
        let user_rc = format!("{}/.ssh/rc", info.home_str);
        let (command, input) =
            if !subsystem && env.user_rc_allowed() && std::path::Path::new(&user_rc).exists() {
                (
                    format!("{} -c '/bin/sh {user_rc}'", info.shell_str),
                    cookie_line,
                )
            } else if std::path::Path::new("/etc/ssh/sshrc").exists() {
                ("/bin/sh /etc/ssh/sshrc".to_string(), cookie_line)
            } else if let (Some((proto, cookie, display)), Some(Some(xauth))) =
                (x11, XAUTH_LOCATION.get())
            {
                (
                    format!("{xauth} -q -"),
                    Some(format!(
                        "remove {display}\nadd {display} {proto} {cookie}\n"
                    )),
                )
            } else {
                return None;
            };
        let mut strings = Vec::new();
        for a in ["/bin/sh", "-c", command.as_str()] {
            strings.push(std::ffi::CString::new(a).ok()?);
        }
        let n_argv = strings.len();
        if let Some(vars) = &envp {
            for (k, v) in vars {
                strings.push(std::ffi::CString::new(format!("{k}={v}")).ok()?);
            }
        }
        let ptrs: Vec<*const libc::c_char> = strings.iter().map(|s| s.as_ptr()).collect();
        let mut argv = ptrs[..n_argv].to_vec();
        argv.push(std::ptr::null());
        let envp = envp.map(|_| {
            let mut e = ptrs[n_argv..].to_vec();
            e.push(std::ptr::null());
            e
        });
        Some(StartupRc {
            _strings: strings,
            argv,
            envp,
            input: input.unwrap_or_default().into_bytes(),
        })
    }

    /// Run `rc` and wait for it, feeding its stdin; its stdout / stderr are
    /// the session's. Post-fork safe: no allocation.
    fn run_startup_rc(rc: &StartupRc) {
        // SAFETY: plain fd / process syscalls on fds this function owns;
        // argv / envp are NUL-terminated arrays of live C strings.
        unsafe {
            let mut fds = [0 as libc::c_int; 2];
            if libc::pipe(fds.as_mut_ptr()) != 0 {
                return;
            }
            // Writing to an rc that does not read must not kill us.
            let old = libc::signal(libc::SIGPIPE, libc::SIG_IGN);
            let pid = libc::fork();
            if pid == 0 {
                libc::signal(libc::SIGPIPE, libc::SIG_DFL);
                libc::dup2(fds[0], 0);
                libc::close(fds[0]);
                libc::close(fds[1]);
                match &rc.envp {
                    Some(envp) => libc::execve(rc.argv[0], rc.argv.as_ptr(), envp.as_ptr()),
                    None => libc::execv(rc.argv[0], rc.argv.as_ptr()),
                };
                libc::_exit(127);
            }
            libc::close(fds[0]);
            if pid > 0 {
                let mut off = 0;
                while off < rc.input.len() {
                    let n = libc::write(
                        fds[1],
                        rc.input[off..].as_ptr() as *const libc::c_void,
                        rc.input.len() - off,
                    );
                    if n <= 0 {
                        if n < 0
                            && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR)
                        {
                            continue;
                        }
                        break;
                    }
                    off += n as usize;
                }
            }
            libc::close(fds[1]);
            if pid > 0 {
                let mut status = 0;
                while libc::waitpid(pid, &mut status, 0) < 0
                    && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR)
                {
                }
            }
            libc::signal(libc::SIGPIPE, old);
        }
    }

    /// Resolved POSIX identity for a login user. Captured pre-fork so
    /// every field is already owned and async-signal-safe to consume
    /// from the post-fork child.
    #[derive(Clone)]
    struct UserInfo {
        name: String,
        /// `name` as a `CString` — used directly by `initgroups`,
        /// which only takes `&CStr` and isn't safe to allocate against
        /// post-fork.
        name_c: std::ffi::CString,
        uid: nix::unistd::Uid,
        gid: nix::unistd::Gid,
        /// Home directory as a `CString` — fed straight to `chdir`.
        /// Falls back to `/` if the entry's home is unreadable so the
        /// shell still has a working cwd.
        home_c: std::ffi::CString,
        home_str: String,
        /// Login shell as a `CString` for `execvp`. Defaults to
        /// `/bin/sh` if `pw_shell` is empty or non-UTF-8.
        shell_c: std::ffi::CString,
        shell_str: String,
        /// Login-shell argv0 — `"-"` followed by the basename of
        /// `shell` (bash/zsh/sh treat this as "behave as a login shell"
        /// and source profile files).
        argv0_c: std::ffi::CString,
    }

    /// The authenticated user's identity as resolved by the session-open
    /// hook from the *real* passwd database, before any `ChrootDirectory`.
    /// Fork's copy-on-write isolates it per connection. Once set,
    /// [`lookup_user`] answers for that name from here, so a jail without an
    /// `/etc/passwd` still works and a jail *with* a writable one cannot
    /// feed the daemon a different uid/home/shell.
    static SESSION_USER: Mutex<Option<UserInfo>> = Mutex::new(None);

    fn remember_session_user(info: &UserInfo) {
        if let Ok(mut g) = SESSION_USER.lock() {
            *g = Some(info.clone());
        }
    }

    fn lookup_user(name: &str) -> puressh::Result<UserInfo> {
        if let Ok(g) = SESSION_USER.lock()
            && let Some(info) = g.as_ref()
            && info.name == name
        {
            return Ok(info.clone());
        }
        let user = nix::unistd::User::from_name(name)
            .map_err(nix_io)?
            .ok_or_else(|| {
                puressh::Error::Io(std::io::Error::other(format!("user '{name}' not found")))
            })?;

        let name_c = std::ffi::CString::new(user.name.clone()).map_err(|_| {
            puressh::Error::Io(std::io::Error::other("user name contains NUL byte"))
        })?;

        let home_str = user.dir.to_string_lossy().into_owned();
        let home_for_c = if home_str.is_empty() { "/" } else { &home_str };
        let home_c = std::ffi::CString::new(home_for_c.as_bytes()).map_err(|_| {
            puressh::Error::Io(std::io::Error::other("home directory contains NUL byte"))
        })?;

        let shell_str = {
            let s = user.shell.to_string_lossy();
            if s.is_empty() {
                "/bin/sh".to_string()
            } else {
                s.into_owned()
            }
        };
        let shell_c = std::ffi::CString::new(shell_str.as_bytes()).map_err(|_| {
            puressh::Error::Io(std::io::Error::other("shell path contains NUL byte"))
        })?;

        // argv0 = "-" + basename(shell). Login-shell convention.
        let basename = std::path::Path::new(&shell_str)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("sh");
        let argv0 = format!("-{basename}");
        let argv0_c = std::ffi::CString::new(argv0).map_err(|_| {
            puressh::Error::Io(std::io::Error::other("shell argv0 contains NUL byte"))
        })?;

        Ok(UserInfo {
            name: user.name,
            name_c,
            uid: user.uid,
            gid: user.gid,
            home_c,
            home_str,
            shell_c,
            shell_str,
            argv0_c,
        })
    }

    /// Whether `name` resolves to the root account (uid 0) in the passwd
    /// database *right now*. The literal name `root` always counts (so the
    /// policy holds even if the passwd lookup transiently fails); any other
    /// name is root only if it currently maps to uid 0 — this catches
    /// uid-0 aliases like `toor`. Resolved at login time, never cached
    /// across connections, so it can't go stale against the daemon's
    /// lifetime.
    fn resolves_to_root(name: &str) -> bool {
        name == "root"
            || matches!(
                nix::unistd::User::from_name(name),
                Ok(Some(u)) if u.uid.as_raw() == 0
            )
    }

    /// Resolve `name`'s supplementary group names via `getgrouplist(3)` plus
    /// its primary group, for `Match group` / `AllowGroups` / `DenyGroups`.
    /// Returns an empty vec for an unknown user or on any lookup failure —
    /// resolved uniformly at login time (mirrors [`resolves_to_root`]) so the
    /// call cannot become a user-enumeration timing oracle.
    /// Platform-portable group-gid list for `name` with primary `gid`.
    /// Uses `getgrouplist(3)` where nix exposes it; elsewhere falls back to
    /// the primary group only.
    #[cfg(not(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "aix",
        target_os = "illumos",
        target_os = "solaris",
        target_os = "redox",
    )))]
    fn group_gids(name: &str, primary: nix::unistd::Gid) -> Vec<nix::unistd::Gid> {
        let cname = match std::ffi::CString::new(name) {
            Ok(c) => c,
            Err(_) => return vec![primary],
        };
        nix::unistd::getgrouplist(&cname, primary).unwrap_or_else(|_| vec![primary])
    }

    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "aix",
        target_os = "illumos",
        target_os = "solaris",
        target_os = "redox",
    ))]
    fn group_gids(_name: &str, primary: nix::unistd::Gid) -> Vec<nix::unistd::Gid> {
        vec![primary]
    }

    fn lookup_user_groups(name: &str) -> Vec<String> {
        use nix::unistd::{Gid, Group, User};
        let Ok(Some(user)) = User::from_name(name) else {
            return Vec::new();
        };
        // getgrouplist returns the user's group gids (primary + supplementary)
        // on platforms that expose it; fall back to just the primary group if
        // it fails or is unavailable (macOS / Solaris / AIX don't have it in
        // nix). The primary group still feeds AllowGroups/DenyGroups there.
        let gids: Vec<Gid> = group_gids(name, user.gid);
        let mut names: Vec<String> = Vec::new();
        for gid in gids {
            if let Ok(Some(g)) = Group::from_gid(gid)
                && !names.contains(&g.name)
            {
                names.push(g.name);
            }
        }
        names
    }

    /// Layer login env vars (HOME/USER/LOGNAME/SHELL) on top of the
    /// snapshot returned by PAM. Conventional names — pam_env may have
    /// supplied some of them already; we overwrite with the resolved
    /// `/etc/passwd` truth.
    fn apply_login_envs(envs: &mut Vec<(std::ffi::CString, std::ffi::CString)>, info: &UserInfo) {
        // CString::new can't fail on these (no interior NUL by
        // construction in lookup_user). Use unwrap_or_default as a
        // belt-and-braces fallback.
        let pairs: [(&str, &std::ffi::CString); 4] = [
            ("HOME", &info.home_c),
            ("USER", &info.name_c),
            ("LOGNAME", &info.name_c),
            ("SHELL", &info.shell_c),
        ];
        for (k, v) in pairs {
            let key = std::ffi::CString::new(k).unwrap_or_default();
            // Overwrite any pam_env contribution: /etc/passwd wins.
            if let Some(slot) = envs
                .iter_mut()
                .find(|(kk, _)| kk.as_bytes() == k.as_bytes())
            {
                slot.1 = v.clone();
            } else {
                envs.push((key, v.clone()));
            }
        }
    }

    /// The variables OpenSSH gives every session: `SSH_CLIENT` (client
    /// address and port, server port), `SSH_CONNECTION` (client address and
    /// port, server address and port) and, on a pty, `SSH_TTY`. Set after
    /// the client's `env` requests, which cannot replace them.
    fn connection_env(tty: Option<&str>) -> Vec<(&'static str, String)> {
        let mut out = Vec::new();
        if INETD.load(Ordering::Relaxed) {
            // stdin is not a socket: OpenSSH's placeholders.
            out.push(("SSH_CLIENT", "UNKNOWN 65535 65535".to_string()));
            out.push(("SSH_CONNECTION", "UNKNOWN 65535 UNKNOWN 65535".to_string()));
        } else if let Some((peer, local)) = conn_addrs() {
            let (lip, lport) = local.map_or((String::new(), 0), |l| {
                (sshd_log::addr_str(l.ip()), l.port())
            });
            let pip = sshd_log::addr_str(peer.ip());
            out.push(("SSH_CLIENT", format!("{pip} {} {lport}", peer.port())));
            out.push((
                "SSH_CONNECTION",
                format!("{pip} {} {lip} {lport}", peer.port()),
            ));
        }
        if let Some(t) = tty {
            out.push(("SSH_TTY", t.to_string()));
        }
        out
    }

    /// True iff we're already running as `info`'s uid/gid — in which
    /// case the setuid/setgid/initgroups dance is unnecessary (and
    /// would in fact fail for non-root daemons).
    fn already_matches(info: &UserInfo) -> bool {
        nix::unistd::geteuid() == info.uid && nix::unistd::getegid() == info.gid
    }

    // -------------------------------------------------------------------------
    // NixShellHandler — backend for `pty-req` + `shell`. Allocates a PTY
    // with `openpty()`, forks manually so PAM_TTY can be set pre-fork,
    // drops to the target user's uid/gid, then `execvp`s their login
    // shell. Exposes the master fd as a non-blocking `ShellSession`.
    // -------------------------------------------------------------------------

    struct NixShellHandler {
        pam: Arc<pam_gate::PamGate>,
        debug: bool,
        /// Per-connection `PrintMotd`, written by `on_session_open` and read at
        /// shell spawn. Shared via `Arc` so the (COW-isolated, per-fork) child
        /// sees the value the hook resolved for this connection. Only the PTY
        /// path consults it — `/etc/motd` is for interactive logins.
        print_motd: Arc<std::sync::atomic::AtomicBool>,
    }

    impl ShellHandler for NixShellHandler {
        fn spawn(
            &self,
            user: &str,
            env: &SessionEnv,
            pty: Option<PtySpec>,
        ) -> puressh::Result<Box<dyn ShellSession>> {
            // Snapshot the per-channel env into an owned vector. spawn_pty_shell
            // forks and then setenv()s post-fork; the child can't hold a borrow
            // across that boundary, so we hand it owned (key, value) pairs.
            // safe_session_env enforces a defense-in-depth blocklist
            // (LD_PRELOAD/IFS/PATH/etc.) on top of the server's filter.
            let env_pairs = lookup_user(user)
                .map(|info| session_vars(env, &info.home_str))
                .unwrap_or_default();
            match pty {
                Some(spec) => {
                    let print_motd = self.print_motd.load(std::sync::atomic::Ordering::Relaxed);
                    let startup = lookup_user(user)
                        .ok()
                        .and_then(|info| startup_rc(&info, env, false, None));
                    spawn_pty_shell(
                        &self.pam, user, &env_pairs, &spec, self.debug, print_motd, None, startup,
                    )
                }
                None => spawn_pipe_shell(&self.pam, user, &env_pairs, self.debug),
            }
        }

        /// `ssh -t host command`: the command, through the user's shell,
        /// on a pseudo-terminal. No motd (OpenSSH prints it only for an
        /// interactive login).
        fn spawn_command(
            &self,
            user: &str,
            env: &SessionEnv,
            pty: PtySpec,
            command: &str,
        ) -> puressh::Result<Box<dyn ShellSession>> {
            let env_pairs = lookup_user(user)
                .map(|info| session_vars(env, &info.home_str))
                .unwrap_or_default();
            let startup = lookup_user(user)
                .ok()
                .and_then(|info| startup_rc(&info, env, false, None));
            spawn_pty_shell(
                &self.pam,
                user,
                &env_pairs,
                &pty,
                self.debug,
                false,
                Some(command),
                startup,
            )
        }
    }

    /// Read `/etc/motd` and return its bytes with bare `\n` line endings
    /// rewritten to `\r\n` so the message displays correctly on the raw PTY
    /// (a terminal in raw mode does not translate `\n`). Returns `None` (and,
    /// in debug, warns) if the file is missing or unreadable — a missing motd
    /// is normal and must never block the shell.
    fn read_motd_for_pty(debug: bool) -> Option<Vec<u8>> {
        match std::fs::read("/etc/motd") {
            Ok(bytes) => Some(crlf_for_pty(&bytes)),
            Err(e) => {
                if debug {
                    eprintln!("sshd: PrintMotd: cannot read /etc/motd: {e}");
                }
                None
            }
        }
    }

    /// Rewrite bare `\n` to `\r\n` for display on a raw-mode PTY. An existing
    /// `\r\n` is left intact (the `\r` is copied, then the `\n` does not get a
    /// second `\r` prepended because the byte before it was already `\r`).
    fn crlf_for_pty(bytes: &[u8]) -> Vec<u8> {
        let mut out = Vec::with_capacity(bytes.len() + 16);
        let mut prev = 0u8;
        for &b in bytes {
            if b == b'\n' && prev != b'\r' {
                out.push(b'\r');
            }
            out.push(b);
            prev = b;
        }
        out
    }

    // -------------------------------------------------------------------------
    // SftpSubsystemHandler — backend for `subsystem("sftp")`. Runs in-process
    // (no fork, no execvp): a fresh thread is spawned for each SFTP channel,
    // and the protocol loop reads/writes the channel via a `ChannelStream`.
    //
    // Privilege drop happens once per *connection* (see `drop_to_user` /
    // `Config::on_session_open` below), so all SFTP threads on a given
    // connection already run as the authenticated user — no per-channel
    // setuid is needed. The per-session virtual cwd carried by
    // `SftpServerSession` is what prevents concurrent SFTP channels from
    // stomping each other's working directory.
    // -------------------------------------------------------------------------

    struct SftpSubsystemHandler {
        /// `subsystem sftp` requests are served (a forced `internal-sftp`
        /// is, regardless).
        enabled: bool,
        read_only: bool,
        root: Option<std::path::PathBuf>,
        /// The `Subsystem sftp` line's sftp-server arguments.
        args: Vec<String>,
        debug: bool,
    }

    impl SubsystemHandler for SftpSubsystemHandler {
        fn serves(&self, name: &str) -> bool {
            self.enabled && name == "sftp"
        }

        fn handle(
            &self,
            user: &str,
            _env: &SessionEnv,
            name: &str,
            stream: ChannelStream,
        ) -> puressh::Result<()> {
            if name != "sftp" || !self.enabled {
                if self.debug {
                    eprintln!(
                        "sshd: refusing unknown subsystem '{}' for {user}",
                        sanitize_log(name)
                    );
                }
                return Ok(()); // dropping `stream` sends EOF + Close
            }
            self.serve(user, &self.args, stream)
        }

        fn handle_with_args(
            &self,
            user: &str,
            _env: &SessionEnv,
            _name: &str,
            args: &[String],
            stream: ChannelStream,
        ) -> puressh::Result<()> {
            self.serve(user, args, stream)
        }
    }

    impl SftpSubsystemHandler {
        /// One SFTP session, configured by sftp-server's arguments: `-d`
        /// (start directory, `%d` / `%u` expanded), `-u` (umask), `-R`
        /// (read-only). Logging options follow sshd's own; any other option
        /// (`-P` / `-p` request lists) refuses the session.
        fn serve(
            &self,
            user: &str,
            args: &[String],
            mut stream: ChannelStream,
        ) -> puressh::Result<()> {
            let info = lookup_user(user).ok();
            let mut read_only = self.read_only;
            let mut start_dir = None;
            let mut it = args.iter();
            while let Some(a) = it.next() {
                match a.as_str() {
                    "-R" => read_only = true,
                    "-d" => start_dir = it.next().cloned(),
                    "-u" => {
                        let mask = it.next().and_then(|m| u32::from_str_radix(m, 8).ok());
                        match mask {
                            // SAFETY: umask only swaps the process's mask.
                            Some(m) if m <= 0o777 => unsafe {
                                libc::umask(m as libc::mode_t);
                            },
                            _ => {
                                eprintln!("sftp-server: Invalid umask");
                                let _ = stream.send_exit_status(1);
                                return Ok(());
                            }
                        }
                    }
                    "-f" | "-l" => {
                        it.next();
                    }
                    "-e" | "-h" => {}
                    // Request allow / deny lists are not implemented: refuse
                    // the session rather than serve it unrestricted.
                    other => {
                        eprintln!("sftp-server: option {other} is not supported");
                        let _ = stream.send_exit_status(1);
                        return Ok(());
                    }
                }
            }

            // As OpenSSH: the home directory when it exists (inside a
            // ChrootDirectory it usually does not), else the root; `-d`
            // names another.
            let home = info
                .as_ref()
                .map(|i| std::path::PathBuf::from(&i.home_str))
                .filter(|h| h.is_dir());
            let mut cwd = home
                .clone()
                .unwrap_or_else(|| std::path::PathBuf::from("/"));
            if let Some(dir) = start_dir {
                let expanded = info.as_ref().map_or(Ok(dir.clone()), |i| {
                    expand_command_arg(&dir, &[('d', i.home_str.clone()), ('u', i.name.clone())])
                });
                let dir = match expanded {
                    Ok(d) => cwd.join(d),
                    Err(e) => {
                        eprintln!("sftp-server: -d: {e}");
                        let _ = stream.send_exit_status(1);
                        return Ok(());
                    }
                };
                if dir.is_dir() {
                    cwd = dir;
                } else {
                    eprintln!("sftp-server: chdir to \"{}\" failed", dir.display());
                }
            }

            let mut opts = SftpServerOptions::new(cwd);
            if let Some(root) = &self.root {
                opts = opts.with_root(root.clone());
            }
            if read_only {
                opts = opts.read_only();
            }

            let mut session = SftpServerSession::new(opts);
            if self.debug {
                eprintln!("sshd: sftp session opened for {user}");
            }
            // Report an exit status like OpenSSH's sftp-server process does:
            // scp and sftp treat a session without one as a failure.
            let res = session.run(&mut stream);
            let _ = stream.send_exit_status(if res.is_ok() { 0 } else { 1 });
            // Map SFTP-protocol errors into the generic puressh error type;
            // the dispatcher only cares whether the handler returned cleanly.
            res.map_err(|e| puressh::Error::Io(std::io::Error::other(format!("sftp: {e:?}"))))?;
            if self.debug {
                eprintln!("sshd: sftp session closed for {user}");
            }
            Ok(())
        }
    }

    // -------------------------------------------------------------------------
    // ScpExecHandler — intercept `exec scp -t …` / `exec scp -f …` requests
    // and run the in-process SCP sender/receiver on the channel. Anything
    // that doesn't look like an `scp` invocation falls through to the
    // buffered command handler (which then either runs it or refuses).
    //
    // We deliberately do NOT spawn a shell. The command string is parsed
    // ourselves with a single-quote-aware tokenizer; anything more elaborate
    // (pipes, redirections, command substitution, env assignments) is
    // refused. That gives us CVE-2020-15778-style protection without
    // depending on the user's shell quoting.
    //
    // Privilege drop already happened in `Config::on_session_open`, so the
    // handler thread runs as the authenticated user. The output path is
    // resolved against the user's home directory — that's the cwd both real
    // sshd and our own session loop expose to scp(1).
    // -------------------------------------------------------------------------

    struct ScpExecHandler {
        debug: bool,
    }

    /// Every `exec` request: in-process `scp` when enabled and asked for,
    /// otherwise the command through the user's shell, streamed.
    struct ExecDispatch {
        scp: Option<ScpExecHandler>,
        shell: Arc<ShellCommandHandler>,
    }

    impl ExecStreamHandler for ExecDispatch {
        fn claims(&self, _command: &str) -> bool {
            true
        }

        fn run(
            &self,
            user: &str,
            env: &SessionEnv,
            command: &str,
            stream: ChannelStream,
        ) -> puressh::Result<()> {
            match &self.scp {
                Some(scp) if scp.claims(command) => scp.run(user, env, command, stream),
                _ => self.shell.run_streaming(user, env, Some(command), stream),
            }
        }

        fn claims_login_shell(&self) -> bool {
            true
        }

        fn run_login_shell(
            &self,
            user: &str,
            env: &SessionEnv,
            stream: ChannelStream,
        ) -> puressh::Result<()> {
            self.shell.run_streaming(user, env, None, stream)
        }
    }

    impl ExecStreamHandler for ScpExecHandler {
        fn claims(&self, command: &str) -> bool {
            // Cheap pre-check before tokenising. We're after the literal
            // `scp ` prefix optionally preceded by whitespace.
            let t = command.trim_start();
            if !(t.starts_with("scp ") || t == "scp") {
                return false;
            }
            // Only a plain `scp -t|-f path` runs in-process; anything else
            // (a remote glob such as `scp -f -- *.txt`, other flags) goes to
            // the user's shell and the system scp, as with OpenSSH.
            tokenize_argv(command)
                .ok()
                .is_some_and(|argv| parse_scp_args(&argv).is_ok())
        }

        fn run(
            &self,
            user: &str,
            _env: &SessionEnv,
            command: &str,
            stream: ChannelStream,
        ) -> puressh::Result<()> {
            let argv = match tokenize_argv(command) {
                Ok(a) => a,
                Err(e) => {
                    if self.debug {
                        eprintln!("sshd: scp: refusing command {command:?}: {e}");
                    }
                    return Err(puressh::Error::Io(std::io::Error::other(format!(
                        "scp: {e}"
                    ))));
                }
            };
            let parsed = match parse_scp_args(&argv) {
                Ok(p) => p,
                Err(e) => {
                    if self.debug {
                        eprintln!("sshd: scp: bad args {argv:?}: {e}");
                    }
                    return Err(puressh::Error::Io(std::io::Error::other(format!(
                        "scp: {e}"
                    ))));
                }
            };

            // Resolve the target path against $HOME if relative. After the
            // connection-level priv drop the process cwd is wherever the
            // daemon was started — we don't want scp's bare-name argument
            // landing in /etc/sshd just because that's where systemd
            // started us.
            let home = lookup_user(user)
                .ok()
                .map(|i| std::path::PathBuf::from(&i.home_str))
                .unwrap_or_else(|| std::path::PathBuf::from("/"));
            let abs_path = if parsed.path.is_absolute() {
                parsed.path.clone()
            } else {
                home.join(&parsed.path)
            };

            if self.debug {
                eprintln!(
                    "sshd: scp {:?} {:?} (recursive={}, preserve_times={}) for {user}",
                    parsed.role, abs_path, parsed.recursive, parsed.preserve_times
                );
            }

            let mut stream = stream;
            let res = match parsed.role {
                // Several sources (`-d`) need a directory to land in: refuse
                // before the transfer starts, as OpenSSH's sink does.
                ScpRole::To if parsed.target_dir && !abs_path.is_dir() => {
                    let msg = format!("\x01scp: {}: Not a directory\n", abs_path.display());
                    let _ = std::io::Write::write_all(&mut stream, msg.as_bytes());
                    Err(puressh::scp::ScpError::Remote(format!(
                        "{}: Not a directory",
                        abs_path.display()
                    )))
                }
                ScpRole::To => {
                    // `scp -t` — the peer is the sender, we receive.
                    let mut opts = ScpRecvOptions::default();
                    opts.recursive = parsed.recursive;
                    opts.preserve_times = parsed.preserve_times;
                    // If the local destination already exists as a
                    // directory we use it as the parent; otherwise it's
                    // the literal file path.
                    opts.target_is_file = !abs_path.is_dir();
                    ScpReceiver::new(&mut stream, &abs_path, opts).and_then(|mut rx| rx.run())
                }
                ScpRole::From => {
                    // `scp -f` — we read from disk and send to the peer.
                    let mut opts = ScpSendOptions::default();
                    opts.recursive = parsed.recursive;
                    opts.preserve_times = parsed.preserve_times;
                    ScpSender::new(&mut stream).and_then(|mut tx| tx.send_path(&abs_path, &opts))
                }
            };
            // An exit status, as the scp process would have: the client
            // treats a session without one as a failure.
            let _ = stream.send_exit_status(if res.is_ok() { 0 } else { 1 });
            res.map_err(|e| puressh::Error::Io(std::io::Error::other(format!("scp: {e}"))))?;
            Ok(())
        }
    }

    /// One `scp` invocation's worth of parsed arguments. We only care about
    /// the role flag (`-t` or `-f`), the recursive/preserve_times modes, and
    /// the single positional path. Anything else is a hard reject.
    #[derive(Debug)]
    struct ParsedScp {
        role: ScpRole,
        recursive: bool,
        preserve_times: bool,
        /// `-d`: the target must be a directory (several sources).
        target_dir: bool,
        path: std::path::PathBuf,
    }

    #[derive(Debug)]
    enum ScpRole {
        /// `-t`: the peer is the sender; we write to disk.
        To,
        /// `-f`: the peer is the receiver; we read from disk.
        From,
    }

    /// Tokenize a command string with single-quote support — enough to
    /// handle the way OpenSSH's `scp(1)` quotes its remote arg list. We
    /// refuse anything that smells like shell metacharacters (`$`, `` ` ``,
    /// `&`, `|`, `;`, `<`, `>`, `(`, `)`, `\`, `"`, `*`, `?`, `[`, `]`,
    /// `{`, `}`, `~`, `!`) outside quotes, because the local-side `scp`
    /// crafts its remote command itself and never needs them.
    fn tokenize_argv(command: &str) -> Result<Vec<String>, String> {
        let mut out: Vec<String> = Vec::new();
        let mut cur = String::new();
        let mut in_word = false;
        let mut in_quote = false;
        let bytes = command.as_bytes();
        let mut i = 0;
        while i < bytes.len() {
            let c = bytes[i] as char;
            if in_quote {
                if c == '\'' {
                    in_quote = false;
                } else if c == '\n' || c == '\0' {
                    return Err("control character in quoted arg".into());
                } else {
                    cur.push(c);
                }
            } else if c == '\'' {
                in_quote = true;
                in_word = true;
            } else if c == ' ' || c == '\t' {
                if in_word {
                    out.push(std::mem::take(&mut cur));
                    in_word = false;
                }
            } else if matches!(
                c,
                '$' | '`'
                    | '&'
                    | '|'
                    | ';'
                    | '<'
                    | '>'
                    | '('
                    | ')'
                    | '\\'
                    | '"'
                    | '*'
                    | '?'
                    | '['
                    | ']'
                    | '{'
                    | '}'
                    | '~'
                    | '!'
                    | '\n'
                    | '\r'
                    | '\0'
            ) {
                return Err(format!("unsupported character {c:?} in command"));
            } else {
                cur.push(c);
                in_word = true;
            }
            i += 1;
        }
        if in_quote {
            return Err("unterminated single quote".into());
        }
        if in_word {
            out.push(cur);
        }
        Ok(out)
    }

    /// Parse `scp [-r] [-p] [-d] [-v] [-t|-f] [--] PATH`. We accept the
    /// usual mode flags plus `-d` (target must be a dir — informational only
    /// for us) and `-v` (verbose; ignored). Anything else is rejected.
    fn parse_scp_args(argv: &[String]) -> Result<ParsedScp, String> {
        if argv.is_empty() || argv[0] != "scp" {
            return Err("not an scp invocation".into());
        }
        let mut role: Option<ScpRole> = None;
        let mut recursive = false;
        let mut preserve_times = false;
        let mut target_dir = false;
        let mut positional: Vec<&str> = Vec::new();
        let mut i = 1;
        while i < argv.len() {
            let a = argv[i].as_str();
            match a {
                "-t" => role = Some(ScpRole::To),
                "-f" => role = Some(ScpRole::From),
                "-r" => recursive = true,
                "-p" => preserve_times = true,
                "-d" => target_dir = true,
                // Innocent flags scp(1) sometimes adds — accept and ignore.
                "-v" | "-q" | "-B" | "-C" | "-1" | "-2" | "-3" | "-4" | "-6" => {}
                "--" => {
                    i += 1;
                    while i < argv.len() {
                        positional.push(argv[i].as_str());
                        i += 1;
                    }
                    break;
                }
                s if s.starts_with('-') => return Err(format!("unsupported flag: {s}")),
                _ => positional.push(a),
            }
            i += 1;
        }
        let role = role.ok_or_else(|| "missing -t or -f".to_string())?;
        if positional.len() != 1 {
            return Err(format!(
                "expected exactly one path argument, got {}",
                positional.len()
            ));
        }
        let path = std::path::PathBuf::from(positional[0]);
        Ok(ParsedScp {
            role,
            recursive,
            preserve_times,
            target_dir,
            path,
        })
    }

    /// Expand the OpenSSH `%h` (home) / `%u` (user) / `%%` tokens in a path
    /// template (`ChrootDirectory`, `AuthorizedPrincipalsFile`) against the
    /// target user's passwd entry. Unknown `%X` sequences are rejected so a typo
    /// can't silently produce a surprising path.
    fn expand_pct_tokens(template: &str, info: &UserInfo) -> Result<String, String> {
        let mut out = String::with_capacity(template.len());
        let mut chars = template.chars();
        while let Some(c) = chars.next() {
            if c != '%' {
                out.push(c);
                continue;
            }
            match chars.next() {
                Some('h') => out.push_str(&info.home_str),
                Some('u') => out.push_str(&info.name),
                Some('%') => out.push('%'),
                Some(other) => {
                    return Err(format!("unknown token %{other}"));
                }
                None => return Err("trailing % in path template".to_string()),
            }
        }
        Ok(out)
    }

    /// StrictModes-style validation of a resolved `ChrootDirectory`: the
    /// directory and every parent component up to `/` must be owned by root
    /// (uid 0) and not group- or world-writable, exactly as OpenSSH requires
    /// (`safely_chroot`). Returns the resolved path on success.
    fn validate_chroot_dir(path: &str) -> Result<(), String> {
        use std::os::unix::fs::MetadataExt;
        let md =
            std::fs::metadata(path).map_err(|e| format!("stat ChrootDirectory {path}: {e}"))?;
        if !md.is_dir() {
            return Err(format!("ChrootDirectory {path}: not a directory"));
        }
        // Walk this component and every ancestor; each must be root-owned and
        // not group/world-writable. OpenSSH refuses a chroot whose path is
        // writable by anyone but root, since a writable parent lets a
        // non-root user swap the target out from under the daemon.
        let mut cur: Option<&std::path::Path> = Some(std::path::Path::new(path));
        while let Some(p) = cur {
            let md = std::fs::metadata(p).map_err(|e| format!("stat {}: {e}", p.display()))?;
            if md.uid() != 0 {
                return Err(format!(
                    "ChrootDirectory component {} must be owned by root (uid 0), is uid {}",
                    p.display(),
                    md.uid()
                ));
            }
            if md.mode() & 0o022 != 0 {
                return Err(format!(
                    "ChrootDirectory component {} is group/world-writable (mode 0o{:o})",
                    p.display(),
                    md.mode() & 0o777
                ));
            }
            cur = p.parent();
        }
        Ok(())
    }

    /// Resolve, validate, and `chroot()` into `template` for the user `info`
    /// (already looked up from the real passwd database), then `chdir("/")`
    /// inside the new root. Must run **while still root**, before any
    /// `setuid` — `chroot(2)` requires `CAP_SYS_CHROOT`. Called from
    /// `Config::on_session_open` ahead of [`drop_to_user`].
    fn apply_chroot(info: &UserInfo, template: &str, debug: bool) -> puressh::Result<()> {
        let user = info.name.as_str();
        let resolved = expand_pct_tokens(template, info).map_err(|e| {
            puressh::Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, e))
        })?;
        validate_chroot_dir(&resolved).map_err(|e| {
            puressh::Error::Io(std::io::Error::new(std::io::ErrorKind::PermissionDenied, e))
        })?;
        nix::unistd::chroot(resolved.as_str()).map_err(nix_io)?;
        nix::unistd::chdir("/").map_err(nix_io)?;
        if debug {
            eprintln!("sshd: chrooted {user} into {resolved}");
        }
        Ok(())
    }

    /// Drop the calling process to `info`'s uid/gid with the supplementary
    /// group list `gids` — both resolved by the caller from the **real**
    /// passwd/group databases *before* any `ChrootDirectory` was applied.
    /// Nothing here consults `/etc/passwd` or `/etc/group` (which, inside
    /// the jail, may be missing or attacker-writable): the ids are installed
    /// with `setgroups(2)` on the pre-resolved list, never `initgroups(3)`.
    /// Idempotent — if we already match `info`'s ids, the function is a
    /// no-op. Called from `Config::on_session_open` once per connection,
    /// after PAM session-open succeeded.
    fn drop_to_user(
        info: &UserInfo,
        gids: &[nix::unistd::Gid],
        debug: bool,
    ) -> puressh::Result<()> {
        let user = info.name.as_str();
        if already_matches(info) {
            if debug {
                eprintln!(
                    "sshd: connection already running as {user} (uid={})",
                    info.uid
                );
            }
            return Ok(());
        }
        // setgroups([]) → setgid → setgroups(list) → setuid. Clearing first
        // guarantees the post-drop process starts from an empty list even
        // if installing the resolved list somehow retained daemon groups.
        // setuid is the point of no return; we verify the result
        // afterwards to catch any silent capability/policy failure.
        setgroups_clear().map_err(nix_io)?;
        nix::unistd::setgid(info.gid).map_err(nix_io)?;
        setgroups_list(gids).map_err(nix_io)?;
        nix::unistd::setuid(info.uid).map_err(nix_io)?;
        verify_post_setuid(info.uid, info.gid).map_err(nix_io)?;
        if debug {
            eprintln!(
                "sshd: dropped connection to {user} (uid={} gid={} groups={})",
                info.uid,
                info.gid,
                gids.len()
            );
        }
        Ok(())
    }

    /// Install `gids` as the supplementary group list (`setgroups(2)`), via
    /// libc for the same portability reasons as [`setgroups_clear`].
    fn setgroups_list(gids: &[nix::unistd::Gid]) -> nix::Result<()> {
        let raw: Vec<libc::gid_t> = gids.iter().map(|g| g.as_raw()).collect();
        // SAFETY: `raw` is a live, correctly-sized array of gid_t for the
        // duration of the call; the count argument matches its length.
        let rc = unsafe { libc::setgroups(raw.len() as _, raw.as_ptr()) };
        if rc == 0 { Ok(()) } else { Err(Errno::last()) }
    }

    /// Empty the process environment in the post-fork child, before the
    /// PAM / login / channel vars are layered back on. POSIX has no portable
    /// `clearenv()`: glibc/Linux provides it, but macOS and the BSDs do not,
    /// so on those we point libc's `environ` at an empty, NUL-terminated list
    /// (a single pointer write — async-signal-safe in the fork→exec window).
    /// A subsequent `setenv()` allocates a fresh environ from there.
    ///
    /// # Safety
    /// Must run in the single-threaded post-fork child only.
    unsafe fn clear_environ() {
        unsafe {
            #[cfg(target_os = "linux")]
            {
                libc::clearenv();
            }
            #[cfg(not(target_os = "linux"))]
            {
                // A 'static, never-mutated empty environ (just the terminator).
                // Raw pointers aren't `Sync`, so wrap the array in a newtype we
                // assert `Sync` for — sound because it is read-only.
                struct EnvironList([*const libc::c_char; 1]);
                unsafe impl Sync for EnvironList {}
                static EMPTY: EnvironList = EnvironList([core::ptr::null()]);
                let empty = EMPTY.0.as_ptr() as *mut *mut libc::c_char;
                #[cfg(target_os = "macos")]
                {
                    *libc::_NSGetEnviron() = empty;
                }
                #[cfg(not(target_os = "macos"))]
                {
                    unsafe extern "C" {
                        static mut environ: *mut *mut libc::c_char;
                    }
                    core::ptr::write(core::ptr::addr_of_mut!(environ), empty);
                }
            }
        }
    }

    /// Build a `puressh::Error` from a `nix::errno::Errno` by wrapping the
    /// raw OS error as an `io::Error`. Avoids leaking nix types through the
    /// trait surface.
    fn nix_io(e: Errno) -> puressh::Error {
        puressh::Error::Io(std::io::Error::from_raw_os_error(e as i32))
    }

    /// `pipe(2)` with both ends marked close-on-exec.
    ///
    /// `pipe2(O_CLOEXEC)` would do this atomically, but nix only exposes it on
    /// Linux and the BSDs — macOS has no `pipe2` — and CI lints every target.
    /// The tiny window between `pipe` and `fcntl` only matters if another
    /// thread forks in between; every caller runs on the single-threaded
    /// accept loop (or in a test), so `pipe` + `F_SETFD` is equivalent here.
    fn pipe_cloexec() -> nix::Result<(OwnedFd, OwnedFd)> {
        let (rx, tx) = nix::unistd::pipe()?;
        for fd in [rx.as_fd(), tx.as_fd()] {
            fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC))?;
        }
        Ok((rx, tx))
    }

    /// Spawn the user's login shell — or, with `command`, `shell -c command`
    /// (non-login argv0, as OpenSSH runs `exec` requests) — on a new pty.
    #[allow(clippy::too_many_arguments)]
    fn spawn_pty_shell(
        pam: &Arc<pam_gate::PamGate>,
        user: &str,
        session_env: &[(String, String)],
        spec: &PtySpec,
        debug: bool,
        print_motd: bool,
        command: Option<&str>,
        startup: Option<StartupRc>,
    ) -> puressh::Result<Box<dyn ShellSession>> {
        // argv for `shell -c command`, built pre-fork (allocation is not
        // async-signal-safe after fork).
        let command_argv: Option<[std::ffi::CString; 3]> = match command {
            Some(cmd) => Some([
                {
                    let shell = lookup_user(user)?.shell_c;
                    let base = shell
                        .as_bytes()
                        .rsplit(|b| *b == b'/')
                        .next()
                        .unwrap_or(b"sh");
                    std::ffi::CString::new(base).map_err(|_| {
                        puressh::Error::Io(std::io::Error::other("shell name has NUL"))
                    })?
                },
                c"-c".to_owned(),
                std::ffi::CString::new(cmd).map_err(|_| {
                    puressh::Error::Io(std::io::Error::other("command contains NUL byte"))
                })?,
            ]),
            None => None,
        };
        // PrintMotd: read /etc/motd in the parent (we may already be inside the
        // ChrootDirectory and dropped to the user — the file is read from the
        // session's view of the filesystem). The bytes are written to the
        // slave pty in the child just before exec so they land on the terminal
        // ahead of the shell prompt. Default is off, so this is skipped unless
        // PrintMotd=yes — which avoids double-printing when PAM's pam_motd is
        // already configured.
        // OpenSSH's check_quietlogin: a command, or ~/.hushlogin, silences
        // the motd and the last-login line.
        let quiet = command.is_some() || {
            let home = lookup_user(user)?.home_str;
            std::path::Path::new(&home).join(".hushlogin").exists()
        };
        let motd: Option<Vec<u8>> = if print_motd && !quiet {
            read_motd_for_pty(debug)
        } else {
            None
        };
        // PrintLastLog: the previous login, read before this one is recorded.
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        let last_login: Option<Vec<u8>> = if PRINT_LAST_LOG.load(Ordering::Relaxed) && !quiet {
            sshd_login::last_login_message(lookup_user(user)?.uid.as_raw()).map(String::into_bytes)
        } else {
            None
        };
        #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
        let last_login: Option<Vec<u8>> = None;

        let ws = nix::pty::Winsize {
            ws_row: clamp_u16(spec.rows),
            ws_col: clamp_u16(spec.cols),
            ws_xpixel: clamp_u16(spec.px_w),
            ws_ypixel: clamp_u16(spec.px_h),
        };

        // Resolve the target user. Must happen pre-fork — getpwnam_r
        // allocates and isn't safe in the post-fork window.
        let info = lookup_user(user)?;
        let drop_privs = !already_matches(&info);

        // Allocate the master/slave pair *before* forking. PAM_TTY must
        // be the slave's path on disk so PAM modules (pam_loginuid,
        // pam_systemd, pam_lastlog, …) can stat it; `forkpty` doesn't
        // expose that path pre-fork, hence the manual split.
        let pty = nix::pty::openpty(Some(&ws), None).map_err(nix_io)?;
        // Both ends close-on-exec: this connection process may later spawn
        // other children (an `exec` request's command, a second shell) and
        // none of them may inherit this channel's PTY master — a sibling
        // session could otherwise read/inject on the first one's terminal.
        // The slave is `dup2`'d onto stdio in the shell child below, which
        // clears the flag on the new descriptors, so it is harmless there.
        for fd in [pty.master.as_fd(), pty.slave.as_fd()] {
            fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).map_err(nix_io)?;
        }

        // pty_setowner parity with OpenSSH: while still root and before the
        // fork hands the slave to the unprivileged shell, set the slave's
        // ownership to the authenticated user and mode to 0620 (user rw,
        // tty-group w). Without this the slave stays root-owned and, on a
        // permissively-configured devpts, another local user could snoop or
        // inject into the victim's tty. The tty group is resolved by name,
        // falling back to the user's primary gid when no "tty" group exists.
        //
        // Only meaningful when we are privileged and dropping to a different
        // user; when the daemon already runs as the target (e.g. unprivileged
        // single-user testing) the kernel already allocated the slave to that
        // uid and a self-chown would need privileges we don't have, so skip it.
        if drop_privs {
            let tty_gid = match nix::unistd::Group::from_name("tty").map_err(nix_io)? {
                Some(g) => g.gid,
                None => info.gid,
            };
            nix::unistd::fchown(pty.slave.as_fd(), Some(info.uid), Some(tty_gid))
                .map_err(nix_io)?;
            nix::sys::stat::fchmod(
                pty.slave.as_fd(),
                nix::sys::stat::Mode::from_bits_truncate(0o620),
            )
            .map_err(nix_io)?;
        }

        apply_pty_modes(pty.slave.as_raw_fd(), &spec.modes);

        let slave_path = nix::unistd::ttyname(&pty.slave)
            .map_err(nix_io)?
            .to_string_lossy()
            .into_owned();

        // Open the PAM session with the slave path as PAM_TTY. Strict:
        // failure here propagates as `puressh::Error` and the channel
        // request is rejected upstream.
        let mut pam_envs = pam.ensure(user, &slave_path)?;
        apply_login_envs(&mut pam_envs, &info);

        // Convert the per-channel SSH `env` requests into NUL-terminated
        // bytes pre-fork — CString::new allocates, and we can't allocate
        // safely between fork and execvp. Reject any pair with interior
        // NUL bytes (would smuggle past setenv's terminator otherwise);
        // such pairs cannot reach us through a well-formed SSH peer.
        //
        // Re-run the hard blocklist here as a final defense-in-depth
        // barrier — the caller already filtered via safe_session_env,
        // but the spawn_pty_shell signature accepts any
        // `&[(String,String)]` and a future caller might forget.
        let session_env = safe_owned_env(session_env);
        let mut channel_envs: Vec<(std::ffi::CString, std::ffi::CString)> =
            Vec::with_capacity(session_env.len());
        for (k, v) in &session_env {
            let kc = std::ffi::CString::new(k.as_bytes()).map_err(|_| {
                puressh::Error::Io(std::io::Error::other("channel env name contains NUL byte"))
            })?;
            let vc = std::ffi::CString::new(v.as_bytes()).map_err(|_| {
                puressh::Error::Io(std::io::Error::other("channel env value contains NUL byte"))
            })?;
            channel_envs.push((kc, vc));
        }
        // TERM from the pty request (it wins over a client `env` TERM, as
        // with OpenSSH), then the connection variables.
        let term = (!spec.term.is_empty()).then(|| ("TERM", spec.term.clone()));
        for (k, v) in term.into_iter().chain(connection_env(Some(&slave_path))) {
            if let (Ok(k), Ok(v)) = (std::ffi::CString::new(k), std::ffi::CString::new(v)) {
                channel_envs.push((k, v));
            }
        }

        // SAFETY: fork() in single-threaded code is safe; the child
        // branch performs only async-signal-safe ops (with the known
        // caveat about setenv, documented inline below) before execvp.
        let pid = unsafe { fork() }.map_err(nix_io)?;
        match pid {
            ForkResult::Child => {
                // Child does not need the master end — close it so the
                // pty drains correctly when the user's shell exits.
                drop(pty.master);
                // Become a fresh session leader, then claim the slave
                // as the controlling tty. Without TIOCSCTTY, programs
                // like `vim` and `top` won't get SIGWINCH on resize.
                let _ = nix::unistd::setsid();
                // SAFETY: TIOCSCTTY on a slave pty in a fresh session
                // is well-defined; dup2 rewires stdio onto it.
                //
                // Treat TIOCSCTTY failure as fatal: if we can't claim the
                // pty as the controlling tty, foreground job control is
                // broken (Ctrl-C / Ctrl-Z won't work, no SIGWINCH on
                // resize) and the shell would silently misbehave.  Better
                // to refuse the session than to hand the user a half-wired
                // pty. _exit(126) matches the "could not execute"
                // convention used elsewhere in this file.
                unsafe {
                    if libc::ioctl(pty.slave.as_raw_fd(), libc::TIOCSCTTY as _, 0) != 0 {
                        libc::_exit(126);
                    }
                    libc::dup2(pty.slave.as_raw_fd(), 0);
                    libc::dup2(pty.slave.as_raw_fd(), 1);
                    libc::dup2(pty.slave.as_raw_fd(), 2);
                }
                drop(pty.slave);
                // Restore default SIGCHLD so the user's shell can reap
                // its own children via waitpid(WNOHANG).
                let _ = unsafe { signal(Signal::SIGCHLD, SigHandler::SigDfl) };

                // Drop privileges to the target user before applying
                // env / chdir / exec. Order matters:
                //   setgroups([]) — clear daemon supplementary groups
                //   setgid       — set primary group (still root)
                //   initgroups   — install target's supplementary set
                //   setuid       — point of no return
                // verify_post_setuid catches a silent failure where the
                // kernel returned 0 but the ids didn't actually change
                // (e.g. seccomp filter, missing CAP_SETUID).
                if drop_privs
                    && (setgroups_clear().is_err()
                        || nix::unistd::setgid(info.gid).is_err()
                        || initgroups_libc(&info.name_c, info.gid).is_err()
                        || nix::unistd::setuid(info.uid).is_err()
                        || verify_post_setuid(info.uid, info.gid).is_err())
                {
                    // Any step failing means we can't safely
                    // continue — refuse rather than running the
                    // shell with mixed privileges.
                    unsafe { libc::_exit(126) };
                }

                // chdir(home). Best-effort: if home is unreadable
                // post-drop, fall back to / so the shell still runs.
                // SAFETY: `info.home_c` is a valid NUL-terminated
                // CString we own.
                unsafe {
                    if libc::chdir(info.home_c.as_ptr()) != 0 {
                        let _ = libc::chdir(c"/".as_ptr());
                    }
                }

                // Scrub the daemon's inherited environment before layering
                // the PAM + login + channel vars. Without this the whole
                // sshd environment (the parent's PATH, any operator-set
                // vars, etc.) leaks into the user's interactive login shell.
                // Mirrors the exec path's `cmd.env_clear()`. Runs in the
                // single-threaded post-fork child and only resets the environ
                // pointer — no allocation — so it is safe in the fork→exec
                // window.
                // SAFETY: single-threaded post-fork child; clear_environ just
                // empties the process environment.
                unsafe {
                    clear_environ();
                }

                // Apply PAM environment (now layered with HOME/USER/
                // LOGNAME/SHELL via apply_login_envs above). `setenv`
                // isn't strictly async-signal-safe per POSIX, but
                // our post-fork process is single-threaded and the
                // env list is bounded — the same approach OpenSSH
                // uses in `do_setup_env` → `child_set_env`.
                for (k, v) in &pam_envs {
                    // SAFETY: k, v are NUL-terminated `CString`s we
                    // own; the third argument 1 says "overwrite".
                    unsafe {
                        libc::setenv(k.as_ptr(), v.as_ptr(), 1);
                    }
                }
                // Layer per-channel SSH env (`env` requests) over the
                // PAM-derived env so the client's LANG / LC_* / user
                // variables win. Same async-signal-safe caveats as
                // above; the list is bounded by the channel's request
                // count and converted to CString pre-fork.
                for (k, v) in &channel_envs {
                    unsafe {
                        libc::setenv(k.as_ptr(), v.as_ptr(), 1);
                    }
                }

                // PrintMotd: write /etc/motd to the terminal (fd 1 is the
                // slave pty after the dup2 above) before handing control to the
                // shell. `write(2)` is async-signal-safe; the byte buffer was
                // read in the parent. Best-effort — a short write or error must
                // not block the login.
                // The last-login line comes first, as with OpenSSH.
                for bytes in [&last_login, &motd].into_iter().flatten() {
                    // SAFETY: fd 1 is the slave pty; `bytes` is an owned, live
                    // buffer. write() is async-signal-safe in the post-fork
                    // child. Ignore the result (best-effort motd).
                    unsafe {
                        let _ = libc::write(1, bytes.as_ptr() as *const libc::c_void, bytes.len());
                    }
                }

                // The rc files / xauth (environment and cwd are set up),
                // then SIGPIPE back to its default: Rust ignores it, and an
                // ignored signal would survive into the user's shell
                // (`yes | head` complaining of a broken pipe).
                if let Some(rc) = &startup {
                    run_startup_rc(rc);
                }
                // SAFETY: resetting a disposition; async-signal-safe.
                unsafe {
                    libc::signal(libc::SIGPIPE, libc::SIG_DFL);
                }

                // `exec` on a pty: `shell -c command`, plain argv0.
                if let Some(argv) = &command_argv {
                    let _ = execvp(&info.shell_c, argv);
                    unsafe { libc::_exit(127) };
                }
                // execvp the user's actual login shell from passwd,
                // with argv0 prefixed by "-" so bash/zsh/sh source
                // their login profile files.
                let _ = execvp(&info.shell_c, &[info.argv0_c.as_c_str()]);
                // execvp failed (binary missing, ENOEXEC, …). Use
                // _exit so we don't run stdlib atexit handlers
                // inherited from the parent.
                unsafe { libc::_exit(127) };
            }
            ForkResult::Parent { child } => {
                // Parent doesn't need the slave — close it so EOF
                // semantics work when the child exits.
                drop(pty.slave);
                let master = pty.master;
                let raw = master.as_raw_fd();
                let cur = fcntl(master.as_fd(), FcntlArg::F_GETFL).map_err(nix_io)?;
                let new = OFlag::from_bits_truncate(cur) | OFlag::O_NONBLOCK;
                fcntl(master.as_fd(), FcntlArg::F_SETFL(new)).map_err(nix_io)?;
                if debug {
                    eprintln!(
                        "sshd: spawned pty shell pid={} master_fd={} pts={} user={} shell={}",
                        child.as_raw(),
                        raw,
                        slave_path,
                        info.name,
                        info.shell_str,
                    );
                }
                // utmp / wtmp / lastlog.
                let login = record_login(child.as_raw(), &slave_path, user, info.uid.as_raw());
                Ok(Box::new(NixShellSession {
                    master: Some(master),
                    child_pid: child,
                    cached_exit: None,
                    login,
                }))
            }
        }
    }

    fn spawn_pipe_shell(
        pam: &Arc<pam_gate::PamGate>,
        user: &str,
        _session_env: &[(String, String)],
        _debug: bool,
    ) -> puressh::Result<Box<dyn ShellSession>> {
        // `ssh -T` (no PTY) lands here. Open the PAM session anyway —
        // strict mode wants to surface auth/account failures before we
        // return the user-facing "unsupported" message — then bail.
        let _ = pam.ensure(user, "ssh")?;
        Err(puressh::Error::Unsupported(
            "shell without pty-req is not yet supported by this sshd",
        ))
    }

    /// Apply a `pty-req`'s terminal modes to the new pty, as OpenSSH's
    /// tty_parse_modes does: control characters (255: disabled), flags,
    /// character size and parity, line speeds. Unknown opcodes are skipped.
    fn apply_pty_modes(fd: std::os::fd::RawFd, modes: &[u8]) {
        // SAFETY: termios is plain data, filled in by tcgetattr.
        let mut t: libc::termios = unsafe { std::mem::zeroed() };
        if unsafe { libc::tcgetattr(fd, &mut t) } != 0 {
            return;
        }
        #[cfg(target_os = "linux")]
        const VDISABLE: libc::cc_t = 0;
        #[cfg(not(target_os = "linux"))]
        const VDISABLE: libc::cc_t = 0xff;
        let cc = |v: u32| if v == 255 { VDISABLE } else { v as libc::cc_t };
        for (op, v) in puressh::server::decode_terminal_modes(modes) {
            let on = v != 0;
            let set = |field: &mut libc::tcflag_t, bit: libc::tcflag_t| {
                if on {
                    *field |= bit;
                } else {
                    *field &= !bit;
                }
            };
            match op {
                1 => t.c_cc[libc::VINTR] = cc(v),
                2 => t.c_cc[libc::VQUIT] = cc(v),
                3 => t.c_cc[libc::VERASE] = cc(v),
                4 => t.c_cc[libc::VKILL] = cc(v),
                5 => t.c_cc[libc::VEOF] = cc(v),
                6 => t.c_cc[libc::VEOL] = cc(v),
                7 => t.c_cc[libc::VEOL2] = cc(v),
                8 => t.c_cc[libc::VSTART] = cc(v),
                9 => t.c_cc[libc::VSTOP] = cc(v),
                10 => t.c_cc[libc::VSUSP] = cc(v),
                12 => t.c_cc[libc::VREPRINT] = cc(v),
                13 => t.c_cc[libc::VWERASE] = cc(v),
                14 => t.c_cc[libc::VLNEXT] = cc(v),
                18 => t.c_cc[libc::VDISCARD] = cc(v),
                30 => set(&mut t.c_iflag, libc::IGNPAR),
                31 => set(&mut t.c_iflag, libc::PARMRK),
                32 => set(&mut t.c_iflag, libc::INPCK),
                33 => set(&mut t.c_iflag, libc::ISTRIP),
                34 => set(&mut t.c_iflag, libc::INLCR),
                35 => set(&mut t.c_iflag, libc::IGNCR),
                36 => set(&mut t.c_iflag, libc::ICRNL),
                #[cfg(target_os = "linux")]
                37 => set(&mut t.c_iflag, libc::IUCLC),
                38 => set(&mut t.c_iflag, libc::IXON),
                39 => set(&mut t.c_iflag, libc::IXANY),
                40 => set(&mut t.c_iflag, libc::IXOFF),
                41 => set(&mut t.c_iflag, libc::IMAXBEL),
                42 => set(&mut t.c_iflag, libc::IUTF8),
                50 => set(&mut t.c_lflag, libc::ISIG),
                51 => set(&mut t.c_lflag, libc::ICANON),
                53 => set(&mut t.c_lflag, libc::ECHO),
                54 => set(&mut t.c_lflag, libc::ECHOE),
                55 => set(&mut t.c_lflag, libc::ECHOK),
                56 => set(&mut t.c_lflag, libc::ECHONL),
                57 => set(&mut t.c_lflag, libc::NOFLSH),
                58 => set(&mut t.c_lflag, libc::TOSTOP),
                59 => set(&mut t.c_lflag, libc::IEXTEN),
                60 => set(&mut t.c_lflag, libc::ECHOCTL),
                61 => set(&mut t.c_lflag, libc::ECHOKE),
                62 => set(&mut t.c_lflag, libc::PENDIN),
                70 => set(&mut t.c_oflag, libc::OPOST),
                #[cfg(target_os = "linux")]
                71 => set(&mut t.c_oflag, libc::OLCUC),
                72 => set(&mut t.c_oflag, libc::ONLCR),
                73 => set(&mut t.c_oflag, libc::OCRNL),
                74 => set(&mut t.c_oflag, libc::ONOCR),
                75 => set(&mut t.c_oflag, libc::ONLRET),
                90 | 91 if on => {
                    t.c_cflag &= !libc::CSIZE;
                    t.c_cflag |= if op == 90 { libc::CS7 } else { libc::CS8 };
                }
                92 => set(&mut t.c_cflag, libc::PARENB),
                93 => set(&mut t.c_cflag, libc::PARODD),
                128 | 129 => {
                    let speed = match v {
                        9600 => libc::B9600,
                        19200 => libc::B19200,
                        38400 => libc::B38400,
                        57600 => libc::B57600,
                        115200 => libc::B115200,
                        230400 => libc::B230400,
                        _ => continue,
                    };
                    // SAFETY: plain setters on the local termios.
                    unsafe {
                        if op == 128 {
                            libc::cfsetispeed(&mut t, speed);
                        } else {
                            libc::cfsetospeed(&mut t, speed);
                        }
                    }
                }
                _ => {}
            }
        }
        // SAFETY: a valid fd and a fully initialised termios.
        unsafe { libc::tcsetattr(fd, libc::TCSANOW, &t) };
    }

    fn clamp_u16(v: u32) -> u16 {
        if v > u16::MAX as u32 {
            u16::MAX
        } else {
            v as u16
        }
    }

    /// One live PTY-shell session, holding the master fd and the child's PID.
    struct NixShellSession {
        master: Option<OwnedFd>,
        child_pid: Pid,
        cached_exit: Option<ShellExitStatus>,
        /// The utmp/wtmp login, closed when the session ends.
        login: Option<LoginRecord>,
    }

    impl NixShellSession {
        /// Record the logout, once.
        fn logged_out(&mut self) {
            if let Some(l) = self.login.take() {
                record_logout(&l);
            }
        }
    }

    impl ShellSession for NixShellSession {
        fn read(&mut self, buf: &mut [u8]) -> puressh::Result<usize> {
            let Some(master) = self.master.as_ref() else {
                return Ok(0);
            };
            match nix::unistd::read(master.as_fd(), buf) {
                Ok(n) => Ok(n),
                // EAGAIN and EWOULDBLOCK alias on every platform we support,
                // so a single arm is enough — listing both triggers a
                // `unreachable_patterns` warning.
                Err(Errno::EAGAIN) => Ok(0),
                // On Linux, reading the master fd after the slave is fully
                // closed returns EIO. macOS returns 0. Both mean "no more
                // bytes ever" — surface as Ok(0); `try_exit` will pick up
                // the child's status on the next tick.
                Err(Errno::EIO) => Ok(0),
                Err(e) => Err(nix_io(e)),
            }
        }

        fn write(&mut self, data: &[u8]) -> puressh::Result<usize> {
            let Some(master) = self.master.as_ref() else {
                return Ok(0);
            };
            match nix::unistd::write(master.as_fd(), data) {
                Ok(n) => Ok(n),
                Err(Errno::EAGAIN) => Ok(0),
                Err(e) => Err(nix_io(e)),
            }
        }

        fn close_stdin(&mut self) -> puressh::Result<()> {
            // A pty has no half-close, and the client's EOF is not typed
            // into it (OpenSSH ignores it too): a ^D would reach a raw-mode
            // reader as data, and one typed ahead of the shell is lost.
            Ok(())
        }

        fn resize(&mut self, cols: u32, rows: u32, px_w: u32, px_h: u32) -> puressh::Result<()> {
            let Some(master) = self.master.as_ref() else {
                return Ok(0).map(|_| ());
            };
            let ws = libc::winsize {
                ws_row: clamp_u16(rows),
                ws_col: clamp_u16(cols),
                ws_xpixel: clamp_u16(px_w),
                ws_ypixel: clamp_u16(px_h),
            };
            // SAFETY: TIOCSWINSZ takes `*const struct winsize`; we pass a
            // pointer to a local. `ioctl` is variadic in libc; the cast on
            // the request constant covers platform-specific types
            // (`c_ulong` on Linux, `u_long` on BSD).
            let rc = unsafe {
                libc::ioctl(
                    master.as_raw_fd(),
                    libc::TIOCSWINSZ as _,
                    &ws as *const libc::winsize,
                )
            };
            if rc == -1 {
                return Err(puressh::Error::Io(std::io::Error::last_os_error()));
            }
            Ok(())
        }

        fn try_exit(&mut self) -> Option<ShellExitStatus> {
            if let Some(s) = self.cached_exit.clone() {
                return Some(s);
            }
            let status = self.wait_child();
            if status.is_some() {
                self.logged_out();
            }
            status
        }
    }

    impl NixShellSession {
        fn wait_child(&mut self) -> Option<ShellExitStatus> {
            match waitpid(self.child_pid, Some(WaitPidFlag::WNOHANG)) {
                Ok(WaitStatus::Exited(_, code)) => {
                    let code_u32 = if code < 0 { 255u32 } else { code as u32 };
                    let s = ShellExitStatus::Exited(code_u32);
                    self.cached_exit = Some(s.clone());
                    Some(s)
                }
                Ok(WaitStatus::Signaled(_, sig, core)) => {
                    let name = strip_sig_prefix(&format!("{sig:?}"));
                    let s = ShellExitStatus::Signalled {
                        name,
                        core_dumped: core,
                        message: String::new(),
                    };
                    self.cached_exit = Some(s.clone());
                    Some(s)
                }
                // StillAlive / Stopped / Continued: keep waiting.
                Ok(_) => None,
                // ECHILD: child already reaped (e.g. by SIG_IGN before we
                // overrode it). Treat as clean exit so the channel closes.
                Err(Errno::ECHILD) => {
                    let s = ShellExitStatus::Exited(0);
                    self.cached_exit = Some(s.clone());
                    Some(s)
                }
                Err(_) => None,
            }
        }
    }

    impl Drop for NixShellSession {
        fn drop(&mut self) {
            self.logged_out();
            // Best-effort: HUP the child, give it a tick to die, then reap.
            if self.cached_exit.is_none() {
                let _ = kill(self.child_pid, Signal::SIGHUP);
                let _ = waitpid(self.child_pid, Some(WaitPidFlag::WNOHANG));
            }
            // master OwnedFd auto-closes on drop.
        }
    }

    fn strip_sig_prefix(s: &str) -> String {
        s.strip_prefix("SIG").unwrap_or(s).to_string()
    }

    // -------------------------------------------------------------------------
    // Accept loop with fork() per connection.
    // -------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // Parent-side state for connection caps and graceful shutdown.
    //
    // The signal handlers touch ONLY the two atomics below (async-signal-
    // safe). Everything else — the child table with its per-IP counts and
    // auth-notification pipes — is owned by the accept loop and reconciled
    // there (`ChildTable::reap` / `ChildTable::poll_auth`), never from signal
    // context.
    // -------------------------------------------------------------------------

    /// Set by the SIGCHLD handler; the accept loop reaps on its next pass. The
    /// handler installs without `SA_RESTART`, so a child exit also wakes a
    /// `poll()` that is waiting for connections.
    static SIGCHLD_PENDING: AtomicBool = AtomicBool::new(false);

    /// Set to `true` by the SIGTERM/SIGINT handler. The accept loop polls
    /// it before each `accept()` and exits cleanly when it flips, letting
    /// in-flight children drain on their own without orphaning them.
    static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);

    /// SIGCHLD handler: just raise the flag. Reaping (`waitpid`) and the
    /// bookkeeping it drives happen in the accept loop, where a `Mutex` /
    /// `HashMap` may be touched.
    ///
    /// SAFETY: signal-context safe — a single relaxed atomic store.
    extern "C" fn sigchld_handler(_sig: libc::c_int) {
        SIGCHLD_PENDING.store(true, Ordering::Relaxed);
    }

    /// SIGTERM / SIGINT handler: flip the shutdown flag so the accept
    /// loop exits at the next iteration. We deliberately do *not* try to
    /// signal in-flight children — they each carry their own client
    /// socket and the natural EOF on shutdown will tear them down.
    ///
    /// SAFETY: signal-context safe — just a single relaxed atomic store.
    extern "C" fn shutdown_handler(_sig: libc::c_int) {
        SHUTDOWN_REQUESTED.store(true, Ordering::Relaxed);
    }

    /// `PrintLastLog` (global only, as in OpenSSH).
    static PRINT_LAST_LOG: AtomicBool = AtomicBool::new(true);

    /// Set by SIGHUP: re-read the configuration (by re-executing).
    static RELOAD_REQUESTED: AtomicBool = AtomicBool::new(false);

    /// SIGHUP handler. SAFETY: signal-context safe — one atomic store.
    extern "C" fn reload_handler(_sig: libc::c_int) {
        RELOAD_REQUESTED.store(true, Ordering::Relaxed);
    }

    /// SIGHUP: like OpenSSH, re-execute this binary with the original
    /// arguments, so the new process reads the configuration (and host keys)
    /// afresh. Live sessions are separate processes and are unaffected. The
    /// new configuration is checked first: if it does not load, the daemon
    /// keeps running with the old one rather than exiting. Returns only on
    /// failure.
    fn reload(cli: &Cli, args: &[String]) {
        if let Err(e) = load_effective_config(cli) {
            eprintln!("sshd: SIGHUP: new configuration rejected, keeping the old one: {e}");
            return;
        }
        // argv[0] when absolute (systemd starts us by absolute path, and it
        // still names the *new* binary after a package upgrade), else
        // /proc/self/exe.
        let exe = std::env::args_os()
            .next()
            .map(std::path::PathBuf::from)
            .filter(|p| p.is_absolute())
            .or_else(|| std::env::current_exe().ok());
        let Some(exe) = exe else {
            eprintln!("sshd: SIGHUP: cannot find our own executable; not reloading");
            return;
        };
        eprintln!("sshd: SIGHUP: re-executing {}", exe.display());
        // Listening sockets are close-on-exec; the new process binds afresh.
        // A detached daemon stays this process (same PID, PidFile right).
        let mut args = args.to_vec();
        if !cli.no_detach {
            args.push("-D".into());
        }
        let err = Command::new(&exe).args(&args).exec();
        eprintln!("sshd: SIGHUP: exec {}: {err}", exe.display());
    }

    /// Become a background daemon (see the caller).
    fn detach(keep_stderr: bool) -> Result<(), String> {
        // SAFETY: the daemon parent has no other threads at this point.
        match unsafe { nix::unistd::fork() } {
            Ok(ForkResult::Parent { .. }) => std::process::exit(0),
            Ok(ForkResult::Child) => {}
            Err(e) => return Err(format!("fork: {e}")),
        }
        nix::unistd::setsid().map_err(|e| format!("setsid: {e}"))?;
        let _ = std::env::set_current_dir("/");
        let null = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open("/dev/null")
            .map_err(|e| format!("/dev/null: {e}"))?;
        let _ = nix::unistd::dup2_stdin(&null);
        let _ = nix::unistd::dup2_stdout(&null);
        if !keep_stderr {
            let _ = nix::unistd::dup2_stderr(&null);
        }
        Ok(())
    }

    /// Install SIGCHLD (wake the accept loop to reap) and SIGTERM/SIGINT
    /// (graceful shutdown).
    fn install_parent_signals() -> Result<(), String> {
        // SAFETY: `sigaction` with caller-owned `sigaction` structs is
        // POSIX-defined; the handler funcs we install reference only
        // statics + async-signal-safe APIs.
        unsafe {
            let mut sa: libc::sigaction = core::mem::zeroed();
            sa.sa_sigaction = sigchld_handler as *const () as usize;
            // SA_NOCLDSTOP: don't notify on stopped/continued children.
            // No SA_RESTART: a child exit must interrupt the accept loop's
            // `poll()` so the exit is reaped promptly (the loop treats
            // EINTR as "go around again").
            sa.sa_flags = libc::SA_NOCLDSTOP;
            libc::sigemptyset(&mut sa.sa_mask);
            if libc::sigaction(libc::SIGCHLD, &sa, core::ptr::null_mut()) != 0 {
                return Err(format!(
                    "sigaction(SIGCHLD): {}",
                    std::io::Error::last_os_error()
                ));
            }
            let mut sa: libc::sigaction = core::mem::zeroed();
            sa.sa_sigaction = shutdown_handler as *const () as usize;
            // Deliberately no SA_RESTART: we *want* SIGTERM/SIGINT to
            // wake the blocked poll() so the loop can observe the flag.
            sa.sa_flags = 0;
            libc::sigemptyset(&mut sa.sa_mask);
            if libc::sigaction(libc::SIGTERM, &sa, core::ptr::null_mut()) != 0 {
                return Err(format!(
                    "sigaction(SIGTERM): {}",
                    std::io::Error::last_os_error()
                ));
            }
            if libc::sigaction(libc::SIGINT, &sa, core::ptr::null_mut()) != 0 {
                return Err(format!(
                    "sigaction(SIGINT): {}",
                    std::io::Error::last_os_error()
                ));
            }
            let mut sa: libc::sigaction = core::mem::zeroed();
            sa.sa_sigaction = reload_handler as *const () as usize;
            sa.sa_flags = 0;
            libc::sigemptyset(&mut sa.sa_mask);
            if libc::sigaction(libc::SIGHUP, &sa, core::ptr::null_mut()) != 0 {
                return Err(format!(
                    "sigaction(SIGHUP): {}",
                    std::io::Error::last_os_error()
                ));
            }
        }
        Ok(())
    }

    /// The byte a connection child writes to its auth-notification pipe once
    /// userauth has succeeded.
    const AUTH_OK_BYTE: u8 = b'A';

    /// Write end of *this* connection child's auth-notification pipe, as a raw
    /// fd (`-1` = none). The parent stores it just before `fork()` and clears
    /// it right after; fork's copy-on-write leaves the child with its own
    /// value, which the session-open hook consumes via
    /// [`notify_parent_authenticated`].
    static AUTH_NOTIFY_FD: AtomicI32 = AtomicI32::new(-1);

    /// Tell the daemon parent that this connection has authenticated, so it
    /// stops counting against `MaxStartups`: write one byte and close the
    /// pipe. Idempotent; a no-op when no pipe was set up (tests, or a
    /// pipe() failure at accept time).
    fn notify_parent_authenticated() {
        AUTHENTICATED.store(true, Ordering::Relaxed);
        tell_parent(&[AUTH_OK_BYTE, b'\n']);
    }

    /// This connection process authenticated its client.
    static AUTHENTICATED: AtomicBool = AtomicBool::new(false);

    /// Send one message line to the daemon parent over this connection's
    /// pipe, which stays open for the connection's life: `A` (authenticated),
    /// `L pid tty user uid` / `O pid tty` (a pty login / logout to record —
    /// the parent is root and the connection no longer is). False when there
    /// is no pipe (tests, a pipe() failure at accept time).
    fn tell_parent(line: &[u8]) -> bool {
        let fd = AUTH_NOTIFY_FD.load(Ordering::Relaxed);
        if fd < 0 {
            return false;
        }
        // SAFETY: the fd was created by `pipe_cloexec` in the parent and its
        // ownership handed to this static at fork; nothing closes it.
        let tx = unsafe { BorrowedFd::borrow_raw(fd) };
        nix::unistd::write(tx, line).is_ok_and(|n| n == line.len())
    }

    /// A pty login being recorded: by the daemon parent (normally), or
    /// directly when there is no parent to ask.
    enum LoginRecord {
        Parent {
            pid: i32,
            tty: String,
        },
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        Local(sshd_login::Session),
    }

    /// Record a pty login (utmp, wtmp, lastlog) of `user` on `tty`.
    fn record_login(pid: i32, tty: &str, user: &str, uid: u32) -> Option<LoginRecord> {
        let msg = format!("L\t{pid}\t{tty}\t{user}\t{uid}\n");
        if tell_parent(msg.as_bytes()) {
            return Some(LoginRecord::Parent {
                pid,
                tty: tty.to_string(),
            });
        }
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        {
            let peer = conn_addrs().map(|(p, _)| p.ip());
            let host = peer.map(sshd_log::addr_str).unwrap_or_default();
            Some(LoginRecord::Local(sshd_login::login(
                pid, tty, user, uid, &host, peer,
            )))
        }
        #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
        None
    }

    fn record_logout(rec: &LoginRecord) {
        match rec {
            LoginRecord::Parent { pid, tty } => {
                tell_parent(format!("O\t{pid}\t{tty}\n").as_bytes());
            }
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            LoginRecord::Local(s) => sshd_login::logout(s),
        }
    }

    /// One forked connection child, as tracked by the daemon parent.
    struct ChildRecord {
        /// Peer IP, for `--per-source-max`. Counted for the child's whole
        /// lifetime.
        ip: IpAddr,
        /// Read end of the auth-notification pipe, held while the child has
        /// not yet reported success. `None` once it has (or once it closed
        /// the pipe without doing so, e.g. exited pre-auth).
        auth_rx: Option<OwnedFd>,
        /// True once the child reported userauth success; such children no
        /// longer count against `MaxStartups`.
        authenticated: bool,
        /// Unprocessed bytes from the pipe (messages are lines).
        buf: Vec<u8>,
        /// Pty logins recorded for this child, closed when it says so or
        /// when it is reaped.
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        logins: Vec<sshd_login::Session>,
    }

    impl ChildRecord {
        /// Handle one message line from the child (see `tell_parent`).
        fn message(&mut self, line: &[u8]) {
            if line == [AUTH_OK_BYTE] {
                self.authenticated = true;
            } else {
                #[cfg(all(target_os = "linux", target_env = "gnu"))]
                self.login_message(line);
            }
        }

        /// `L …` / `O …`: record a pty login or logout.
        #[cfg(all(target_os = "linux", target_env = "gnu"))]
        fn login_message(&mut self, line: &[u8]) {
            {
                let Ok(line) = std::str::from_utf8(line) else {
                    return;
                };
                let f: Vec<&str> = line.split('\t').collect();
                match f.as_slice() {
                    ["L", pid, tty, user, uid] if self.authenticated && self.logins.len() < 64 => {
                        let (Ok(pid), Ok(uid)) = (pid.parse::<i32>(), uid.parse::<u32>()) else {
                            return;
                        };
                        if !login_claim_ok(tty, user, uid) {
                            return;
                        }
                        // The peer as this parent knows it, not as claimed.
                        let host = sshd_log::addr_str(self.ip);
                        self.logins.push(sshd_login::login(
                            pid,
                            tty,
                            user,
                            uid,
                            &host,
                            Some(self.ip),
                        ));
                    }
                    ["O", pid, tty] => {
                        let Ok(pid) = pid.parse::<i32>() else {
                            return;
                        };
                        if let Some(i) = self.logins.iter().position(|l| l.is(pid, tty)) {
                            sshd_login::logout(&self.logins.remove(i));
                        }
                    }
                    _ => {}
                }
            }
        }

        /// Close every login still open (the connection is gone).
        fn close_logins(&mut self) {
            #[cfg(all(target_os = "linux", target_env = "gnu"))]
            for l in self.logins.drain(..) {
                sshd_login::logout(&l);
            }
        }
    }

    /// A child's login claim holds: `tty` is a pty owned by `uid`, which is
    /// `user`'s. (The child runs as that user: it can only own its ptys.)
    #[cfg(all(target_os = "linux", target_env = "gnu"))]
    fn login_claim_ok(tty: &str, user: &str, uid: u32) -> bool {
        use std::os::unix::fs::MetadataExt;
        let Some(n) = tty.strip_prefix("/dev/pts/") else {
            return false;
        };
        !n.is_empty()
            && n.bytes().all(|b| b.is_ascii_digit())
            && std::fs::metadata(tty).is_ok_and(|m| m.uid() == uid)
            && lookup_user(user).is_ok_and(|i| i.uid.as_raw() == uid)
    }

    /// Why a connection that never authenticated is penalised
    /// (`PerSourcePenalties`), from how its process ended.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    enum PenaltyKind {
        Crash,
        AuthFail,
        InvalidUser,
        NoAuth,
        GraceExceeded,
    }

    /// Exit codes a connection process ends with before authenticating,
    /// telling the daemon what to penalise its source for (OpenSSH's).
    const EXIT_LOGIN_GRACE: i32 = 3;
    const EXIT_AUTH_ATTEMPTED: i32 = 5;
    const EXIT_INVALID_USER: i32 = 7;

    /// This connection attempted authentication (not just `none`).
    static AUTH_ATTEMPTED: AtomicBool = AtomicBool::new(false);
    /// This connection asked for an account that does not exist.
    static INVALID_USER: AtomicBool = AtomicBool::new(false);

    /// The exit code of a connection process that ends before
    /// authenticating: what its source is penalised for.
    fn preauth_exit_code(timed_out: bool) -> i32 {
        if timed_out {
            EXIT_LOGIN_GRACE
        } else if AUTH_ATTEMPTED.load(Ordering::Relaxed) {
            EXIT_AUTH_ATTEMPTED
        } else if INVALID_USER.load(Ordering::Relaxed) {
            EXIT_INVALID_USER
        } else {
            255
        }
    }

    /// The penalty for a connection process that ended so (OpenSSH's
    /// child_reap): none once it authenticated.
    fn penalty_for(status: &WaitStatus, authenticated: bool) -> Option<PenaltyKind> {
        if authenticated {
            return None;
        }
        match *status {
            WaitStatus::Signaled(_, sig, _) => matches!(
                sig,
                Signal::SIGSEGV
                    | Signal::SIGBUS
                    | Signal::SIGILL
                    | Signal::SIGFPE
                    | Signal::SIGABRT
                    | Signal::SIGSYS
                    | Signal::SIGTRAP
            )
            .then_some(PenaltyKind::Crash),
            WaitStatus::Exited(_, 0) => None,
            WaitStatus::Exited(_, EXIT_LOGIN_GRACE) => Some(PenaltyKind::GraceExceeded),
            WaitStatus::Exited(_, EXIT_AUTH_ATTEMPTED) => Some(PenaltyKind::AuthFail),
            WaitStatus::Exited(_, EXIT_INVALID_USER) => Some(PenaltyKind::InvalidUser),
            WaitStatus::Exited(..) => Some(PenaltyKind::NoAuth),
            _ => None,
        }
    }

    /// `PerSourcePenalties`: the daemon's table of penalised source net
    /// blocks, as OpenSSH's (srclimit.c).
    struct Penalties {
        cfg: puressh::config::PerSourcePenalties,
        exempt: Vec<puressh::config::AddressPattern>,
        bits: (u8, u8),
        /// Masked source → (expiry, active, reason).
        table: HashMap<IpAddr, (Instant, bool, &'static str)>,
    }

    impl Penalties {
        fn new(opts: &puressh::config::ServerOptions) -> Self {
            Penalties {
                cfg: opts.per_source_penalties.clone().unwrap_or_default(),
                exempt: opts
                    .per_source_penalty_exempt
                    .as_deref()
                    .map(|l| {
                        l.split(',')
                            .filter(|t| !t.is_empty())
                            .map(puressh::config::AddressPattern::parse)
                            .collect()
                    })
                    .unwrap_or_default(),
                bits: opts.per_source_net_block_size.unwrap_or((32, 128)),
                table: HashMap::new(),
            }
        }

        fn mask(&self, ip: IpAddr) -> IpAddr {
            match ip {
                IpAddr::V4(a) => {
                    let bits = u32::from(self.bits.0.min(32));
                    let m = u32::MAX.checked_shl(32 - bits).unwrap_or(0);
                    IpAddr::V4((u32::from(a) & m).into())
                }
                IpAddr::V6(a) => {
                    let bits = u32::from(self.bits.1.min(128));
                    let m = u128::MAX.checked_shl(128 - bits).unwrap_or(0);
                    IpAddr::V6((u128::from(a) & m).into())
                }
            }
        }

        fn exempt(&self, ip: IpAddr) -> bool {
            puressh::config::address_matches(&self.exempt, &ip.to_string())
        }

        fn expire(&mut self, now: Instant) {
            self.table.retain(|_, (expiry, _, _)| *expiry > now);
        }

        fn count(&self, v4: bool) -> usize {
            self.table.keys().filter(|k| k.is_ipv4() == v4).count()
        }

        /// `Some(reason)` when connections from `ip` are refused.
        fn refuses(&mut self, ip: IpAddr) -> Option<&'static str> {
            if !self.cfg.enabled || self.exempt(ip) {
                return None;
            }
            self.expire(Instant::now());
            let (full, deny_all) = if ip.is_ipv4() {
                (
                    self.count(true) >= self.cfg.max_sources4 as usize,
                    self.cfg.overflow_deny_all,
                )
            } else {
                (
                    self.count(false) >= self.cfg.max_sources6 as usize,
                    self.cfg.overflow6_deny_all,
                )
            };
            if full && deny_all {
                return Some("too many penalised addresses");
            }
            match self.table.get(&self.mask(ip)) {
                Some((_, true, reason)) => Some(reason),
                _ => None,
            }
        }

        /// Penalise `ip`'s net block for `kind`: a new penalty, or added to
        /// the one it has (up to `max`), refusing once past `min`.
        fn penalise(&mut self, ip: IpAddr, kind: PenaltyKind, debug: bool) {
            if !self.cfg.enabled || self.exempt(ip) {
                return;
            }
            let (secs, reason) = match kind {
                PenaltyKind::Crash => (self.cfg.crash, "penalty: caused crash"),
                PenaltyKind::AuthFail => (self.cfg.authfail, "penalty: failed authentication"),
                PenaltyKind::InvalidUser => (
                    self.cfg.invalid_user,
                    "penalty: attempted authentication by invalid user",
                ),
                PenaltyKind::NoAuth => (
                    self.cfg.noauth,
                    "penalty: connections without attempting authentication",
                ),
                PenaltyKind::GraceExceeded => {
                    (self.cfg.grace_exceeded, "penalty: exceeded LoginGraceTime")
                }
            };
            if secs == 0 {
                return;
            }
            let now = Instant::now();
            self.expire(now);
            let key = self.mask(ip);
            let (max_sources, deny_all) = if key.is_ipv4() {
                (self.cfg.max_sources4, self.cfg.overflow_deny_all)
            } else {
                (self.cfg.max_sources6, self.cfg.overflow6_deny_all)
            };
            let add = Duration::from_secs(u64::from(secs));
            let cap = now + Duration::from_secs(u64::from(self.cfg.max));
            let min = Duration::from_secs(u64::from(self.cfg.min));
            match self.table.get_mut(&key) {
                Some((expiry, active, why)) => {
                    *expiry = (*expiry + add).min(cap);
                    *active |= expiry.saturating_duration_since(now) > min;
                    *why = reason;
                }
                None => {
                    if self.count(key.is_ipv4()) >= max_sources as usize {
                        if deny_all {
                            return;
                        }
                        // Permissive: forget the penalty closest to expiry.
                        if let Some(k) = self
                            .table
                            .iter()
                            .filter(|(k, _)| k.is_ipv4() == key.is_ipv4())
                            .min_by_key(|(_, v)| v.0)
                            .map(|(k, _)| *k)
                        {
                            self.table.remove(&k);
                        }
                    }
                    self.table
                        .insert(key, ((now + add).min(cap), add > min, reason));
                }
            }
            if debug {
                eprintln!("sshd: {key}: {reason} ({secs}s)");
            }
        }
    }

    /// The daemon parent's table of live connection children, keyed by pid.
    /// Owned by the accept loop; never touched from signal context.
    #[derive(Default)]
    struct ChildTable {
        children: HashMap<Pid, ChildRecord>,
    }

    impl ChildTable {
        fn len(&self) -> usize {
            self.children.len()
        }

        /// Children that have not yet reported authentication success.
        fn unauthenticated(&self) -> usize {
            self.children.values().filter(|c| !c.authenticated).count()
        }

        /// Live children (any auth state) from `ip`.
        fn count_from_ip(&self, ip: IpAddr) -> usize {
            self.children.values().filter(|c| c.ip == ip).count()
        }

        /// Record a freshly forked child.
        fn insert(&mut self, pid: Pid, ip: IpAddr, auth_rx: Option<OwnedFd>) {
            self.children.insert(
                pid,
                ChildRecord {
                    ip,
                    auth_rx,
                    authenticated: false,
                    buf: Vec::new(),
                    #[cfg(all(target_os = "linux", target_env = "gnu"))]
                    logins: Vec::new(),
                },
            );
        }

        /// Reap every exited child (`waitpid(WNOHANG)` loop) and drop its
        /// record — releasing its per-IP slot and closing its pipe.
        fn reap(&mut self, debug: bool, penalties: &mut Penalties) {
            // A child that authenticated just before it exited must not be
            // taken for one that never did.
            self.poll_auth();
            loop {
                match waitpid(None, Some(WaitPidFlag::WNOHANG)) {
                    Ok(WaitStatus::StillAlive) | Err(_) => break,
                    Ok(status) => {
                        if let Some(pid) = status.pid()
                            && let Some(mut rec) = self.children.remove(&pid)
                        {
                            rec.close_logins();
                            // PerSourcePenalties: how a connection that never
                            // authenticated ended, as OpenSSH's child_reap.
                            if let Some(kind) = penalty_for(&status, rec.authenticated) {
                                penalties.penalise(rec.ip, kind, debug);
                            }
                        } else {
                            continue;
                        }
                        if let Some(pid) = status.pid()
                            && debug
                        {
                            eprintln!(
                                "sshd: reaped connection pid {} (live={}, unauth={})",
                                pid.as_raw(),
                                self.len(),
                                self.unauthenticated()
                            );
                        }
                    }
                }
            }
        }

        /// Collect auth-success notifications: a non-blocking `poll()` over
        /// every unauthenticated child's pipe. A child that wrote
        /// [`AUTH_OK_BYTE`] moves to the authenticated column; a pipe that
        /// closed without it (child exited pre-auth) is just released — the
        /// record itself goes when the child is reaped.
        fn poll_auth(&mut self) {
            let pids: Vec<Pid> = self
                .children
                .iter()
                .filter(|(_, c)| c.auth_rx.is_some())
                .map(|(pid, _)| *pid)
                .collect();
            if pids.is_empty() {
                return;
            }
            let mut fds: Vec<PollFd<'_>> = pids
                .iter()
                .map(|pid| {
                    let rx = self.children[pid].auth_rx.as_ref().expect("filtered above");
                    PollFd::new(rx.as_fd(), PollFlags::POLLIN)
                })
                .collect();
            match poll(&mut fds, PollTimeout::ZERO) {
                Ok(n) if n > 0 => {}
                _ => return,
            }
            let ready: Vec<Pid> = pids
                .iter()
                .zip(fds.iter())
                .filter(|(_, f)| f.any().unwrap_or(false))
                .map(|(pid, _)| *pid)
                .collect();
            drop(fds);
            for pid in ready {
                let Some(rec) = self.children.get_mut(&pid) else {
                    continue;
                };
                let Some(rx) = rec.auth_rx.as_ref() else {
                    continue;
                };
                let mut chunk = [0u8; 4096];
                match nix::unistd::read(rx, &mut chunk) {
                    Ok(n) if n > 0 => rec.buf.extend_from_slice(&chunk[..n]),
                    Err(Errno::EINTR | Errno::EAGAIN) => continue,
                    // EOF (the child exited) or an error: the pipe is done.
                    _ => {
                        rec.auth_rx = None;
                    }
                }
                while let Some(i) = rec.buf.iter().position(|b| *b == b'\n') {
                    let line: Vec<u8> = rec.buf.drain(..=i).collect();
                    rec.message(&line[..line.len() - 1]);
                }
                // A child that will not end its lines gets no more hearing.
                if rec.buf.len() > 4096 {
                    rec.buf.clear();
                    rec.auth_rx = None;
                }
            }
        }

        /// Every open child pipe, for the accept loop's poll set.
        fn pipe_fds(&self) -> Vec<BorrowedFd<'_>> {
            self.children
                .values()
                .filter_map(|c| c.auth_rx.as_ref().map(|fd| fd.as_fd()))
                .collect()
        }

        /// Apply the two connection caps: `MaxStartups` over the
        /// *unauthenticated* children only (an authenticated peer cannot
        /// exhaust it, and a flood of idle pre-auth connections cannot block
        /// logins beyond its own budget), and `--per-source-max` over every
        /// live child from the peer's IP. `Err(reason)` ⇒ refuse (the caller
        /// logs and closes the socket).
        fn admit(
            &self,
            peer: &std::net::SocketAddr,
            max_startups: u32,
            early: Option<(u32, u32)>,
            per_source_max: u32,
        ) -> Result<(), &'static str> {
            let unauth = self.unauthenticated();
            if max_startups > 0 && unauth >= max_startups as usize {
                return Err("max-startups");
            }
            // `MaxStartups start:rate:full`: random early drop, `rate`% at
            // `start` rising linearly to 100% at `full` (OpenSSH's formula).
            if let Some((start, rate)) = early
                && max_startups > 0
                && unauth >= start as usize
            {
                let (start, full, unauth) = (start as u64, max_startups as u64, unauth as u64);
                let p = if full > start {
                    (100 - rate as u64) * (unauth - start) / (full - start) + rate as u64
                } else {
                    100
                };
                use purecrypto::rng::{OsRng, RngCore};
                if (OsRng.next_u32() % 100) < p as u32 {
                    return Err("max-startups (early drop)");
                }
            }
            if per_source_max > 0 && self.count_from_ip(peer.ip()) >= per_source_max as usize {
                return Err("per-source-max");
            }
            Ok(())
        }
    }

    fn run() -> Result<i32, String> {
        let args: Vec<String> = std::env::args().skip(1).collect();
        if args.iter().any(|a| a == "-?" || a == "--help") {
            println!("{USAGE}");
            println!();
            println!("A pure-Rust SSH server daemon built on puressh {VERSION}.");
            return Ok(0);
        }
        if args.iter().any(|a| a == "-V" || a == "--version") {
            println!("puressh sshd {VERSION}");
            return Ok(0);
        }

        let cli = parse_args(&args).map_err(|e| format!("{e}\n{USAGE}"))?;

        // `-E file`: append diagnostics to `file` from here on.
        if let Some(path) = cli.log_file.as_deref() {
            let f = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)
                .map_err(|e| format!("-E {path}: {e}"))?;
            nix::unistd::dup2_stderr(&f).map_err(|e| format!("-E {path}: {e}"))?;
        }

        // sshd_config: `-o` options, then `-f` (default /etc/ssh/sshd_config
        // when present), with OpenSSH's defaults for anything left unset.
        // CLI flags always win over the config file.
        let mut sshd_cfg = load_effective_config(&cli)?;
        apply_openssh_defaults(&mut sshd_cfg.global);
        let _ = XAUTH_LOCATION.set(match sshd_cfg.global.xauth_location.as_deref() {
            Some(p) if p.eq_ignore_ascii_case("none") => None,
            Some(p) => Some(p.to_string()),
            None => Some("/usr/bin/xauth".to_string()),
        });
        // `PubkeyAcceptedAlgorithms +ssh-rsa` (global or in a Match block):
        // accept old clients' SHA-1 RSA signatures, as OpenSSH then does.
        let names_ssh_rsa = |o: &puressh::config::ServerOptions| {
            o.pubkey_accepted_algorithms.as_ref().is_some_and(|l| {
                l.iter()
                    .any(|a| a == "ssh-rsa" || a == "ssh-rsa-cert-v01@openssh.com")
            })
        };
        let host_key_ssh_rsa = sshd_cfg
            .global
            .host_key_algorithms
            .as_ref()
            .is_some_and(|l| {
                l.iter()
                    .any(|a| a == "ssh-rsa" || a == "ssh-rsa-cert-v01@openssh.com")
            });
        if host_key_ssh_rsa
            || names_ssh_rsa(&sshd_cfg.global)
            || sshd_cfg.match_blocks.iter().any(|b| names_ssh_rsa(&b.opts))
        {
            puressh::hostkey::set_allow_rsa_sha1(true);
        }
        let sshd_cfg = Arc::new(sshd_cfg);
        // OpenSSH keywords we accept but do not implement, ignored arguments.
        for w in sshd_cfg.warnings() {
            eprintln!("sshd: warning: config {w}");
        }
        if cli.dump_config {
            return dump_config(&cli, &sshd_cfg);
        }

        // LogLevel (sshd_config): VERBOSE/DEBUG* (level >= 1) turns on the same
        // verbose diagnostics as `-d`, so the config keyword actually controls
        // output. `-d` always wins (it can't be turned back off). Rebind `cli`
        // so every downstream `cli.debug` reflects the effective level.
        let log_level = sshd_cfg.global.log_level.unwrap_or(3);
        // OpenSSH's logging: syslog (SyslogFacility) at LogLevel, or stderr
        // with -d / -e / -E; -d raises the level to DEBUG1, -q silences it.
        {
            let configured = puressh::config::server::LOG_LEVELS[usize::from(log_level.min(7))];
            let mut level = sshd_log::Level::parse(configured).unwrap_or(sshd_log::Level::Info);
            if cli.debug {
                level = level.max(sshd_log::Level::Debug1);
            }
            if cli.quiet {
                level = sshd_log::Level::Quiet;
            }
            let facility = sshd_cfg
                .global
                .syslog_facility
                .as_deref()
                .and_then(sshd_log::facility)
                .unwrap_or(libc::LOG_AUTH);
            let to_stderr = cli.debug || cli.log_stderr || cli.log_file.is_some() || cli.test_only;
            sshd_log::init(level, facility, to_stderr);
            PRINT_LAST_LOG.store(
                sshd_cfg.global.print_last_log.unwrap_or(true),
                Ordering::Relaxed,
            );
            sshd_log::set_max_auth_tries(
                sshd_cfg
                    .global
                    .max_auth_tries
                    .unwrap_or(puressh::server::DEFAULT_MAX_AUTH_TRIES),
            );
        }
        // `-d` itself (not LogLevel DEBUG) keeps the daemon in the foreground.
        let debug_flag = cli.debug;
        let cli = {
            let mut c = cli;
            c.debug = c.debug || log_level >= 5;
            c
        };

        // Resolve effective values: CLI > config > built-in default.
        // Ports: `-p` (repeatable), else every `Port` line, else 22.
        let ports: Vec<u16> = if !cli.ports.is_empty() {
            cli.ports.clone()
        } else if !sshd_cfg.global.ports.is_empty() {
            sshd_cfg.global.ports.clone()
        } else {
            vec![22]
        };
        // The first one names the daemon in diagnostics and is the knock's
        // default UDP port.
        let port = ports[0];
        let strict_modes = pick(cli.strict_modes, sshd_cfg.global.strict_modes, true);
        // SFTP is on when either the puressh `SftpEnabled` knob OR the standard
        // `Subsystem sftp internal-sftp` line enables it (CLI still wins).
        let sftp_enabled = pick(
            cli.sftp,
            sshd_cfg
                .global
                .sftp_enabled
                .or(sshd_cfg.global.subsystem_sftp),
            true,
        );
        let sftp_read_only = pick(cli.sftp_read_only, sshd_cfg.global.sftp_read_only, false);
        // SFTP virtual-root precedence: CLI `--sftp-root` > puressh `SftpRoot`.
        // This is an in-process path jail that needs no privilege. The standard
        // `ChrootDirectory` is no longer mapped here: it now drives a *real*
        // `chroot()` in `on_session_open` (see `apply_chroot`), which confines
        // shell / exec / SFTP uniformly — the in-process SFTP subsystem runs
        // after that hook, so it already operates inside the new root. (A real
        // chroot requires root, exactly as OpenSSH's `ChrootDirectory` does.)
        let sftp_root: Option<std::path::PathBuf> = cli
            .sftp_root
            .as_deref()
            .or(sshd_cfg.global.sftp_root.as_deref())
            .map(std::path::PathBuf::from);
        let scp_enabled = pick(cli.scp, sshd_cfg.global.scp_enabled, true);
        let agent_forward = pick(
            cli.agent_forward,
            sshd_cfg.global.allow_agent_forwarding,
            true,
        );
        // X11Forwarding defaults to `no`, as in OpenSSH.
        let x11_forward = pick(cli.x11_forward, sshd_cfg.global.x11_forwarding, false);
        let login_grace_time = pick(
            cli.login_grace_time,
            sshd_cfg.global.login_grace_time,
            120u32,
        );
        let max_startups = pick(cli.max_startups, sshd_cfg.global.max_startups, 100u32);
        // `--per-source-max` > `PerSourceMaxStartups` > no cap (OpenSSH's
        // default; `none` is 0 as well).
        let per_source_max = pick(
            cli.per_source_max,
            sshd_cfg.global.per_source_max_startups,
            0u32,
        );

        // CLI host-keys, then any HostKey lines from config (cumulative).
        let mut host_key_files = cli.host_key_files.clone();
        host_key_files.extend(sshd_cfg.global.host_key_files.iter().cloned());
        if host_key_files.is_empty() {
            // OpenSSH's defaults, skipping the ones that do not exist.
            host_key_files = DEFAULT_HOST_KEYS
                .iter()
                .filter(|p| std::path::Path::new(p).exists())
                .map(|p| p.to_string())
                .collect();
        }
        if host_key_files.is_empty() {
            return Err(format!(
                "no host keys: none of {} exist (generate them with `ssh-keygen -A`), \
                 and no -h / HostKey was given",
                DEFAULT_HOST_KEYS.join(", ")
            ));
        }

        // CLI `-u`, then `AllowUsers` from the global section. `AllowUsers`
        // lines inside `Match` blocks are added per connection by the
        // authenticator once the user / peer are known.
        let mut allowed_user_list = cli.allowed_users.clone();
        allowed_user_list.extend(sshd_cfg.global.allow_users.iter().cloned());

        // Likewise `--accept-env` ++ `AcceptEnv`.
        let mut accept_env = cli.accept_env.clone();
        accept_env.extend(sshd_cfg.global.accept_env.iter().cloned());

        // Listen addresses: `-b` + `ListenAddress` (cumulative), on `ports`.
        let mut bind_specs = cli.listen_addresses.clone();
        bind_specs.extend(sshd_cfg.global.listen_addresses.iter().cloned());

        let mut host_certificate_files = cli.host_certificate_files.clone();
        host_certificate_files.extend(sshd_cfg.global.host_certificate_files.iter().cloned());
        // `HostKeyAgent SSH_AUTH_SOCK` names the environment's agent.
        let host_key_agent = sshd_cfg.global.host_key_agent.as_deref().and_then(|a| {
            if a == "SSH_AUTH_SOCK" {
                std::env::var("SSH_AUTH_SOCK")
                    .ok()
                    .filter(|s| !s.is_empty())
            } else {
                Some(a.to_string())
            }
        });
        let host_keys = load_host_keys_with_certs(
            &host_key_files,
            &host_certificate_files,
            strict_modes,
            host_key_agent.as_deref(),
        )?;
        // Authorized keys come in two mutually exclusive modes:
        //
        //  * Per-user (the default, OpenSSH semantics): `AuthorizedKeysFile`
        //    templates, expanded and read by each connection for its own
        //    login user (`LocalAuthenticator::resolved_authorized_keys`),
        //    StrictModes-checked against that user. Nothing is read here.
        //
        //  * `-A FILE`: ONE global file whose every key authorizes the single
        //    allowed user. Loaded now, as the daemon's user, with the
        //    root-owned StrictModes rule. Because the file cannot say *which*
        //    user a key belongs to, it is refused unless exactly one literal
        //    user is allowed anywhere in the configuration.
        // The single user a `-A` file authorizes, for the knock key source.
        let mut global_keys_user: Option<String> = None;
        let global_authorized_keys: Option<Arc<AuthorizedKeys>> = match &cli.authorized_keys_file {
            Some(path) => {
                let mut all_allowed: Vec<String> = allowed_user_list.clone();
                for block in &sshd_cfg.match_blocks {
                    all_allowed.extend(block.opts.allow_users.iter().cloned());
                }
                all_allowed.sort();
                all_allowed.dedup();
                let single = match all_allowed.as_slice() {
                    [] => current_user()?,
                    [one] if is_literal_user_token(one) => one.clone(),
                    _ => {
                        return Err(format!(
                            "-A {path}: a global authorized_keys file authorizes every key in it \
                             for every allowed user, so it requires exactly one literal allowed \
                             user (-u USER, or a single AllowUsers name with no wildcard/@host); \
                             configured: {all_allowed:?}. Use AuthorizedKeysFile (per-user, \
                             with %u/%h tokens) instead."
                        ));
                    }
                };
                let set = load_authorized_keys_and_cas(path, strict_modes, None)?;
                eprintln!(
                    "sshd: -A {path}: {} key(s) and {} cert-authority line(s) authorize user \
                     {single:?} (global file; every listed key logs in as that user)",
                    set.blobs.len(),
                    set.cas.len()
                );
                global_keys_user = Some(single);
                Some(Arc::new(set))
            }
            None => None,
        };
        let authorized_keys_files: Vec<String> = sshd_cfg
            .global
            .authorized_keys_file
            .clone()
            .unwrap_or_else(default_authorized_keys_files);
        let knock_keys = KnockKeys {
            users: (!sshd_cfg.global.knock_users.is_empty())
                .then(|| sshd_cfg.global.knock_users.clone()),
            global: global_keys_user.clone().zip(global_authorized_keys.clone()),
            files: authorized_keys_files.clone(),
            strict_modes,
            debug: cli.debug,
        };
        // A template with no per-user token is one shared file: every key in
        // it logs in as any allowed user. Legal (as in OpenSSH), but loud.
        for block in sshd_cfg.all_blocks() {
            for t in block.authorized_keys_file.iter().flatten() {
                if t.starts_with('/') && !t.contains("%u") && !t.contains("%h") {
                    eprintln!(
                        "sshd: WARNING: AuthorizedKeysFile {t} has no %u/%h token: every key in \
                         it can log in as ANY allowed user"
                    );
                }
            }
        }

        // TrustedUserCAKeys / RevokedKeys: load every file named in the global
        // section *or any Match block* now, so a bad path is a startup error
        // (failing closed beats silently running with no revocation), and each
        // connection just picks the set its matched blocks name.
        let mut ca_files: HashMap<String, Arc<Vec<Vec<u8>>>> = HashMap::new();
        let mut krls: HashMap<Vec<String>, Arc<puressh::krl::Krl>> = HashMap::new();
        for block in sshd_cfg.all_blocks() {
            if let Some(path) = &block.trusted_user_ca_keys
                && !ca_files.contains_key(path)
            {
                let cas = load_ca_keys_file(path, strict_modes)
                    .map_err(|e| format!("TrustedUserCAKeys: {e}"))?;
                ca_files.insert(path.clone(), Arc::new(cas));
            }
            if let Some(path) = &block.revoked_keys
                && !krls.contains_key(path)
            {
                krls.insert(path.clone(), Arc::new(load_krls(path, cli.debug)?));
            }
        }
        let trusted_user_ca_blobs: Vec<Vec<u8>> = sshd_cfg
            .global
            .trusted_user_ca_keys
            .as_ref()
            .and_then(|p| ca_files.get(p))
            .map(|v| (**v).clone())
            .unwrap_or_default();
        let revoked_keys: Option<Arc<puressh::krl::Krl>> = sshd_cfg
            .global
            .revoked_keys
            .as_ref()
            .and_then(|p| krls.get(p).cloned());

        // AuthorizedPrincipalsFile: keep the raw path *template* (it may carry
        // `%u`/`%h` tokens). Each connection expands it against its own login
        // user's passwd entry and loads it lazily in the authenticator — `%h`
        // is only knowable once the user is bound.
        let authorized_principals_file: Option<String> =
            sshd_cfg.global.authorized_principals_file.clone();

        // AllowUsers is matched as OpenSSH `Host`-style globs (a literal name
        // is just a glob with no metacharacters). Empty ⇒ no restriction, as
        // in OpenSSH (a daemon not running as root can only ever serve its
        // own user anyway: it cannot switch to anyone else).
        let default_allow_user: Option<String> = None;
        let allow_users = UserHostPattern::parse_all(&effective_allow_users(
            &cli.allowed_users,
            &sshd_cfg.global.allow_users,
            default_allow_user.as_deref(),
        ));
        let deny_users = UserHostPattern::parse_all(&sshd_cfg.global.deny_users);
        let allow_groups = puressh::config::HostPattern::parse_all(&sshd_cfg.global.allow_groups);
        let deny_groups = puressh::config::HostPattern::parse_all(&sshd_cfg.global.deny_groups);
        let group_lookup: GroupLookup = Arc::new(lookup_user_groups);

        // PermitRootLogin: CLI > config > built-in `prohibit-password`
        // (OpenSSH's default; permits root-by-key since puressh has no
        // password auth). The root-account check itself happens at login
        // time — in the authenticator during userauth, plus a backstop in the
        // on_session_open gate — resolving the requested username against the
        // live passwd database rather than a daemon-startup snapshot.
        let permit_root_login = pick(
            cli.permit_root_login,
            sshd_cfg.global.permit_root_login,
            puressh::config::PermitRootLogin::ProhibitPassword,
        );
        if cli.debug {
            eprintln!("sshd: PermitRootLogin={permit_root_login:?}");
        }

        // One PamGate per accept-loop iteration's child. The parent
        // holds a clone too, but fork's COW gives each connection its
        // own copy — no cross-connection state bleed. The authenticator
        // borrows a clone for password verification.
        // `PAMServiceName`: kept for the daemon's lifetime.
        let pam_service: &'static str = match &sshd_cfg.global.pam_service_name {
            Some(s) => Box::leak(s.clone().into_boxed_str()),
            None => "sshd",
        };
        let pam_gate = pam_gate::PamGate::new(cli.debug, pam_service);

        // Whether a real PAM backend is compiled in. Password and
        // keyboard-interactive auth are *only* advertised when both the config
        // enables them AND this is a PAM build — otherwise we'd offer a method
        // we cannot satisfy. `pam_check_password` on a non-PAM build always
        // fails, so this is the authoritative gate.
        //
        // `UsePAM no` turns PAM off altogether, as in OpenSSH: no PAM
        // account check or session, OpenSSH's own account checks instead
        // (locked or expired accounts), and no password or
        // keyboard-interactive authentication, which this build only does
        // through PAM. Unset, a PAM build uses PAM.
        let pam_available = cfg!(all(feature = "pam", target_os = "linux"))
            && sshd_cfg.global.use_pam != Some(false);
        if !pam_available {
            pam_gate.disable();
        }

        // OpenSSH defaults both to yes (Ubuntu's stock file turns
        // keyboard-interactive off).
        // What this build can offer. Whether a method is on for a connection
        // (`PubkeyAuthentication`, `PasswordAuthentication`,
        // `KbdInteractiveAuthentication`, globally or in a `Match` block, which
        // may turn one back on) is resolved per connection by the server, which
        // refuses an attempt at any other method before the authenticator sees
        // it.
        let password_enabled = pam_available;
        let kbd_interactive_enabled = pam_available;
        let permit_empty_passwords = sshd_cfg.global.permit_empty_passwords == Some(true);

        let asked_password = sshd_cfg.global.password_authentication == Some(true)
            || sshd_cfg.global.kbd_interactive_authentication == Some(true);
        if asked_password && !pam_available {
            eprintln!(
                "sshd: warning: PasswordAuthentication/KbdInteractiveAuthentication requested but \
                 no PAM backend is compiled in (need the `pam` feature on Linux); these methods \
                 will NOT be advertised"
            );
        }

        let mut advertised: Vec<&'static str> =
            vec!["publickey", "password", "keyboard-interactive"];
        if !pam_available {
            advertised.retain(|m| *m == "publickey");
        }
        if cli.debug {
            eprintln!("sshd: auth methods available: {advertised:?}");
        }

        // Connection-wide AuthenticationMethods default (multi-factor chains),
        // threaded into the authenticator via on_user_resolved.
        let default_auth_methods = sshd_cfg
            .global
            .authentication_methods
            .clone()
            .unwrap_or_default();

        let conn_policy = Arc::new(ConnPolicy {
            config: sshd_cfg.clone(),
            cli_allow_users: cli.allowed_users.clone(),
            default_allow_user,
            cli_permit_root_login: cli.permit_root_login,
            ca_files,
            krls,
        });

        let factory = Arc::new(LocalAuthFactory {
            native_account_checks: !pam_available,
            allow_users: Arc::new(allow_users),
            deny_users: Arc::new(deny_users),
            allow_groups: Arc::new(allow_groups),
            deny_groups: Arc::new(deny_groups),
            global_authorized_keys,
            authorized_keys_files,
            trusted_user_ca_blobs: Arc::new(trusted_user_ca_blobs),
            revoked_keys,
            policy: Some(conn_policy.clone()),
            authorized_principals_file,
            strict_modes,
            permit_root_login,
            group_lookup: group_lookup.clone(),
            pam: pam_gate.clone(),
            password_enabled,
            kbd_interactive_enabled,
            permit_empty_passwords,
            debug: cli.debug,
        });

        // Per-connection `PrintMotd`, resolved by `on_session_open` and read by
        // the PTY shell handler. Shared by `Arc` so the (COW-isolated) forked
        // child sees the value the hook wrote for *this* connection.
        let print_motd_flag = Arc::new(std::sync::atomic::AtomicBool::new(false));

        let shell_commands = Arc::new(ShellCommandHandler {
            pam: pam_gate.clone(),
            debug: cli.debug,
            debug_commands: cli.debug_commands,
        });
        let mut config = Config::new(host_keys, factory, advertised, shell_commands.clone())
            .with_auth_methods(default_auth_methods)
            .with_shell(Arc::new(NixShellHandler {
                pam: pam_gate.clone(),
                debug: cli.debug,
                print_motd: print_motd_flag.clone(),
            }));

        // Resolved CASignatureAlgorithms for user-certificate verification.
        if let Some(ca) = sshd_cfg.global.ca_signature_algorithms.clone() {
            config.ca_signature_algorithms = ca;
        }

        // Always installed: a forced `internal-sftp` runs it even without a
        // `Subsystem sftp` line, as OpenSSH's does.
        config = config.with_subsystem(Arc::new(SftpSubsystemHandler {
            enabled: sftp_enabled,
            read_only: sftp_read_only,
            root: sftp_root.clone(),
            args: sshd_cfg
                .global
                .subsystem_sftp_args
                .clone()
                .unwrap_or_default(),
            debug: cli.debug,
        }));
        for (name, command) in sshd_cfg.global.subsystems.iter().flatten() {
            config = config.with_subsystem_command(name, command);
        }

        // TCP and Unix-socket forwarding (`ssh -L/-R/-D/-W`), on by default
        // as in OpenSSH. The handlers accept what reaches them: the server's
        // per-user policy layer applies AllowTcpForwarding, PermitOpen,
        // PermitListen, GatewayPorts (bind-address rewrite),
        // AllowStreamLocalForwarding and DisableForwarding first, and the
        // connection already runs as the logged-in user.
        config = config
            .with_direct_tcpip(Arc::new(
                puressh::forwarding::direct::DefaultDirectTcpipHandler::permit_all(),
            ))
            .with_tcpip_forward(Arc::new(
                puressh::forwarding::reverse::DefaultTcpipForwardHandler::permit_all_interfaces(),
            ))
            .with_direct_streamlocal(Arc::new(
                puressh::forwarding::direct_streamlocal::DefaultDirectStreamlocalHandler::permit_all(),
            ))
            .with_streamlocal_forward(Arc::new(
                puressh::forwarding::streamlocal::DefaultStreamlocalForwardHandler::permit_all(),
            ))
            // PermitTunnel (default no) gates it; the device is opened as
            // the logged-in user, as OpenSSH's sshd does.
            .with_tun(Arc::new(TunDevices));

        // `exec` requests stream (stdin, stdout, stderr, exit status);
        // `scp` is served in-process when enabled.
        config = config.with_exec_stream_handler(Arc::new(ExecDispatch {
            scp: scp_enabled.then_some(ScpExecHandler { debug: cli.debug }),
            shell: shell_commands,
        }));

        if agent_forward {
            use puressh::forwarding::agent::DefaultAgentForwardHandler;
            config = config.with_agent_forward(Arc::new(DefaultAgentForwardHandler::new()));
        }

        if x11_forward {
            use puressh::forwarding::x11::DefaultX11ForwardHandler;
            config = config.with_x11_forward(Arc::new(DefaultX11ForwardHandler::new()));
        }

        // Connection-level session open. Two steps, in this order, exactly
        // once per connection:
        //
        //   1. pam.ensure() — pam_acct_mgmt + pam_open_session against
        //      service `sshd`, run while we are still root so pam_loginuid /
        //      pam_limits / pam_systemd (which need privilege) work, and so
        //      EVERY session type (shell / exec / SFTP / SCP) is uniformly
        //      gated by the authoritative account check. If PAM rejects the
        //      account (expired/locked, /etc/nologin, pam_time, pam_access)
        //      ensure() returns Err and we refuse the connection here —
        //      before any privilege drop and before any handler runs.
        //   2. drop_to_user() — drop to the authenticated user's uid/gid.
        //      Subsequent shell forks discover `already_matches(&info)` true
        //      and skip their own drop; SFTP/SCP run as the user in-process.
        //
        // The PAM session opened here stays valid for the connection's life;
        // the eventual pam_close_session runs at teardown as the user, which
        // works for every PAM module shipped by Linux distros today. The
        // per-handler ensure() calls are now idempotent no-ops (the gate is
        // once-guarded) and simply return the cached PAM env list.
        let debug = cli.debug;
        let session_pam = pam_gate.clone();
        let session_print_motd = print_motd_flag.clone();
        let hook_policy = conn_policy.clone();
        config = config.on_session_open(move |ctx: &SessionOpenContext<'_>| {
            let user = ctx.user;
            // Userauth has succeeded by the time this hook runs: tell the
            // daemon parent so this connection stops counting against
            // `MaxStartups` (whatever happens below, it is no longer an
            // unauthenticated connection an attacker could be holding open).
            notify_parent_authenticated();
            // PermitRootLogin backstop, evaluated at login time before we
            // open a PAM session or drop privilege. The authenticator already
            // denies root during userauth; this re-checks against the live
            // passwd database so a uid-0 login cannot proceed even if it
            // reached session-open by some other path. Resolved here (not at
            // startup) so it reflects the current database and the `Match`
            // blocks that apply to this connection.
            let permit_root_login = conn_permit_root_login(&hook_policy, user);
            // Resolve the identity we will drop to — uid, gid, supplementary
            // groups — from the REAL passwd/group databases now, before any
            // ChrootDirectory is entered. Everything below uses this resolved
            // value; nothing re-reads `<jail>/etc/passwd` or `<jail>/etc/group`
            // (a jail without them would fail closed, and a jail whose /etc is
            // writable by the user could otherwise map the login to uid 0 and
            // skip the drop entirely). The value is also cached so later
            // per-handler lookups (shell, home) inside the jail see it.
            let info = lookup_user(user)?;
            let gids = group_gids(&info.name, info.gid);
            let is_root = user == "root" || resolves_to_root(user) || info.uid.is_root();
            if is_root && !permit_root_login.permits_publickey() {
                if debug {
                    eprintln!(
                        "sshd: refusing session for root user {user}: PermitRootLogin forbids it"
                    );
                }
                return Err(puressh::Error::Io(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "root login not permitted",
                )));
            }
            remember_session_user(&info);
            // Stash the resolved PrintMotd for this connection so the PTY shell
            // handler (which runs later, in a COW-isolated forked child) can
            // read it. Default-off; only printed when PrintMotd=yes — which
            // avoids double-printing alongside PAM's pam_motd.
            session_print_motd.store(ctx.print_motd, std::sync::atomic::Ordering::Relaxed);
            // PAM_TTY = "ssh" matches OpenSSH's value for the session-level
            // gate; PTY shells later re-call ensure() (a no-op) for env.
            session_pam.ensure(user, "ssh")?;
            // ChrootDirectory: chroot() while we still hold root, *before*
            // drop_to_user's setuid (chroot(2) needs CAP_SYS_CHROOT). This
            // confines shell / exec / SFTP alike — the SFTP subsystem runs
            // in-process after this hook, so it inherits the new root too.
            // The path is validated StrictModes-style (root-owned, not
            // group/world-writable) before the chroot.
            if let Some(dir) = ctx.chroot_directory {
                apply_chroot(&info, dir, debug)?;
            }
            drop_to_user(&info, &gids, debug)
        });

        // Plumb finding-#1 (env allowlist) and finding-#2 (pre-auth
        // inactivity timeout) into the server config. with_accept_env
        // accepts an empty vec to mean "drop every client env" — which
        // is the secure default. login_grace_time = 0 disables the
        // timeout for users who want OpenSSH's classic "no limit"
        // behaviour.
        config = config.with_accept_env(accept_env);
        if login_grace_time > 0 {
            config = config
                .with_login_grace_time(std::time::Duration::from_secs(login_grace_time.into()));
        } else {
            // Pass Duration::ZERO so the server can treat 0 as "disabled".
            config = config.with_login_grace_time(std::time::Duration::ZERO);
        }

        // Crypto-algorithm overrides from sshd_config (already strict-validated
        // by the config parser). HostKeyAlgorithms is used as a preference
        // order and intersected with the loaded host keys; the strict-kex
        // markers are re-appended by the server regardless of KexAlgorithms.
        config = config.with_algorithms(
            sshd_cfg.global.ciphers.clone(),
            sshd_cfg.global.macs.clone(),
            sshd_cfg.global.kex_algorithms.clone(),
            sshd_cfg.global.host_key_algorithms.clone(),
        );
        config.pubkey_accepted_algorithms = sshd_cfg.global.pubkey_accepted_algorithms.clone();

        // RekeyLimit (startup-only): map the parsed thresholds onto the
        // server's RekeyPolicy. `default`/unset bytes keep the built-in cap;
        // an explicit time threshold replaces the duration. (No-op on builds
        // without the `std` feature, where max_duration does not exist.)
        if let Some(rk) = sshd_cfg.global.rekey_limit {
            let mut policy = config.rekey_policy;
            if let Some(b) = rk.max_bytes {
                policy.max_bytes = b;
            }
            #[cfg(feature = "std")]
            if let Some(secs) = rk.max_seconds {
                policy.max_duration = std::time::Duration::from_secs(secs as u64);
            }
            config.rekey_policy = policy;
        }

        // Compression (startup-only): `no` strips zlib from the KEXINIT advert.
        config.compression = sshd_cfg.global.compression;

        // AddressFamily (startup-only): `-4`/`-6` > config; restricts the
        // listener family.
        let address_family = cli.address_family.or(sshd_cfg.global.address_family);
        let listen = listen_addrs(&bind_specs, &ports, address_family)?;
        // PidFile (startup-only): write our PID after bind unless `none`;
        // OpenSSH's /run/sshd.pid by default (as root: elsewhere it could
        // not be written).
        let pid_file = if sshd_cfg.global.pid_file_set {
            sshd_cfg.global.pid_file.clone()
        } else if nix::unistd::geteuid().is_root() {
            Some("/run/sshd.pid".to_string())
        } else {
            None
        };

        // Per-connection policy: the whole parsed sshd_config (global + Match
        // blocks) is resolved twice per connection (pre-auth address-only,
        // post-auth user/groups) to gate the auth method set, banner, and
        // forwarding capabilities. The group resolver feeds `Match group`.
        config = config
            .with_policy(sshd_cfg.clone())
            .with_group_resolver(group_lookup);

        let cfg = Arc::new(config);

        // `-t`: everything above parsed and loaded; stop before binding.
        if cli.test_only {
            if cli.debug {
                eprintln!("sshd: configuration OK; would listen on {listen:?}");
            }
            return Ok(0);
        }

        // `-i`: one connection, on stdin / stdout.
        if cli.inetd {
            return serve_inetd(cfg);
        }

        // As OpenSSH does for its session processes: no ptrace attach and no
        // core dumps (host keys, session keys). Forked connection handlers
        // inherit it; the users' programs (exec) get the default back. Only
        // as root: a daemon run by an ordinary user holds keys that user can
        // read anyway, and non-dumpable makes /proc/self root-owned, which
        // breaks PAM modules (pam_loginuid) that user's sessions go through.
        #[cfg(any(target_os = "linux", target_os = "android"))]
        if nix::unistd::geteuid().is_root() {
            // SAFETY: PR_SET_DUMPABLE takes plain integer arguments.
            unsafe {
                libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0);
            }
        }

        install_parent_signals()?;

        // The parent holds a pipe per live connection (login records): use
        // the whole open-file allowance (systemd's soft default is 1024).
        // SAFETY: getrlimit/setrlimit on a local, fully initialised struct.
        unsafe {
            let mut lim: libc::rlimit = std::mem::zeroed();
            if libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) == 0 && lim.rlim_cur < lim.rlim_max {
                lim.rlim_cur = lim.rlim_max;
                libc::setrlimit(libc::RLIMIT_NOFILE, &lim);
            }
        }

        // As in OpenSSH, an address that cannot be bound (e.g. `::` on a host
        // without IPv6) is reported and skipped; only binding none is fatal.
        let mut listeners = Vec::with_capacity(listen.len());
        let mut bound = Vec::with_capacity(listen.len());
        let mut bind_errors = Vec::new();
        for a in &listen {
            match bind_listener(*a) {
                Ok(l) => {
                    listeners.push(l);
                    bound.push(*a);
                }
                Err(e) => {
                    eprintln!("sshd: warning: bind {a}: {e}");
                    bind_errors.push(format!("{a}: {e}"));
                }
            }
        }
        if listeners.is_empty() {
            return Err(format!(
                "could not bind any address: {}",
                bind_errors.join("; ")
            ));
        }
        let listen = bound;
        let mut knock = KnockFrontend::bind(
            &sshd_cfg.global,
            port,
            knock_keys,
            &host_key_files,
            cli.debug,
        )?;

        // Without `-D` (or `-d`): detach now that the listeners are up (so a
        // bind failure still reaches the terminal and the exit status), as
        // OpenSSH's daemon(0, 0): fork, the parent exits, a new session,
        // `/` as the working directory, stdio on /dev/null (except a `-E`
        // log, which is stderr). The parent is still single-threaded.
        if !cli.no_detach && !debug_flag {
            detach(cli.log_file.is_some())?;
        }

        // PidFile: write our PID now that the listener is up.
        if let Some(path) = pid_file.as_deref()
            && let Err(e) = std::fs::write(path, format!("{}\n", std::process::id()))
        {
            eprintln!("sshd: warning: could not write PidFile {path}: {e}");
        }

        for a in &listen {
            sshd_log::info(&format!(
                "Server listening on {} port {}.",
                sshd_log::addr_str(a.ip()),
                a.port()
            ));
        }
        notify_ready();

        // Exponential backoff for `fork()` EAGAIN — under a fork-bomb a
        // tight `continue` loop just makes the kernel keep saying no.
        // Reset to `MIN` on any successful fork.
        const FORK_BACKOFF_MIN_MS: u64 = 10;
        const FORK_BACKOFF_MAX_MS: u64 = 1_000;
        let mut fork_backoff_ms: u64 = FORK_BACKOFF_MIN_MS;

        // Live connection children: per-IP accounting for `--per-source-max`
        // and the unauthenticated count for `MaxStartups`. Reconciled at the
        // top of every pass (reap exits, collect auth notifications) — the
        // only place the caps are consulted is right before a fork, so that
        // is exactly when the table must be current.
        let mut children = ChildTable::default();
        let mut penalties = Penalties::new(&sshd_cfg.global);
        // How long `poll()` waits for a connection before the loop goes
        // around anyway to reap / check the shutdown flag. A signal (SIGCHLD,
        // SIGTERM) interrupts it earlier — `poll()` is not restarted on
        // EINTR, unlike std's `accept()`, which retries internally and would
        // otherwise swallow the wake-up.
        let accept_tick = PollTimeout::from(1_000u16);

        loop {
            if SHUTDOWN_REQUESTED.load(Ordering::Relaxed) {
                sshd_log::info("Received signal 15; terminating.");
                if cli.debug {
                    eprintln!("sshd: shutdown requested, exiting accept loop");
                }
                break;
            }
            if RELOAD_REQUESTED.swap(false, Ordering::Relaxed) {
                reload(&cli, &args);
            }
            if SIGCHLD_PENDING.swap(false, Ordering::Relaxed) || children.len() > 0 {
                children.reap(cli.debug, &mut penalties);
            }
            children.poll_auth();

            // Wait on the listener plus every knock socket / rendezvous
            // listener, waking early for the knock's own deadlines.
            let tick = match knock.next_wakeup() {
                Some(d) => {
                    let ms = d
                        .saturating_duration_since(std::time::Instant::now())
                        .as_millis()
                        .clamp(1, 1_000) as u16;
                    PollTimeout::from(ms)
                }
                None => accept_tick,
            };
            let ready_listeners: Vec<usize> = {
                let mut wait: Vec<PollFd<'_>> = listeners
                    .iter()
                    .map(|l| PollFd::new(l.as_fd(), PollFlags::POLLIN))
                    .collect();
                wait.extend(
                    knock
                        .poll_fds()
                        .into_iter()
                        .map(|fd| PollFd::new(fd, PollFlags::POLLIN)),
                );
                // Children's messages (logins to record) wake the loop too.
                wait.extend(
                    children
                        .pipe_fds()
                        .into_iter()
                        .map(|fd| PollFd::new(fd, PollFlags::POLLIN)),
                );
                match poll(&mut wait, tick) {
                    Ok(_) => {}
                    Err(Errno::EINTR) => continue, // signal: flags checked above
                    Err(e) => {
                        eprintln!("sshd: poll: {e}");
                        std::thread::sleep(std::time::Duration::from_millis(FORK_BACKOFF_MIN_MS));
                        continue;
                    }
                }
                (0..listeners.len())
                    .filter(|&i| wait[i].revents().is_some_and(|r| !r.is_empty()))
                    .collect()
            };

            // Connections to hand off this pass: knocked rendezvous
            // connections (bound to the knock's user), then the listener.
            let mut incoming: Vec<(std::net::TcpStream, std::net::SocketAddr, Option<String>)> =
                Vec::new();
            for (stream, peer, user) in knock.process() {
                if cli.debug {
                    eprintln!("sshd: knock: rendezvous from {peer} for {user}");
                }
                incoming.push((stream, peer, Some(user)));
            }
            for i in ready_listeners {
                match listeners[i].accept() {
                    Ok((stream, peer)) => incoming.push((stream, peer, None)),
                    Err(e)
                        if matches!(
                            e.kind(),
                            std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock
                        ) => {}
                    Err(e) => eprintln!("sshd: accept: {e}"),
                }
            }

            // TCPKeepAlive (default yes, as OpenSSH): a peer that vanished
            // is noticed and its session cleaned up.
            if sshd_cfg.global.tcp_keep_alive != Some(false) {
                for (stream, _, _) in &incoming {
                    let _ = nix::sys::socket::setsockopt(
                        stream,
                        nix::sys::socket::sockopt::KeepAlive,
                        &true,
                    );
                }
            }
            let mut incoming = incoming.into_iter();
            #[allow(clippy::while_let_on_iterator)] // the child drops `incoming` mid-loop
            while let Some((stream, peer, knock_user)) = incoming.next() {
                // PerSourcePenalties: a penalised source is turned away at
                // once, as OpenSSH's.
                if let Some(reason) = penalties.refuses(peer.ip()) {
                    if cli.debug {
                        eprintln!("sshd: drop connection from {peer}: {reason}");
                    }
                    drop(stream);
                    continue;
                }
                // Enforce both connection caps *before* fork so a flood
                // can't OOM us via per-process accounting. On refusal we
                // simply drop the socket — RST tells the client to retry.
                if let Err(reason) = children.admit(
                    &peer,
                    max_startups,
                    sshd_cfg.global.max_startups_early,
                    per_source_max,
                ) {
                    if cli.debug {
                        eprintln!(
                            "sshd: refused {peer}: {reason} (live={}, unauth={}, from-ip={})",
                            children.len(),
                            children.unauthenticated(),
                            children.count_from_ip(peer.ip())
                        );
                    }
                    drop(stream);
                    continue;
                }

                // Auth-notification pipe: the child writes one byte on userauth
                // success so the parent moves it out of the `MaxStartups`
                // count. Close-on-exec on both ends, so no program the child
                // later spawns inherits either. If the pipe cannot be created
                // the child is simply counted as unauthenticated for life
                // (fail closed for the cap; the connection still works).
                let (auth_rx, auth_tx) = match pipe_cloexec() {
                    Ok(p) => (Some(p.0), Some(p.1)),
                    Err(e) => {
                        eprintln!("sshd: pipe for auth notification: {e}");
                        (None, None)
                    }
                };
                AUTH_NOTIFY_FD.store(
                    auth_tx.as_ref().map(|fd| fd.as_raw_fd()).unwrap_or(-1),
                    Ordering::Relaxed,
                );

                // SAFETY: the daemon parent is single-threaded — no `thread::spawn`
                // in this loop — so the `fork()` is followed by ordinary Rust
                // code with no async-signal-safety concerns. The kernel
                // duplicates fds across fork; the child inherits its own copy of
                // `stream` and `listener`.
                match unsafe { fork() } {
                    Ok(ForkResult::Parent { child }) => {
                        fork_backoff_ms = FORK_BACKOFF_MIN_MS;
                        // The write end now belongs to the child alone: close
                        // ours so its EOF is observable, and forget the fd.
                        AUTH_NOTIFY_FD.store(-1, Ordering::Relaxed);
                        drop(auth_tx);
                        // Account the child (per-IP slot, unauthenticated) for as
                        // long as it lives; `reap` releases it.
                        children.insert(child, peer.ip(), auth_rx);
                        if cli.debug {
                            eprintln!(
                                "sshd: forked connection {peer} -> pid {} (live={}, unauth={})",
                                child.as_raw(),
                                children.len(),
                                children.unauthenticated(),
                            );
                        }
                        // Parent has no further use for this socket — its
                        // refcount in the child keeps it alive.
                        drop(stream);
                    }
                    Ok(ForkResult::Child) => {
                        // The child owns nothing in the parent's table: close the
                        // inherited read ends (this one's and every sibling's).
                        // Its own write end is now owned by `AUTH_NOTIFY_FD`, so
                        // the `OwnedFd` wrapper must not close it here.
                        drop(children);
                        drop(auth_rx);
                        if let Some(tx) = auth_tx {
                            core::mem::forget(tx);
                        }
                        // CRUCIAL: release the listener fd before we enter the
                        // long session loop. Without this, restarting the
                        // daemon on the same port keeps hitting EADDRINUSE
                        // because the kernel sees an open listener.
                        drop(listeners);
                        // Likewise the knock sockets, and every other connection
                        // of this batch (each is the parent's / a sibling's).
                        #[allow(clippy::drop_non_drop)] // empty without `knock`
                        drop(knock);
                        drop(incoming);
                        if let Ok(mut g) = KNOCK_USER.lock() {
                            *g = knock_user;
                        }
                        // Restore default SIGCHLD so the grandchild shell
                        // can be reaped via waitpid(WNOHANG).
                        // SAFETY: same justification as the parent — we run
                        // in a single-threaded process here.
                        let _ = unsafe { signal(Signal::SIGCHLD, SigHandler::SigDfl) };
                        // Likewise restore default SIGTERM/SIGINT/SIGHUP so
                        // the child dies cleanly on signal rather than getting
                        // the parent's shutdown / reload handlers.
                        let _ = unsafe { signal(Signal::SIGTERM, SigHandler::SigDfl) };
                        let _ = unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) };
                        let _ = unsafe { signal(Signal::SIGHUP, SigHandler::SigDfl) };

                        // Stash the peer address on *this child's* PamGate
                        // copy — set_peer mutates state behind a Mutex but
                        // post-fork COW means only this child sees it.
                        pam_gate.set_peer(peer.to_string());
                        // Likewise record this connection's socket addresses for
                        // the `Match LocalAddress`/`LocalPort` context and the
                        // session-open hook (COW-isolated per child).
                        if let Ok(mut g) = CONN_ADDRS.lock() {
                            *g = Some((peer, stream.local_addr().ok()));
                        }
                        sshd_log::conn_begin(peer, stream.local_addr().ok());

                        let result = handle_session_with_peer(stream, peer, cfg.clone());
                        sshd_log::conn_end(match &result {
                            Ok(()) => sshd_log::End::Closed,
                            Err(puressh::Error::Disconnected {
                                reason,
                                description,
                            }) => sshd_log::End::PeerDisconnect {
                                reason: *reason,
                                description,
                            },
                            Err(puressh::Error::AuthFailed) => sshd_log::End::AuthFailed,
                            Err(puressh::Error::Io(e))
                                if e.kind() == std::io::ErrorKind::TimedOut =>
                            {
                                sshd_log::End::GraceTimeout
                            }
                            // The client going away is a close, not an error.
                            Err(puressh::Error::Protocol("connection closed")) => {
                                sshd_log::End::Closed
                            }
                            Err(puressh::Error::Io(e))
                                if matches!(
                                    e.kind(),
                                    std::io::ErrorKind::ConnectionReset
                                        | std::io::ErrorKind::BrokenPipe
                                        | std::io::ErrorKind::UnexpectedEof
                                        | std::io::ErrorKind::ConnectionAborted
                                ) =>
                            {
                                sshd_log::End::Closed
                            }
                            Err(e) => match e.openssh_negotiation_message(false) {
                                Some(m) => sshd_log::End::NoMatch(m),
                                None => sshd_log::End::Error(e.to_string()),
                            },
                        });
                        let timed_out = matches!(&result, Err(puressh::Error::Io(e))
                            if e.kind() == std::io::ErrorKind::TimedOut);
                        let rc = match result {
                            Ok(()) => 0,
                            Err(e) => {
                                if cli.debug {
                                    eprintln!("sshd[child]: session error: {e}");
                                }
                                1
                            }
                        };
                        // Before authentication, the code says what the
                        // source is penalised for (PerSourcePenalties).
                        let rc = if AUTHENTICATED.load(Ordering::Relaxed) {
                            rc
                        } else {
                            preauth_exit_code(timed_out)
                        };
                        // Skip atexit machinery — we've already cleanly
                        // returned from handle_session.
                        unsafe { libc::_exit(rc) };
                    }
                    Err(e) => {
                        eprintln!("sshd: fork: {e} (backoff {fork_backoff_ms}ms)");
                        AUTH_NOTIFY_FD.store(-1, Ordering::Relaxed);
                        drop(auth_tx);
                        drop(auth_rx);
                        drop(stream);
                        // Bounded exponential backoff so a sustained EAGAIN
                        // (rlimit, OOM-killer pressure) doesn't pin a core.
                        std::thread::sleep(std::time::Duration::from_millis(fork_backoff_ms));
                        fork_backoff_ms = (fork_backoff_ms * 2).min(FORK_BACKOFF_MAX_MS);
                    }
                }
            }
        }
        // As OpenSSH's daemon on SIGTERM: the PidFile goes with it.
        if let Some(path) = pid_file.as_deref() {
            let _ = std::fs::remove_file(path);
        }
        Ok(0)
    }

    pub fn main() -> ExitCode {
        match run() {
            Ok(code) => {
                let clamped = code.clamp(0, 255) as u8;
                ExitCode::from(clamped)
            }
            Err(msg) => {
                eprintln!("sshd: {msg}");
                ExitCode::from(2)
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use puressh::config::HostPattern;

        #[test]
        fn cidr_matches_ipv4() {
            let ip = "10.1.2.3".parse().unwrap();
            assert!(cidr_matches("10.0.0.0/8", ip));
            assert!(cidr_matches("10.1.2.3", ip)); // bare = /32 exact
            assert!(!cidr_matches("10.1.2.4", ip));
            assert!(!cidr_matches("192.168.0.0/16", ip));
            // Family mismatch never matches.
            assert!(!cidr_matches("2001:db8::/32", ip));
            // Malformed prefix rejects.
            assert!(!cidr_matches("10.0.0.0/99", ip));
        }

        #[test]
        fn cidr_matches_ipv6() {
            let ip = "2001:db8::1".parse().unwrap();
            assert!(cidr_matches("2001:db8::/32", ip));
            assert!(!cidr_matches("2001:dead::/32", ip));
        }

        #[test]
        fn parse_peer_ip_forms() {
            assert_eq!(
                parse_peer_ip("10.0.0.5:2222"),
                Some("10.0.0.5".parse().unwrap())
            );
            assert_eq!(parse_peer_ip("10.0.0.5"), Some("10.0.0.5".parse().unwrap()));
            assert_eq!(
                parse_peer_ip("[2001:db8::1]:22"),
                Some("2001:db8::1".parse().unwrap())
            );
        }

        #[test]
        fn sanitize_log_strips_control_chars_and_truncates() {
            assert_eq!(sanitize_log("alice"), "alice");
            assert_eq!(sanitize_log("a\nb\rc\x1b[2Jd\x7f"), "a?b?c?[2Jd?");
            let long = "x".repeat(LOG_FIELD_MAX + 10);
            let out = sanitize_log(&long);
            assert_eq!(out.chars().count(), LOG_FIELD_MAX + 1);
            assert!(out.ends_with('…'));
        }

        #[test]
        fn invalid_usernames_never_bind() {
            assert!(valid_username("alice"));
            assert!(!valid_username(""));
            assert!(!valid_username("ali\nce"));
            assert!(!valid_username(&"a".repeat(USERNAME_MAX + 1)));
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            assert!(!a.check_user_binding("eve\x1b[2J"));
            assert!(a.bound_user.is_none(), "an invalid name must not bind");
            // A publickey attempt with such a name is refused outright.
            let decision = a.evaluate(AuthAttempt::PublicKey {
                user: "eve\r\nforged: line".into(),
                algorithm: "ssh-ed25519".into(),
                public_blob: vec![1, 2, 3],
                probe_only: true,
                verified: false,
                cert: None,
            });
            assert!(matches!(decision, AuthDecision::Reject));
        }

        #[test]
        fn decode_ssh_string_roundtrip() {
            // "force-command"="echo hi" inner payload is an SSH string.
            let mut blob = Vec::new();
            let s = b"echo hi";
            blob.extend_from_slice(&(s.len() as u32).to_be_bytes());
            blob.extend_from_slice(s);
            assert_eq!(decode_ssh_string(&blob).as_deref(), Some("echo hi"));
            // Truncated / mismatched length rejects.
            assert_eq!(decode_ssh_string(&blob[..blob.len() - 1]), None);
        }

        /// Build a `LocalAuthenticator` with a mock group resolver for access
        /// precedence tests. `groups` maps user→group-names.
        fn auth_with(
            allow_users: &[&str],
            deny_users: &[&str],
            allow_groups: &[&str],
            deny_groups: &[&str],
            groups: std::collections::HashMap<String, Vec<String>>,
        ) -> LocalAuthenticator {
            auth_with_peer(
                allow_users,
                deny_users,
                allow_groups,
                deny_groups,
                groups,
                None,
            )
        }

        /// Like [`auth_with`] but pins the connection's resolved peer address,
        /// so `AllowUsers`/`DenyUsers` `user@host` tokens can be exercised.
        fn auth_with_peer(
            allow_users: &[&str],
            deny_users: &[&str],
            allow_groups: &[&str],
            deny_groups: &[&str],
            groups: std::collections::HashMap<String, Vec<String>>,
            peer: Option<&str>,
        ) -> LocalAuthenticator {
            let to_uh = |xs: &[&str]| {
                UserHostPattern::parse_all(&xs.iter().map(|s| s.to_string()).collect::<Vec<_>>())
            };
            let to_pats = |xs: &[&str]| {
                HostPattern::parse_all(&xs.iter().map(|s| s.to_string()).collect::<Vec<_>>())
            };
            let groups = std::sync::Arc::new(groups);
            let lookup: GroupLookup =
                std::sync::Arc::new(move |u: &str| groups.get(u).cloned().unwrap_or_default());
            LocalAuthenticator {
                native_account_checks: false,
                allow_users: to_uh(allow_users),
                deny_users: to_uh(deny_users),
                allow_groups: to_pats(allow_groups),
                deny_groups: to_pats(deny_groups),
                global_authorized_keys: None,
                authorized_keys_files: Vec::new(),
                authorized_keys: Some(AuthorizedKeys::default()),
                trusted_user_ca_blobs: Vec::new(),
                revoked_keys: None,
                policy: None,
                policy_broken: false,
                authorized_principals_file: None,
                strict_modes: false,
                authorized_principals: None,
                auth_commands: AuthCommands::default(),
                command_cache: Default::default(),
                permit_root_login: puressh::config::PermitRootLogin::ProhibitPassword,
                pam: pam_gate::PamGate::new(false, "sshd"),
                password_enabled: false,
                kbd_interactive_enabled: false,
                kbd_conv: None,
                pending_first_prompt: true,
                permit_empty_passwords: false,
                pubkey_accepted: None,
                required_rsa_size: DEFAULT_REQUIRED_RSA_SIZE,
                chains: Vec::new(),
                satisfied: Vec::new(),
                bound_user: None,
                root_uid0_cache: std::collections::HashMap::new(),
                group_cache: std::collections::HashMap::new(),
                group_lookup: lookup,
                peer: peer.map(str::to_string),
                debug: false,
                accepted_options: None,
            }
        }

        #[test]
        fn deny_users_wins_over_allow_users() {
            let mut a = auth_with(&["alice", "bob"], &["bob"], &[], &[], Default::default());
            assert!(a.access_allowed("alice"));
            // bob is allowed *and* denied — DenyUsers has higher precedence.
            assert!(!a.access_allowed("bob"));
        }

        // ---- FD: password / multi-factor helpers ---------------------------

        #[test]
        fn empty_password_policy() {
            // Non-empty password is always allowed to proceed.
            assert!(LocalAuthenticator::empty_password_allowed(false, b"secret"));
            assert!(LocalAuthenticator::empty_password_allowed(true, b"secret"));
            // Empty password: refused unless PermitEmptyPasswords.
            assert!(!LocalAuthenticator::empty_password_allowed(false, b""));
            assert!(LocalAuthenticator::empty_password_allowed(true, b""));
        }

        #[test]
        fn parse_chains_any_is_single_factor() {
            assert!(parse_auth_method_chains(&["any".to_string()]).is_empty());
            assert!(parse_auth_method_chains(&[]).is_empty());
        }

        #[test]
        fn parse_chains_maps_factors() {
            let chains = parse_auth_method_chains(&["publickey,password".to_string()]);
            assert_eq!(chains, vec![vec!["publickey", "password"]]);
            // `none` never counts toward a chain.
            let chains2 = parse_auth_method_chains(&["publickey,none".to_string()]);
            assert_eq!(chains2, vec![vec!["publickey"]]);
            // Multiple alternatives.
            let chains3 = parse_auth_method_chains(&[
                "publickey,password".to_string(),
                "keyboard-interactive".to_string(),
            ]);
            assert_eq!(
                chains3,
                vec![vec!["publickey", "password"], vec!["keyboard-interactive"]]
            );
        }

        #[test]
        fn failure_lists_only_methods_that_can_continue() {
            let offered = ["publickey", "password", "keyboard-interactive"];
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            // Single-factor: everything offered.
            assert_eq!(a.continuable_methods(&offered), offered);
            // `AuthenticationMethods publickey,password publickey,keyboard-interactive`.
            a.chains = vec![
                vec!["publickey", "password"],
                vec!["publickey", "keyboard-interactive"],
            ];
            assert_eq!(a.continuable_methods(&offered), ["publickey"]);
            a.satisfied = vec!["publickey"];
            assert_eq!(
                a.continuable_methods(&offered),
                ["password", "keyboard-interactive"]
            );
            // A method the server does not offer is never listed.
            assert_eq!(
                a.continuable_methods(&["publickey", "password"]),
                ["password"]
            );
        }

        #[test]
        fn record_and_decide_single_factor_accepts_immediately() {
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            // No chains installed ⇒ single-factor: one success accepts.
            assert!(matches!(
                a.record_and_decide("publickey"),
                AuthDecision::Accept
            ));
        }

        #[test]
        fn record_and_decide_multifactor_partial_then_accept() {
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.chains = vec![vec!["publickey", "password"]];
            // First factor ⇒ PartialAccept asking for the remaining one.
            match a.record_and_decide("publickey") {
                AuthDecision::PartialAccept { still_required } => {
                    assert_eq!(still_required, vec!["password".to_string()]);
                }
                other => panic!("expected PartialAccept, got {other:?}"),
            }
            // Second factor completes the chain ⇒ Accept.
            assert!(matches!(
                a.record_and_decide("password"),
                AuthDecision::Accept
            ));
        }

        #[test]
        fn record_and_decide_enforces_listed_order() {
            // OpenSSH positional order: for `publickey,password`, completing
            // `password` FIRST is out of order and rejected; only `publickey`
            // first advances the chain.
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.chains = vec![vec!["publickey", "password"]];
            // password-first ⇒ rejected, chain not advanced.
            assert!(matches!(
                a.record_and_decide("password"),
                AuthDecision::Reject
            ));
            assert!(a.satisfied.is_empty(), "rejected method must not commit");
            // publickey first ⇒ PartialAccept asking for password next.
            match a.record_and_decide("publickey") {
                AuthDecision::PartialAccept { still_required } => {
                    assert_eq!(still_required, vec!["password".to_string()]);
                }
                other => panic!("expected PartialAccept, got {other:?}"),
            }
            // now password completes the chain in order.
            assert!(matches!(
                a.record_and_decide("password"),
                AuthDecision::Accept
            ));
        }

        #[test]
        fn record_and_decide_still_required_is_next_not_set() {
            // With two alternative chains sharing a first factor, `still_required`
            // after the shared first factor lists only the *next* methods, in the
            // listed order — never the full remaining set.
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.chains = vec![
                vec!["publickey", "password"],
                vec!["publickey", "keyboard-interactive"],
            ];
            match a.record_and_decide("publickey") {
                AuthDecision::PartialAccept { still_required } => {
                    assert_eq!(
                        still_required,
                        vec!["password".to_string(), "keyboard-interactive".to_string()]
                    );
                }
                other => panic!("expected PartialAccept, got {other:?}"),
            }
            // Completing the second factor of either alternative accepts.
            assert!(matches!(
                a.record_and_decide("keyboard-interactive"),
                AuthDecision::Accept
            ));
        }

        #[test]
        fn record_and_decide_three_factor_order() {
            // A three-factor chain must be completed strictly in order.
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.chains = vec![vec!["publickey", "keyboard-interactive", "password"]];
            assert!(matches!(
                a.record_and_decide("publickey"),
                AuthDecision::PartialAccept { .. }
            ));
            // Skipping to `password` (the 3rd) before the 2nd is rejected.
            assert!(matches!(
                a.record_and_decide("password"),
                AuthDecision::Reject
            ));
            // The expected 2nd factor advances.
            assert!(matches!(
                a.record_and_decide("keyboard-interactive"),
                AuthDecision::PartialAccept { .. }
            ));
            assert!(matches!(
                a.record_and_decide("password"),
                AuthDecision::Accept
            ));
        }

        #[test]
        fn user_binding_rejects_username_switch() {
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            assert!(a.check_user_binding("alice"));
            assert!(a.check_user_binding("alice")); // same user OK
            assert!(!a.check_user_binding("bob")); // switch rejected
        }

        #[test]
        fn allow_users_glob() {
            let mut a = auth_with(&["dev-*"], &[], &[], &[], Default::default());
            assert!(a.access_allowed("dev-1"));
            assert!(!a.access_allowed("prod-1"));
        }

        #[test]
        fn allow_groups_requires_membership() {
            let mut groups = std::collections::HashMap::new();
            groups.insert("alice".to_string(), vec!["wheel".to_string()]);
            groups.insert("bob".to_string(), vec!["users".to_string()]);
            let mut a = auth_with(&["*"], &[], &["wheel"], &[], groups);
            assert!(a.access_allowed("alice")); // in wheel
            assert!(!a.access_allowed("bob")); // not in wheel
        }

        #[test]
        fn deny_groups_precedes_allow_groups() {
            let mut groups = std::collections::HashMap::new();
            groups.insert(
                "eve".to_string(),
                vec!["wheel".to_string(), "banned".to_string()],
            );
            let mut a = auth_with(&["*"], &[], &["wheel"], &["banned"], groups);
            // eve is in wheel (allowed) but also banned (denied) — DenyGroups
            // is evaluated before AllowGroups, so she is refused.
            assert!(!a.access_allowed("eve"));
        }

        // ---- F8: AllowUsers/DenyUsers user@host -----------------------------

        #[test]
        fn allow_users_at_host_matches_peer() {
            // alice@10.0.0.0/8-ish glob: only from 10.* hosts.
            let mut a = auth_with_peer(
                &["alice@10.*"],
                &[],
                &[],
                &[],
                Default::default(),
                Some("10.1.2.3"),
            );
            assert!(a.access_allowed("alice"));
            // Wrong user.
            assert!(!a.access_allowed("bob"));

            // Same rule, peer outside the host glob ⇒ denied.
            let mut b = auth_with_peer(
                &["alice@10.*"],
                &[],
                &[],
                &[],
                Default::default(),
                Some("192.168.0.1"),
            );
            assert!(!b.access_allowed("alice"));

            // A user@host rule with no known peer never matches.
            let mut c = auth_with_peer(&["alice@10.*"], &[], &[], &[], Default::default(), None);
            assert!(!c.access_allowed("alice"));
        }

        #[test]
        fn allow_users_mixed_bare_and_at_host() {
            // bob matches by bare username from any host; alice only from 10.*.
            let mut a = auth_with_peer(
                &["bob", "alice@10.*"],
                &[],
                &[],
                &[],
                Default::default(),
                Some("203.0.113.9"),
            );
            assert!(a.access_allowed("bob")); // bare token, host-independent
            assert!(!a.access_allowed("alice")); // alice only from 10.*
        }

        #[test]
        fn deny_users_at_host_blocks_by_peer() {
            // eve is allowed by the wildcard, but denied specifically from the
            // evil host range.
            let mut a = auth_with_peer(
                &["*"],
                &["eve@10.6.6.*"],
                &[],
                &[],
                Default::default(),
                Some("10.6.6.66"),
            );
            assert!(!a.access_allowed("eve"));
            // Same eve from a different host is fine.
            let mut b = auth_with_peer(
                &["*"],
                &["eve@10.6.6.*"],
                &[],
                &[],
                Default::default(),
                Some("10.0.0.1"),
            );
            assert!(b.access_allowed("eve"));
        }

        #[test]
        fn user_host_pattern_parse() {
            let p = UserHostPattern::parse("alice@1.2.3.4");
            assert!(!p.negated);
            assert!(p.positive_match("alice", Some("1.2.3.4")));
            assert!(!p.positive_match("alice", Some("1.2.3.5")));
            assert!(!p.positive_match("bob", Some("1.2.3.4")));

            let neg = UserHostPattern::parse("!alice@1.2.3.4");
            assert!(neg.negated);
            assert!(neg.positive_match("alice", Some("1.2.3.4")));

            let bare = UserHostPattern::parse("dev-*");
            assert!(bare.host.is_none());
            assert!(bare.positive_match("dev-1", None));
        }

        // ---- F7: ChrootDirectory path resolution + ownership check ----------

        #[test]
        fn chroot_token_expansion() {
            let info = lookup_user_for_test();
            let out = expand_pct_tokens("/chroots/%u", &info).expect("expand");
            assert_eq!(out, format!("/chroots/{}", info.name));
            let out2 = expand_pct_tokens("%h/jail", &info).expect("expand");
            assert_eq!(out2, format!("{}/jail", info.home_str));
            assert_eq!(expand_pct_tokens("100%%", &info).expect("expand"), "100%");
            // Unknown token rejected.
            assert!(expand_pct_tokens("%z", &info).is_err());
            assert!(expand_pct_tokens("trailing%", &info).is_err());
        }

        #[test]
        fn authorized_principals_file_expands_u_token() {
            // Build an AuthorizedPrincipalsFile path containing `%u`, write a
            // principals list at the expanded path, and confirm the lazy loader
            // resolves + reads it for the bound user.
            let info = lookup_user_for_test();
            let user = info.name.clone();
            let dir = std::env::temp_dir().join(format!("puressh-princ-{}", std::process::id()));
            std::fs::create_dir_all(&dir).expect("mkdir");
            // Path template uses %u; the resolved file is named after the user.
            let template = format!("{}/%u.principals", dir.display());
            let expanded = format!("{}/{}.principals", dir.display(), user);
            std::fs::write(&expanded, "alice\nbob\n# comment\n\n").expect("write principals");

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_principals_file = Some(template);
            a.strict_modes = false; // temp file isn't root-owned

            let resolved = a
                .resolved_principals(&user)
                .clone()
                .map(|l| l.into_iter().map(|p| p.name).collect::<Vec<_>>());
            std::fs::remove_file(&expanded).ok();
            std::fs::remove_dir(&dir).ok();

            assert_eq!(
                resolved,
                Some(vec!["alice".to_string(), "bob".to_string()]),
                "%u-expanded AuthorizedPrincipalsFile must load the user's file"
            );
        }

        #[test]
        fn authorized_principals_file_none_is_no_constraint() {
            // No file configured ⇒ resolves to `None` (login user must itself be
            // a cert principal — OpenSSH default).
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_principals_file = None;
            assert!(a.resolved_principals("anyone").is_none());
        }

        #[test]
        fn authorized_principals_file_missing_fails_closed() {
            // A configured-but-missing file resolves to `Some(vec![])` — no
            // principals — which fails authorization closed (never widens it).
            let info = lookup_user_for_test();
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_principals_file = Some("/nonexistent/puressh/%u.principals".to_string());
            a.strict_modes = false;
            assert!(
                a.resolved_principals(&info.name)
                    .as_ref()
                    .is_some_and(Vec::is_empty)
            );
        }

        /// Resolve a real user for token-expansion tests: prefer $USER, fall
        /// back to root (always present).
        fn lookup_user_for_test() -> UserInfo {
            std::env::var("USER")
                .ok()
                .filter(|n| !n.is_empty())
                .and_then(|n| lookup_user(&n).ok())
                .or_else(|| lookup_user("root").ok())
                .expect("a resolvable test user")
        }

        #[test]
        fn session_user_cache_answers_lookup_without_passwd() {
            // Once the session-open hook has resolved the identity, a lookup
            // for that name is served from the cache (as it would be inside a
            // jail with no /etc/passwd), and other names still hit the
            // database.
            let mut info = lookup_user_for_test();
            info.name = "puressh-cached-user-xyzzy".to_string();
            info.home_str = "/cached-home".to_string();
            remember_session_user(&info);
            let got = lookup_user("puressh-cached-user-xyzzy").expect("served from cache");
            assert_eq!(got.home_str, "/cached-home");
            assert_eq!(got.uid, info.uid);
            assert!(lookup_user("\u{0}no-such-user-xyzzy").is_err());
            if let Ok(mut g) = SESSION_USER.lock() {
                *g = None;
            }
        }

        #[test]
        fn chroot_validation_rejects_non_root_owned() {
            // A temp dir created by the (non-root) test process is owned by the
            // test user, not root ⇒ the StrictModes-style check must refuse it.
            // Skip when the suite happens to run as root (the dir would then be
            // root-owned and pass the ownership half).
            if nix::unistd::geteuid().is_root() {
                return;
            }
            let dir = std::env::temp_dir().join(format!("puressh-chroot-{}", std::process::id()));
            let _ = std::fs::create_dir(&dir);
            let res = validate_chroot_dir(dir.to_str().unwrap());
            assert!(
                res.is_err(),
                "a non-root-owned chroot dir must be rejected: {res:?}"
            );
            let _ = std::fs::remove_dir(&dir);
        }

        #[test]
        fn chroot_validation_root_passes_ownership_but_checks_writability() {
            // `/` is root-owned and not group/world-writable on a sane system,
            // so the validator accepts it. (This documents the happy path
            // without needing root to create a fixture.)
            // Only assert when `/` actually has secure modes (it does on
            // standard installs); otherwise skip to avoid CI flakiness.
            use std::os::unix::fs::MetadataExt;
            if let Ok(md) = std::fs::metadata("/")
                && md.uid() == 0
                && md.mode() & 0o022 == 0
            {
                assert!(validate_chroot_dir("/").is_ok());
            }
        }

        /// End-to-end chroot confinement. Requires root (chroot(2) needs
        /// CAP_SYS_CHROOT) and is therefore `#[ignore]`d by default; run with
        /// `sudo cargo test --bin sshd -- --ignored chroot_confines`.
        ///
        /// Builds a root-owned jail containing a single marker file, forks,
        /// `apply_chroot`s in the child, and asserts that (a) the marker is now
        /// reachable at `/marker` and (b) a host-only path outside the jail is
        /// no longer reachable — i.e. the process is genuinely confined.
        #[test]
        #[ignore = "needs root: chroot(2) requires CAP_SYS_CHROOT"]
        fn chroot_confines_filesystem() {
            use std::io::Write;
            use std::os::unix::fs::PermissionsExt;

            assert!(
                nix::unistd::geteuid().is_root(),
                "this #[ignore] test must run as root"
            );

            let jail = std::env::temp_dir().join(format!("puressh-jail-{}", std::process::id()));
            std::fs::create_dir_all(&jail).expect("mkdir jail");
            // Root-owned (we are root) and 0755 — passes the StrictModes check.
            std::fs::set_permissions(&jail, std::fs::Permissions::from_mode(0o755))
                .expect("chmod jail");
            {
                let mut f = std::fs::File::create(jail.join("marker")).expect("marker");
                f.write_all(b"inside").expect("write marker");
            }

            // A sentinel that exists on the host but NOT inside the jail.
            let host_only =
                std::env::temp_dir().join(format!("puressh-host-only-{}", std::process::id()));
            std::fs::File::create(&host_only).expect("host-only");

            // Fork so the chroot does not poison the rest of the test process.
            // SAFETY: single-threaded test child; only does fs reads + _exit.
            match unsafe { fork() }.expect("fork") {
                ForkResult::Child => {
                    let root = lookup_user("root").expect("root passwd entry");
                    let ok = apply_chroot(&root, jail.to_str().unwrap(), false).is_ok()
                        && std::fs::read("/marker")
                            .map(|b| b == b"inside")
                            .unwrap_or(false)
                        && !std::path::Path::new(host_only.to_str().unwrap()).exists();
                    unsafe { libc::_exit(if ok { 0 } else { 1 }) };
                }
                ForkResult::Parent { child } => {
                    let status = nix::sys::wait::waitpid(child, None).expect("waitpid");
                    let _ = std::fs::remove_file(&host_only);
                    let _ = std::fs::remove_dir_all(&jail);
                    assert!(
                        matches!(status, nix::sys::wait::WaitStatus::Exited(_, 0)),
                        "child reported chroot confinement failure: {status:?}"
                    );
                }
            }
        }

        // ---- F6: PrintMotd CRLF rewriting -----------------------------------

        #[test]
        fn motd_crlf_rewrite() {
            // Bare LF gets a CR; existing CRLF is preserved (no doubled CR).
            assert_eq!(crlf_for_pty(b"hello\nworld\n"), b"hello\r\nworld\r\n");
            assert_eq!(crlf_for_pty(b"a\r\nb"), b"a\r\nb");
            assert_eq!(crlf_for_pty(b"no newline"), b"no newline");
            assert_eq!(crlf_for_pty(b""), b"");
        }

        #[test]
        fn lookup_user_groups_includes_real_primary() {
            // The current test user always exists; its group list is non-empty
            // (at least the primary group resolves to a name on normal
            // systems). This guards the getgrouplist plumbing.
            if let Ok(name) = std::env::var("USER")
                && !name.is_empty()
            {
                let groups = lookup_user_groups(&name);
                // Not asserting exact contents (CI users vary); just that the
                // call returns without panicking. A known user usually yields
                // at least one group.
                let _ = groups;
            }
            // An impossible user name resolves to no groups.
            assert!(lookup_user_groups("\u{0}no-such-user-xyzzy").is_empty());
        }

        // ---- KRL revocation wiring -----------------------------------------

        /// Decode a hex string to bytes (test-only helper).
        fn unhex(s: &str) -> Vec<u8> {
            (0..s.len())
                .step_by(2)
                .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
                .collect()
        }

        /// Real `ssh-keygen -k` explicit-key KRL revoking the user key below.
        const KRL_EXPLICIT_HEX: &str = "5353484b524c0a00000000010000000000000000000000006a31ff28000000000000000000000000000000000200000037000000330000000b7373682d6564323535313900000020dac8c367fff423cc766d20abff4f2620880f421ea7e2c58a47100892e490547f";
        /// Raw wire blob of that user's ed25519 public key.
        const USERKEY_BLOB_HEX: &str = "0000000b7373682d6564323535313900000020dac8c367fff423cc766d20abff4f2620880f421ea7e2c58a47100892e490547f";

        #[test]
        fn krl_revokes_authorized_plain_key() {
            let blob = unhex(USERKEY_BLOB_HEX);
            let krl =
                puressh::krl::Krl::parse(&unhex(KRL_EXPLICIT_HEX)).expect("parse fixture KRL");

            // Build an authenticator that *authorizes* the key, then revokes it.
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = Some(AuthorizedKeys {
                blobs: vec![blob.clone()],
                cas: Vec::new(),
                ..Default::default()
            });
            a.revoked_keys = Some(std::sync::Arc::new(krl));

            // A verified publickey attempt for an authorized-but-revoked key is
            // rejected.
            let decision = a.evaluate(AuthAttempt::PublicKey {
                user: "alice".into(),
                algorithm: "ssh-ed25519".into(),
                public_blob: blob.clone(),
                probe_only: false,
                verified: true,
                cert: None,
            });
            assert!(matches!(decision, AuthDecision::Reject));
        }

        fn verified_attempt(alg: &str, blob: &[u8]) -> AuthAttempt {
            AuthAttempt::PublicKey {
                user: "alice".into(),
                algorithm: alg.into(),
                public_blob: blob.to_vec(),
                probe_only: false,
                verified: true,
                cert: None,
            }
        }

        fn authorizing(blob: &[u8]) -> LocalAuthenticator {
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = Some(AuthorizedKeys {
                blobs: vec![blob.to_vec()],
                cas: Vec::new(),
                ..Default::default()
            });
            a
        }

        #[test]
        fn pubkey_accepted_algorithms_gate_userauth() {
            let blob = unhex(USERKEY_BLOB_HEX);
            let mut a = authorizing(&blob);
            assert!(matches!(
                a.evaluate(verified_attempt("ssh-ed25519", &blob)),
                AuthDecision::Accept
            ));
            let mut a = authorizing(&blob);
            a.pubkey_accepted = Some(vec!["rsa-sha2-512".into()]);
            assert!(matches!(
                a.evaluate(verified_attempt("ssh-ed25519", &blob)),
                AuthDecision::Reject
            ));
        }

        #[test]
        fn required_rsa_size_gates_userauth() {
            let rsa = |bits: usize| {
                let mut n = vec![0u8; bits / 8];
                n[0] = 0x80;
                PublicKey::Rsa {
                    e: vec![1, 0, 1],
                    n,
                    comment: String::new(),
                }
                .wire_blob()
            };
            let small = rsa(1024);
            assert_eq!(rsa_modulus_bits(&small), Some(1024));
            assert_eq!(rsa_modulus_bits(&unhex(USERKEY_BLOB_HEX)), None);
            let mut a = authorizing(&small);
            assert!(!matches!(
                a.evaluate(verified_attempt("rsa-sha2-512", &small)),
                AuthDecision::Reject
            ));
            let mut a = authorizing(&small);
            a.required_rsa_size = 2048;
            assert!(matches!(
                a.evaluate(verified_attempt("rsa-sha2-512", &small)),
                AuthDecision::Reject
            ));
            let tiny = rsa(768);
            let mut a = authorizing(&tiny);
            assert!(matches!(
                a.evaluate(verified_attempt("rsa-sha2-512", &tiny)),
                AuthDecision::Reject
            ));
        }

        /// A `CertInfo` wrapping `USERKEY_BLOB_HEX` as its embedded key, signed
        /// by a (fake) CA blob, with `alice` as its sole principal. The CA
        /// signature was already verified by the auth layer by the time the
        /// authenticator sees a `verified` attempt, so no real signature is
        /// needed to exercise the trust gate.
        fn cert_info_for(ca_blob: &[u8], principals: &[&str]) -> puressh::auth::CertInfo {
            puressh::auth::CertInfo::new(
                ca_blob.to_vec(),
                unhex(USERKEY_BLOB_HEX),
                "ssh-ed25519",
                "test-cert",
                7,
                principals.iter().map(|s| s.to_string()).collect(),
            )
        }

        #[test]
        fn krl_revoked_plain_key_also_refuses_certificate_wrapping_it() {
            // The KRL revokes the plain user key. A certificate whose
            // *embedded* key is that plain key must be refused even though the
            // cert blob itself (a different byte string) is not listed and the
            // CA is trusted.
            let krl =
                puressh::krl::Krl::parse(&unhex(KRL_EXPLICIT_HEX)).expect("parse fixture KRL");
            let ca_blob =
                b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20fakeCAfakeCAfakeCAfakeCAfakeCAfa"
                    .to_vec();
            let ci = cert_info_for(&ca_blob, &["alice"]);
            let cert_blob = b"not-the-plain-key-blob".to_vec();

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.trusted_user_ca_blobs = vec![ca_blob.clone()];
            // Sanity: without a KRL the certificate is accepted.
            let ok = a.evaluate(AuthAttempt::PublicKey {
                user: "alice".into(),
                algorithm: "ssh-ed25519-cert-v01@openssh.com".into(),
                public_blob: cert_blob.clone(),
                probe_only: false,
                verified: true,
                cert: Some(ci.clone()),
            });
            assert!(matches!(ok, AuthDecision::Accept), "{ok:?}");

            let mut b = auth_with(&["*"], &[], &[], &[], Default::default());
            b.trusted_user_ca_blobs = vec![ca_blob];
            b.revoked_keys = Some(std::sync::Arc::new(krl));
            let decision = b.evaluate(AuthAttempt::PublicKey {
                user: "alice".into(),
                algorithm: "ssh-ed25519-cert-v01@openssh.com".into(),
                public_blob: cert_blob,
                probe_only: false,
                verified: true,
                cert: Some(ci),
            });
            assert!(matches!(decision, AuthDecision::Reject), "{decision:?}");
        }

        /// The fixture user key as an `authorized_keys` line.
        const USERKEY_LINE: &str =
            "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINrIw2f/9CPMdm0gq/9PJiCID0Iep+LFikcQCJLkkFR/ test";

        fn cert_attempt(user: &str, ci: &puressh::auth::CertInfo) -> AuthAttempt {
            AuthAttempt::PublicKey {
                user: user.into(),
                algorithm: "ssh-ed25519-cert-v01@openssh.com".into(),
                public_blob: b"cert-blob".to_vec(),
                probe_only: false,
                verified: true,
                cert: Some(ci.clone()),
            }
        }

        // ---- S7: principals= on cert-authority lines ------------------------

        #[test]
        fn cert_authority_line_principals_option_replaces_username_check() {
            let ca = b"fake-ca-blob-1".to_vec();
            // A CA trusted only via the user's own authorized_keys, restricted
            // to certs carrying the `deploy` principal.
            let ak = AuthorizedKeys {
                blobs: Vec::new(),
                cas: vec![(ca.clone(), Some(vec!["deploy".to_string()]))],
                ..Default::default()
            };
            // Cert lists `deploy` but NOT the login user: accepted, because the
            // principals= list replaces the login-user-must-be-a-principal rule.
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = Some(ak.clone());
            let ci = cert_info_for(&ca, &["deploy"]);
            assert!(matches!(
                a.evaluate(cert_attempt("alice", &ci)),
                AuthDecision::Accept
            ));

            // Cert lists the login user but not `deploy`: refused.
            let mut b = auth_with(&["*"], &[], &[], &[], Default::default());
            b.authorized_keys = Some(ak.clone());
            let ci = cert_info_for(&ca, &["alice"]);
            assert!(matches!(
                b.evaluate(cert_attempt("alice", &ci)),
                AuthDecision::Reject
            ));

            // A cert with NO principals never satisfies a principals= list.
            let mut c = auth_with(&["*"], &[], &[], &[], Default::default());
            c.authorized_keys = Some(ak);
            let ci = cert_info_for(&ca, &[]);
            assert!(matches!(
                c.evaluate(cert_attempt("alice", &ci)),
                AuthDecision::Reject
            ));

            // Without principals=, the standard rule applies: login user must
            // be a principal.
            let plain = AuthorizedKeys {
                blobs: Vec::new(),
                cas: vec![(ca.clone(), None)],
                ..Default::default()
            };
            let mut d = auth_with(&["*"], &[], &[], &[], Default::default());
            d.authorized_keys = Some(plain.clone());
            let ci = cert_info_for(&ca, &["alice"]);
            assert!(matches!(
                d.evaluate(cert_attempt("alice", &ci)),
                AuthDecision::Accept
            ));
            let mut e = auth_with(&["*"], &[], &[], &[], Default::default());
            e.authorized_keys = Some(plain);
            let ci = cert_info_for(&ca, &["bob"]);
            assert!(matches!(
                e.evaluate(cert_attempt("alice", &ci)),
                AuthDecision::Reject
            ));

            // An unrelated CA is not trusted at all.
            let mut f = auth_with(&["*"], &[], &[], &[], Default::default());
            f.authorized_keys = Some(AuthorizedKeys::default());
            let ci = cert_info_for(&ca, &["alice"]);
            assert!(matches!(
                f.evaluate(cert_attempt("alice", &ci)),
                AuthDecision::Reject
            ));
        }

        #[test]
        fn principals_option_matching_is_glob() {
            let list = vec!["deploy-*".to_string(), "ops".to_string()];
            assert!(principals_match_option(&list, &["deploy-eu".to_string()]));
            assert!(principals_match_option(
                &list,
                &["x".to_string(), "ops".to_string()]
            ));
            assert!(!principals_match_option(&list, &["dev".to_string()]));
            assert!(!principals_match_option(&list, &[]));
            assert!(!principals_match_option(&[], &["ops".to_string()]));
        }

        #[test]
        fn authorized_keys_principals_option_parsed_from_file() {
            let dir = tempdir_for_test("ak-principals");
            let path = dir.join("authorized_keys");
            std::fs::write(
                &path,
                format!(
                    "cert-authority,principals=\"deploy,ops-*\" {USERKEY_LINE}\n\
                     cert-authority {USERKEY_LINE}\n\
                     cert-authority,principals=\"\" {USERKEY_LINE}\n\
                     {USERKEY_LINE}\n"
                ),
            )
            .expect("write");
            let set =
                load_authorized_keys_and_cas(path.to_str().unwrap(), false, None).expect("load");
            assert_eq!(set.blobs, vec![unhex(USERKEY_BLOB_HEX)]);
            assert_eq!(set.cas.len(), 3);
            assert_eq!(
                set.cas[0].1.as_deref(),
                Some(&["deploy".to_string(), "ops-*".to_string()][..])
            );
            assert_eq!(set.cas[1].1, None);
            // `principals=""` restricts to nothing rather than widening.
            assert_eq!(set.cas[2].1.as_deref(), Some(&[][..]));
            let _ = std::fs::remove_dir_all(&dir);
        }

        // ---- S1: per-user AuthorizedKeysFile -------------------------------

        fn tempdir_for_test(tag: &str) -> std::path::PathBuf {
            use std::sync::atomic::{AtomicU64, Ordering};
            static SEQ: AtomicU64 = AtomicU64::new(0);
            let dir = std::env::temp_dir().join(format!(
                "puressh-sshd-{tag}-{}-{}",
                std::process::id(),
                SEQ.fetch_add(1, Ordering::Relaxed)
            ));
            std::fs::create_dir_all(&dir).expect("mkdir");
            dir
        }

        #[test]
        fn authorized_keys_file_expands_u_token_per_user() {
            let info = lookup_user_for_test();
            let dir = tempdir_for_test("akf");
            // Only the real test user's file carries the key; another user's
            // file (same template) does not exist.
            std::fs::write(dir.join(format!("{}.keys", info.name)), USERKEY_LINE).expect("write");
            let template = format!("{}/%u.keys", dir.display());

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = None; // force the lazy per-user load
            a.authorized_keys_files = vec![template];
            a.strict_modes = false;
            let set = a.resolved_authorized_keys(&info.name).clone();
            assert_eq!(set.blobs, vec![unhex(USERKEY_BLOB_HEX)]);

            // The key authorizes that user…
            let decision = a.evaluate(AuthAttempt::PublicKey {
                user: info.name.clone(),
                algorithm: "ssh-ed25519".into(),
                public_blob: unhex(USERKEY_BLOB_HEX),
                probe_only: false,
                verified: true,
                cert: None,
            });
            assert!(matches!(decision, AuthDecision::Accept), "{decision:?}");

            // …and nobody else: a different (nonexistent-file) user gets an
            // empty set from the same template.
            let mut b = auth_with(&["*"], &[], &[], &[], Default::default());
            b.authorized_keys = None;
            b.authorized_keys_files = a.authorized_keys_files.clone();
            b.strict_modes = false;
            assert!(b.load_authorized_keys_for("root").blobs.is_empty() || info.name == "root");
            let _ = std::fs::remove_dir_all(&dir);
        }

        #[test]
        fn authorized_keys_file_unknown_user_or_bad_template_is_empty() {
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.strict_modes = false;
            a.authorized_keys_files = vec!["/nonexistent/%u".to_string(), "%z".to_string()];
            assert!(
                a.load_authorized_keys_for("\u{0}no-such-user")
                    .blobs
                    .is_empty()
            );
            let info = lookup_user_for_test();
            assert!(a.load_authorized_keys_for(&info.name).blobs.is_empty());
        }

        #[test]
        fn global_authorized_keys_set_is_used_verbatim() {
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = None;
            a.global_authorized_keys = Some(std::sync::Arc::new(AuthorizedKeys {
                blobs: vec![vec![9, 9, 9]],
                cas: Vec::new(),
                ..Default::default()
            }));
            assert_eq!(
                a.resolved_authorized_keys("anyone").blobs,
                vec![vec![9, 9, 9]]
            );
        }

        #[test]
        fn allow_users_default_and_literal_token_rules() {
            assert!(is_literal_user_token("alice"));
            assert!(!is_literal_user_token("dev-*"));
            assert!(!is_literal_user_token("!alice"));
            assert!(!is_literal_user_token("alice@10.*"));
            assert!(!is_literal_user_token(""));
            assert_eq!(
                effective_allow_users(&["a".into()], &["b".into()], Some("me")),
                vec!["a".to_string(), "b".to_string()]
            );
            assert_eq!(
                effective_allow_users(&[], &[], Some("me")),
                vec!["me".to_string()]
            );
            // Nothing configured and no default user ⇒ no AllowUsers
            // restriction (OpenSSH semantics; authentication still decides).
            assert!(effective_allow_users(&[], &[], None).is_empty());
        }

        // ---- S6: Match-block access policy per connection ------------------

        fn conn_policy_for(src: &str) -> std::sync::Arc<ConnPolicy> {
            std::sync::Arc::new(ConnPolicy {
                config: std::sync::Arc::new(
                    puressh::config::SshServerConfig::parse(src).expect("parse config"),
                ),
                cli_allow_users: Vec::new(),
                default_allow_user: Some("me".to_string()),
                cli_permit_root_login: None,
                ca_files: HashMap::new(),
                krls: HashMap::new(),
            })
        }

        #[test]
        fn match_address_deny_users_applies_per_connection() {
            let pol =
                conn_policy_for("AllowUsers alice\nMatch Address 10.0.0.0/8\n  DenyUsers *\n");
            let mut lan =
                auth_with_peer(&["*"], &[], &[], &[], Default::default(), Some("10.1.2.3"));
            lan.policy = Some(pol.clone());
            lan.on_user_resolved("alice", &[]);
            assert!(
                !lan.access_allowed("alice"),
                "DenyUsers inside Match Address must apply"
            );

            let mut wan =
                auth_with_peer(&["*"], &[], &[], &[], Default::default(), Some("192.0.2.1"));
            wan.policy = Some(pol);
            wan.on_user_resolved("alice", &[]);
            assert!(wan.access_allowed("alice"));
            // Global AllowUsers still applies: bob is not listed.
            assert!(!wan.access_allowed("bob"));
        }

        #[test]
        fn match_user_root_login_and_empty_passwords_apply_per_connection() {
            let pol = conn_policy_for(
                "PermitRootLogin yes\nMatch User alice\n  PermitRootLogin no\n  PermitEmptyPasswords yes\n",
            );
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.policy = Some(pol.clone());
            a.on_user_resolved("alice", &[]);
            assert_eq!(a.permit_root_login, puressh::config::PermitRootLogin::No);
            assert!(a.permit_empty_passwords);

            let mut b = auth_with(&["*"], &[], &[], &[], Default::default());
            b.policy = Some(pol);
            b.on_user_resolved("bob", &[]);
            assert_eq!(b.permit_root_login, puressh::config::PermitRootLogin::Yes);
            assert!(!b.permit_empty_passwords);
        }

        #[test]
        fn match_group_allow_groups_uses_group_resolver() {
            let pol = conn_policy_for(
                "AllowUsers carol dave\nMatch Group ops\n  AllowGroups ops\n  DenyGroups contractors\n",
            );
            let mut groups = std::collections::HashMap::new();
            groups.insert(
                "carol".to_string(),
                vec!["ops".to_string(), "contractors".to_string()],
            );
            groups.insert("dave".to_string(), vec!["ops".to_string()]);
            let mut carol = auth_with(&["*"], &[], &[], &[], groups.clone());
            carol.policy = Some(pol.clone());
            carol.on_user_resolved("carol", &[]);
            assert!(
                !carol.access_allowed("carol"),
                "DenyGroups from the matched block applies"
            );
            let mut dave = auth_with(&["*"], &[], &[], &[], groups);
            dave.policy = Some(pol);
            dave.on_user_resolved("dave", &[]);
            assert!(dave.access_allowed("dave"));
        }

        #[test]
        fn match_block_file_paths_select_preloaded_sets() {
            let mut pol_inner = ConnPolicy {
                config: std::sync::Arc::new(
                    puressh::config::SshServerConfig::parse(
                        "TrustedUserCAKeys /ca/global\nMatch User alice\n  TrustedUserCAKeys /ca/alice\n  RevokedKeys /krl/alice\n  AuthorizedKeysFile /keys/%u\n  AuthorizedPrincipalsFile /principals/%u\n",
                    )
                    .expect("parse"),
                ),
                cli_allow_users: Vec::new(),
                default_allow_user: Some("me".to_string()),
                cli_permit_root_login: None,
                ca_files: HashMap::new(),
                krls: HashMap::new(),
            };
            pol_inner.ca_files.insert(
                "/ca/global".into(),
                std::sync::Arc::new(vec![b"g".to_vec()]),
            );
            pol_inner
                .ca_files
                .insert("/ca/alice".into(), std::sync::Arc::new(vec![b"a".to_vec()]));
            let krl = puressh::krl::Krl::parse(&unhex(KRL_EXPLICIT_HEX)).expect("krl");
            pol_inner
                .krls
                .insert(vec!["/krl/alice".into()], std::sync::Arc::new(krl));
            let pol = std::sync::Arc::new(pol_inner);

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.policy = Some(pol.clone());
            a.on_user_resolved("alice", &[]);
            assert_eq!(a.trusted_user_ca_blobs, vec![b"a".to_vec()]);
            assert!(a.revoked_keys.is_some());
            assert_eq!(a.authorized_keys_files, vec!["/keys/%u".to_string()]);
            assert_eq!(
                a.authorized_principals_file.as_deref(),
                Some("/principals/%u")
            );
            assert!(!a.policy_broken);

            let mut b = auth_with(&["*"], &[], &[], &[], Default::default());
            b.policy = Some(pol);
            b.on_user_resolved("bob", &[]);
            assert_eq!(b.trusted_user_ca_blobs, vec![b"g".to_vec()]);
            assert!(b.revoked_keys.is_none());
            assert_eq!(b.authorized_keys_files, default_authorized_keys_files());
        }

        #[test]
        fn match_block_naming_unloaded_file_fails_closed() {
            let pol = conn_policy_for("Match User alice\n  RevokedKeys /krl/missing\n");
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = Some(AuthorizedKeys {
                blobs: vec![unhex(USERKEY_BLOB_HEX)],
                cas: Vec::new(),
                ..Default::default()
            });
            a.policy = Some(pol);
            a.on_user_resolved("alice", &[]);
            assert!(a.policy_broken);
            let decision = a.evaluate(AuthAttempt::PublicKey {
                user: "alice".into(),
                algorithm: "ssh-ed25519".into(),
                public_blob: unhex(USERKEY_BLOB_HEX),
                probe_only: false,
                verified: true,
                cert: None,
            });
            assert!(matches!(decision, AuthDecision::Reject));
        }

        // ---- S3/S4: parent-side child accounting ---------------------------

        #[test]
        fn child_table_caps_count_unauthenticated_and_per_ip_for_lifetime() {
            let ip4: IpAddr = "10.0.0.1".parse().unwrap();
            let peer_a: std::net::SocketAddr = "10.0.0.1:1000".parse().unwrap();
            let peer_b: std::net::SocketAddr = "10.0.0.2:1000".parse().unwrap();
            let mut t = ChildTable::default();
            t.insert(Pid::from_raw(100_001), ip4, None);
            t.insert(Pid::from_raw(100_002), ip4, None);
            assert_eq!(t.len(), 2);
            assert_eq!(t.unauthenticated(), 2);
            assert_eq!(t.count_from_ip(ip4), 2);
            // MaxStartups over unauthenticated children.
            assert_eq!(t.admit(&peer_b, 2, None, 0), Err("max-startups"));
            assert_eq!(t.admit(&peer_b, 3, None, 0), Ok(()));
            // Per-source cap over live children from that IP.
            assert_eq!(t.admit(&peer_a, 0, None, 2), Err("per-source-max"));
            assert_eq!(t.admit(&peer_b, 0, None, 2), Ok(()));
            // An authenticated child leaves the MaxStartups count but keeps
            // its per-IP slot for life.
            t.children
                .get_mut(&Pid::from_raw(100_001))
                .unwrap()
                .authenticated = true;
            assert_eq!(t.unauthenticated(), 1);
            assert_eq!(t.admit(&peer_b, 2, None, 0), Ok(()));
            assert_eq!(t.admit(&peer_a, 0, None, 2), Err("per-source-max"));
            // Caps of 0 are unlimited.
            assert_eq!(t.admit(&peer_a, 0, None, 0), Ok(()));
            // MaxStartups start:rate:full: 1 unauthenticated child, start 1 at
            // rate 100 ⇒ always dropped; start 2 ⇒ never.
            assert!(t.admit(&peer_b, 10, Some((1, 100)), 0).is_err());
            assert_eq!(t.admit(&peer_b, 10, Some((2, 100)), 0), Ok(()));
            assert_eq!(t.admit(&peer_b, 10, Some((1, 0)), 0), Ok(()));
        }

        #[test]
        fn child_table_auth_pipe_and_reap_with_real_child() {
            // Fork a real child that reports auth success through the pipe
            // exactly as the session-open hook does, then exits. The parent
            // must see it move to "authenticated" and then be reaped (per-IP
            // slot released).
            let ip: IpAddr = "192.0.2.7".parse().unwrap();
            let (rx, tx) = pipe_cloexec().expect("pipe");
            AUTH_NOTIFY_FD.store(tx.as_raw_fd(), Ordering::Relaxed);
            // SAFETY: single-threaded test child; it only writes a byte and exits.
            let pid = match unsafe { fork() }.expect("fork") {
                ForkResult::Child => {
                    core::mem::forget(tx);
                    notify_parent_authenticated();
                    unsafe { libc::_exit(0) };
                }
                ForkResult::Parent { child } => child,
            };
            AUTH_NOTIFY_FD.store(-1, Ordering::Relaxed);
            drop(tx);
            let mut t = ChildTable::default();
            t.insert(pid, ip, Some(rx));
            assert_eq!(t.unauthenticated(), 1);
            // Wait for the byte (bounded), then collect it.
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
            while t.unauthenticated() == 1 && std::time::Instant::now() < deadline {
                t.poll_auth();
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            assert_eq!(t.unauthenticated(), 0, "auth notification not received");
            assert_eq!(t.count_from_ip(ip), 1, "per-IP slot held until reaped");
            // Now reap: the child has exited.
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
            while t.len() == 1 && std::time::Instant::now() < deadline {
                t.reap(false, &mut Penalties::new(&Default::default()));
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            assert_eq!(t.len(), 0, "exited child not reaped");
            assert_eq!(t.count_from_ip(ip), 0);
        }

        #[test]
        fn penalties_accumulate_activate_and_exempt() {
            let cfg = puressh::config::SshServerConfig::parse(
                "PerSourcePenalties authfail:300s min:350s max:900s noauth:1\n\
                 PerSourcePenaltyExemptList 10.0.0.0/8\nPerSourceNetBlockSize 24:64\n",
            )
            .unwrap();
            let mut p = Penalties::new(&cfg.global);
            let a: IpAddr = "192.0.2.7".parse().unwrap();
            let neighbour: IpAddr = "192.0.2.99".parse().unwrap();
            // Below `min`: recorded, not yet refusing.
            p.penalise(a, PenaltyKind::AuthFail, false);
            assert_eq!(p.refuses(a), None);
            // Accumulated past it: the whole /24 is refused.
            p.penalise(a, PenaltyKind::AuthFail, false);
            assert_eq!(p.refuses(neighbour), Some("penalty: failed authentication"));
            assert_eq!(p.refuses("192.0.3.1".parse().unwrap()), None);
            // Exempt sources are never penalised.
            let exempt: IpAddr = "10.1.2.3".parse().unwrap();
            for _ in 0..5 {
                p.penalise(exempt, PenaltyKind::AuthFail, false);
            }
            assert_eq!(p.refuses(exempt), None);
            // Off: nothing is refused.
            let off = puressh::config::SshServerConfig::parse("PerSourcePenalties no\n").unwrap();
            let mut p = Penalties::new(&off.global);
            for _ in 0..5 {
                p.penalise(a, PenaltyKind::AuthFail, false);
            }
            assert_eq!(p.refuses(a), None);
            // How a pre-auth process ended decides the penalty.
            let pid = Pid::from_raw(1);
            assert_eq!(
                penalty_for(&WaitStatus::Exited(pid, EXIT_AUTH_ATTEMPTED), false),
                Some(PenaltyKind::AuthFail)
            );
            assert_eq!(
                penalty_for(&WaitStatus::Exited(pid, 255), false),
                Some(PenaltyKind::NoAuth)
            );
            assert_eq!(penalty_for(&WaitStatus::Exited(pid, 255), true), None);
            assert_eq!(
                penalty_for(&WaitStatus::Signaled(pid, Signal::SIGSEGV, false), false),
                Some(PenaltyKind::Crash)
            );
        }

        #[test]
        fn child_table_pipe_closed_without_success_stays_unauthenticated() {
            let ip: IpAddr = "192.0.2.8".parse().unwrap();
            let (rx, tx) = pipe_cloexec().expect("pipe");
            let mut t = ChildTable::default();
            t.insert(Pid::from_raw(100_003), ip, Some(rx));
            // Peer "exits pre-auth": write end closed with no byte.
            drop(tx);
            // Poll until the hang-up is observed rather than once: a sibling
            // test in this binary forks a real child, and `fork` copies every
            // open descriptor — including our `tx` — into it (close-on-exec
            // only applies at `exec`). Until that child exits the pipe still
            // has a writer and `poll` reports nothing, which made this test
            // flake on CI when the two ran concurrently.
            let pid = Pid::from_raw(100_003);
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
            while t.children[&pid].auth_rx.is_some() && std::time::Instant::now() < deadline {
                t.poll_auth();
                std::thread::sleep(std::time::Duration::from_millis(5));
            }
            assert_eq!(t.unauthenticated(), 1);
            assert!(
                t.children[&pid].auth_rx.is_none(),
                "pipe hang-up never observed"
            );
        }

        // ---- Multi-step keyboard-interactive bridge ------------------------
        //
        // These drive the LocalAuthenticator's kbd-interactive state machine
        // through the real `pam_gate::KbdConversation` channel protocol via a
        // scripted *fake* worker (no real PAM module needed). Gated to the
        // Linux+PAM build, where the conversation type and its test helper
        // live.

        #[cfg(all(feature = "pam", target_os = "linux"))]
        #[test]
        fn kbd_interactive_two_prompt_accept() {
            use std::sync::{Arc, Mutex};
            let received = Arc::new(Mutex::new(Vec::new()));
            let script = vec![
                (String::new(), "Password: ".to_string(), false),
                ("One-time code".to_string(), "OTP: ".to_string(), false),
            ];
            let conv = pam_gate::KbdConversation::fake_for_test(script, true, received.clone());

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.kbd_interactive_enabled = true;
            a.permit_empty_passwords = false;
            let _ = a.check_user_binding("alice");
            a.kbd_conv = Some(conv);
            a.pending_first_prompt = true;

            // First pump: PAM asked the password prompt.
            match a.kbd_pump("alice") {
                AuthDecision::InteractiveRequest { prompts, .. } => {
                    assert_eq!(prompts, vec![("Password: ".to_string(), false)]);
                }
                other => panic!("expected first prompt, got {other:?}"),
            }
            // Answer it → second prompt (OTP), with instruction text attached.
            match a.evaluate_interactive("alice", vec!["hunter2".to_string()]) {
                AuthDecision::InteractiveRequest {
                    prompts,
                    instruction,
                    ..
                } => {
                    assert_eq!(prompts, vec![("OTP: ".to_string(), false)]);
                    assert_eq!(instruction, "One-time code");
                }
                other => panic!("expected second prompt, got {other:?}"),
            }
            // Answer the OTP → PAM Done(true) → Accept (single-factor: no
            // chains; alice is allowed by "*", non-root).
            assert!(matches!(
                a.evaluate_interactive("alice", vec!["123456".to_string()]),
                AuthDecision::Accept
            ));
            // Both answers were threaded to the worker in order.
            assert_eq!(
                *received.lock().unwrap(),
                vec![b"hunter2".to_vec(), b"123456".to_vec()]
            );
            // Conversation cleared after the terminal verdict.
            assert!(a.kbd_conv.is_none());
        }

        #[cfg(all(feature = "pam", target_os = "linux"))]
        #[test]
        fn kbd_interactive_pam_reject() {
            use std::sync::{Arc, Mutex};
            let received = Arc::new(Mutex::new(Vec::new()));
            let script = vec![(String::new(), "Password: ".to_string(), false)];
            let conv = pam_gate::KbdConversation::fake_for_test(script, false, received);

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.kbd_interactive_enabled = true;
            let _ = a.check_user_binding("alice");
            a.kbd_conv = Some(conv);
            a.pending_first_prompt = true;

            assert!(matches!(
                a.kbd_pump("alice"),
                AuthDecision::InteractiveRequest { .. }
            ));
            // Wrong answer → PAM Done(false) → Reject.
            assert!(matches!(
                a.evaluate_interactive("alice", vec!["wrong".to_string()]),
                AuthDecision::Reject
            ));
            assert!(a.kbd_conv.is_none());
        }

        #[cfg(all(feature = "pam", target_os = "linux"))]
        #[test]
        fn kbd_interactive_empty_password_refused() {
            use std::sync::{Arc, Mutex};
            let received = Arc::new(Mutex::new(Vec::new()));
            let script = vec![(String::new(), "Password: ".to_string(), false)];
            // Verdict would be accept, but the empty-password policy must short-
            // circuit BEFORE the worker ever sees the answer.
            let conv = pam_gate::KbdConversation::fake_for_test(script, true, received.clone());

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.kbd_interactive_enabled = true;
            a.permit_empty_passwords = false;
            let _ = a.check_user_binding("alice");
            a.kbd_conv = Some(conv);
            a.pending_first_prompt = true;

            assert!(matches!(
                a.kbd_pump("alice"),
                AuthDecision::InteractiveRequest { .. }
            ));
            // Empty first answer ⇒ refused without consulting the worker.
            assert!(matches!(
                a.evaluate_interactive("alice", vec![String::new()]),
                AuthDecision::Reject
            ));
            assert!(received.lock().unwrap().is_empty());
            assert!(a.kbd_conv.is_none());
        }

        #[cfg(all(feature = "pam", target_os = "linux"))]
        #[test]
        fn kbd_interactive_username_change_rejected() {
            use std::sync::{Arc, Mutex};
            let received = Arc::new(Mutex::new(Vec::new()));
            let script = vec![(String::new(), "Password: ".to_string(), false)];
            let conv = pam_gate::KbdConversation::fake_for_test(script, true, received);

            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.kbd_interactive_enabled = true;
            let _ = a.check_user_binding("alice");
            a.kbd_conv = Some(conv);
            a.pending_first_prompt = true;
            assert!(matches!(
                a.kbd_pump("alice"),
                AuthDecision::InteractiveRequest { .. }
            ));
            // A response that claims a different user mid-conversation ⇒ reject.
            assert!(matches!(
                a.evaluate_interactive("mallory", vec!["x".to_string()]),
                AuthDecision::Reject
            ));
        }

        #[test]
        fn krl_absent_allows_authorized_plain_key() {
            // Sanity: the same authorized key WITHOUT a KRL is accepted, so the
            // rejection above is attributable to revocation, not the harness.
            let blob = unhex(USERKEY_BLOB_HEX);
            let mut a = auth_with(&["*"], &[], &[], &[], Default::default());
            a.authorized_keys = Some(AuthorizedKeys {
                blobs: vec![blob.clone()],
                cas: Vec::new(),
                ..Default::default()
            });
            let decision = a.evaluate(AuthAttempt::PublicKey {
                user: "alice".into(),
                algorithm: "ssh-ed25519".into(),
                public_blob: blob,
                probe_only: false,
                verified: true,
                cert: None,
            });
            assert!(matches!(decision, AuthDecision::Accept));
        }
    }
}