summaryrefslogtreecommitdiff
path: root/scripts/test-kernel-security.py
blob: 6b8a6fea14f9cfaf442b8ccd7b348c708fbd6ffa (plain)
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
#!/usr/bin/env python3
#
#    kernel-security.py regression testing script for kernel and
#    security features
#
#    Copyright (C) 2008-2016 Canonical Ltd.
#    Author: Kees Cook <kees@ubuntu.com>
#    Author: Steve Beattie <steve.beattie@canonical.com>
#    Author: Marc Deslauriers <marc.deslauriers@canonical.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 3,
#    as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# QRT-Packages: build-essential sudo gdb gawk libcap-dev
# QRT-Packages: linux-headers-`UNAME-R`
# the follow is needed when the ORC unwinder is enabled
# QRT-Packages: libelf-dev
# QRT-Alternates: libcap2-bin libcap-bin
# QRT-Alternates: e2fslibs-dev
# QRT-Alternates: gcc-multilib
# QRT-Alternates: nfct
# QRT-Privilege: root
#
# 6.06 dapper 2.6.15
# 6.10 edgy 2.6.18
# 7.04 feisty 2.6.20
# 7.10 gutsy 2.6.22 (is this wrong? was it .23?)
# 8.04 hardy 2.6.24
# 8.10 intrepid 2.6.27
# 9.04 jaunty 2.6.28
# 9.10 karmic 2.6.31
# 10.04 lucid 2.6.32
# 10.10 maverick 2.6.35
# 11.04 natty 2.6.38
# 11.10 oneiric 3.0.0
# 12.04 precise 3.2.0
# ...
# 14.04 trusty 3.13
# ...
# 15.10 wily 4.2
# 16.04 xenial 4.4
# 16.10 yakkety 4.6?

'''
    This expects to be run under sudo, or at least running as root, with
    the "SUDO_USER" environment variable set to a non-root user.
'''

# QRT-Depends: kernel-security private/qrt/kernel_security.py

###########################################################################
#
# TODO: Tests to add
#
# 1) make sure the kernel supports builtin revoked certificates for
#    secure boot; see LP: #1932029 . Essentially, want to ensure that
#    `sudo keyctl list %:.blacklist` does not contain zero entries, at
#    least on amd64. Further enhancement would be to parse the output
#    and confirm its expexted values.
#
###########################################################################

import gzip
import os
import re
import resource
import shutil
import signal
import socket
import subprocess
import tempfile
import time
import unittest

import testlib

try:
    from private.qrt.kernel_security import PrivateKernelSecurityTest
except ImportError:
    class PrivateKernelSecurityTest(object):
        '''Empty class'''


class KPTRValues(object):
    (ALLOWED,       # both root and user can see kernel addresses
     RESTRICTED,    # only root can see kernel addresses,
                    # unless kptr_restrict is unset
     KPTR_STRICT,   # only root can see kernel addresses, regardless
                    # of  kptr_restrict setting
     ALWAYS_ZERO,   # kernel addresses are always zeroed
    ) = list(range(1, 5))


class KernelSecurityBaseTest(testlib.TestlibCase):
    '''Base class for testing  kernel security features'''

    def setUp(self):
        '''Set up prior to each test_* function'''
        self.fs_dir = os.path.abspath('.')
        os.chdir('kernel-security')

        self.arm_archs = ['armel', 'armhf']

        self.aslr_archs = ['i386', 'amd64', 'ppc64el', 'arm64', 's390x']
        if self.kernel_at_least('2.6.35'):
            self.aslr_archs += ['armel', 'armhf']

        self.seccomp_filter_archs = list()
        if self.kernel_at_least('3.0') and not self.kernel_at_least('3.2'):
            self.seccomp_filter_archs += ['i386', 'amd64']

        self.module_ronx_archs = ['i386', 'amd64', 's390x']
        # possibly support for DEBUG_SET_MODULE_RONX was added and
        # enabled on kernels earlier than 4.4
        if self.kernel_at_least('4.4'):
            self.module_ronx_archs += ['arm64']

        # STRICT_MODULE_RWX is supported on ppc since 5.15
        if self.kernel_at_least('5.15'):
            self.module_ronx_archs += ['ppc64el']


        self.sysctl = dict()
        self.sysctl['hardlink'] = 'kernel/yama/protected_nonaccess_hardlinks'
        self.sysctl['symlink'] = 'kernel/yama/protected_sticky_symlinks'
        if self.kernel_at_least('3.6'):
            self.sysctl['hardlink'] = 'fs/protected_hardlinks'
            self.sysctl['symlink'] = 'fs/protected_symlinks'

        self._config_lines_cache = None

        with open("/proc/cpuinfo") as proc_cpuinfo:
            self.cpu_flags = [x[x.find(': ') + 2:] for x in proc_cpuinfo if x.startswith('flags\t')]
        if len(self.cpu_flags) != 0:
            self.cpu_flags = self.cpu_flags[0].split(' ')

        # Record current stack rlimit
        self.old_stack_limit = resource.getrlimit(resource.RLIMIT_STACK)

        # Prepare for per-test teardowns
        self.teardowns = []

    def tearDown(self):
        '''Clean up after each test_* function'''
        os.chdir(self.fs_dir)

        # Restore any changes to stack rlimit
        resource.setrlimit(resource.RLIMIT_STACK, self.old_stack_limit)

        # Handle per-test teardowns
        for func in self.teardowns:
            func()

    def _get_sym(self, sym):
        '''Find a kernel symbol from System.map'''
        systemmap = '/boot/System.map-%s' % (self.kernel_version)
        for line in open(systemmap):
            addr, kind, name = line.strip().split()
            if name == sym:
                return addr
        self.assertTrue(False, "Could not find '%s' in '%s'" % (sym, systemmap))

    def _open_config(self):
        name = "/proc/config.gz"
        if os.path.exists(name):
            return gzip.open(name, "rt")
        for name in ["/boot/config-%s" % (self.kernel_version),
                     "/boot/config"]:
            if os.path.exists(name):
                return open(name, "r")
        self.assertTrue(False, "Could not locate kernel configuration")

    def _config_lines(self):
        # Return cached config list or open and read it.
        if self._config_lines_cache is None:
            config_fh = self._open_config()
            self._config_lines_cache = config_fh.readlines()
            config_fh.close()
        return self._config_lines_cache

    def _get_config(self, name):
        '''Report a specific CONFIG_ option in the running kernel config'''
        for line in self._config_lines():
            if line.startswith('CONFIG_%s=' % (name)):
                return line.split('=', 1)[1].strip()
        return None

    def _test_config(self, name):
        '''Look for a specific CONFIG_ option being enabled in the running kernel config'''
        setting = self._get_config(name)
        if setting == 'y' or setting == 'm':
            return True
        return False

    def reportConfig(self, name, message):
        '''Report the specific setting of a kernel config for situations
           where we don't expect it to be enabled, but don't care if it
           is'''
        self._skipped('%s\nActual config setting: %s=%s' % (message, name, self._get_config(name)))

    def assertKernelConfigSet(self, name, nomodule=False):
        '''Look for a specific CONFIG_ option being enabled in the running
           kernel config and fail the test if it's unset'''
        if nomodule:
            self.assertEqual(self._get_config(name), 'y',
                             "%s option was expected to be set to 'y' in the kernel config" % name)
        else:
            self.assertTrue(self._test_config(name),
                            '%s option was expected to be set in the kernel config' % name)

    def assertKernelConfigUnset(self, name):
        '''Look for a specific CONFIG_ option to be unset in the
           running kernel config and fail the test if it's set'''
        self.assertFalse(self._test_config(name),
                         '%s option was expected to be unset in the kernel config' % name)

    def assertKernelConfig(self, name, expected):
        '''Look for a specific CONFIG_ option being enabled in the running
           kernel config and fail the test if not the expected result'''

        if expected:
            self.assertKernelConfigSet(name)
        else:
            self.assertKernelConfigUnset(name)

    def _get_all_kernel_modules(self):
        kernel_modules = []
        for root, dirnames, filenames in os.walk(os.path.join('/lib/modules', self.kernel_version, 'kernel')):
            for filename in filenames:
                if filename.endswith(".ko"):
                    kernel_modules.append(os.path.join(root, filename))

        return kernel_modules

    def _unpriv_cmd(self, cmd):
        return ['sudo', '-u', os.environ['SUDO_USER']] + cmd


class KernelSecurityTest(KernelSecurityBaseTest):
    '''Test kernel security features'''

    # Clean up all builds here, and make them on a per-test basis.
    def test_000_make(self):
        '''Prepare to build helper tools'''

        self.announce("%s" % (self.gcc_version))
        self.assertShellExitEquals(0, ["make", "clean"])
        # Something might be keeping "gawk" from being the default AWK
        # implementation, so make sure it is set for the kernel build.
        self.assertShellExitEquals(0, ["update-alternatives",
                                       "--set", "awk", "/usr/bin/gawk"])

    # Feisty(?) and newer
    def test_010_proc_maps(self):
        '''/proc/$pid/maps is correctly protected (CVE-2013-2929)'''

        expected = 0
        if not self.kernel_at_least('2.6.22'):
            self._skipped("only Feisty and later")
            expected = 1

        os.chdir('proc-maps')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], "./maps-protection.py", "-v"])

    # Hardy and newer
    def test_030_mmap_min(self):
        '''Low memory allocation respects mmap_min_addr'''

        wanted = 65536
        if self.dpkg_arch in self.arm_archs or self.dpkg_arch == 'arm64':
            wanted = 32768
        self.announce("%d" % (wanted))

        expected = 0
        if not self.kernel_at_least('2.6.24'):
            self._skipped("only Hardy and later")
            expected = 1
            mmap_limit = 0
        else:
            mmap_limit = self._test_sysctl_value('vm/mmap_min_addr', wanted, "is wine or qemu-kvm-extras-static installed?")

        os.chdir('min-addr')
        self.assertShellExitEquals(0, ["make"])

        # Karmic's ec2 reports the wrong value in mmap_min_addr, but enforces 65536.
        if self.lsb_release['Release'] == 9.10 and self.kernel_version.endswith('-ec2'):
            wanted = 65536

        # on arm64 machines with 64K pages enabled, even if
        # mmap_min_addr is set to 32K, it will enforce it as if it
        # was set to 64K. See LP:#1931393.
        if self._test_config('ARM64_64K_PAGES'):
            self.announce("arm kernel with 64K pages configured (LP:#1931393")
            wanted = 65536

        # Test minimum is enforced
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], "./low-mmap", '%d' % (wanted)])

        # Test that zero is still possible
        self.assertShellExitEquals(1, ["./zero-possible", '%d' % (mmap_limit)], msg="Unable to allocate zero-page when mmap_min_addr set to 0!\n")

        # MMAP_PAGE_ZERO is cleared unconditionally (CVE-2009-1895)
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], "./mappage0", '%d' % (wanted)])

    # Gutsy and newer
    def test_031_apparmor(self):
        '''AppArmor loaded'''

        expected = True
        if not self.kernel_at_least('2.6.22'):
            self._skipped("only Gutsy and later")
            expected = False
        else:
            if self.dpkg_arch in self.arm_archs and \
               not self.kernel_at_least('2.6.31'):
                self._skipped("on ARM only Lucid and later")
                expected = False
        self.assertEqual(os.path.exists('/sys/kernel/security/apparmor'), expected)

    # Hardy and newer
    def test_031_seccomp(self):
        '''PR_SET_SECCOMP works'''

        expected = -9
        if not self.kernel_at_least('2.6.24'):
            self._skipped("only Hardy and later")
            expected = 10
        else:
            if self.dpkg_arch in self.arm_archs and \
               not self.kernel_at_least('2.6.35'):
                self._skipped("not available on ARM")
                expected = 10
            if self.dpkg_arch == 'arm64' and \
               not self.kernel_at_least('3.19.0'):
                self._skipped("not available on ARM64")
                expected = 10
            if self.kernel_version.endswith('-ec2') or self.kernel_version.endswith('-virtual') or self.kernel_version.endswith('-xen'):
                self._skipped('LP: #725089')
                return

        os.chdir('seccomp')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, ["./seccomp"])

    # Hardy and newer
    def test_032_dev_kmem(self):
        '''/dev/kmem not available'''

        expected = 6  # No such device
        if not self.kernel_at_least('2.6.24'):
            self._skipped("only Hardy and later")
            expected = 14  # Bad address
        if self.lsb_release['Release'] == 9.10 and self.kernel_version.endswith('-ec2'):
            self._skipped("ignored on Karmic EC2")
            expected = 14  # Bad address
        if not self.kernel_at_least('2.6.22'):
            expected = 1  # Operation not permitted on Gutsy

        self.assertShellExitEquals(0, ["./errno-read.py", '/dev/zero', '4096'])

        dir = tempfile.mkdtemp(prefix='kmem-', dir='/dev/')
        kmem = os.path.join(dir, 'kmem')
        self.assertShellExitEquals(0, ['/bin/mknod', kmem, 'c', '1', '2'])
        self.assertTrue(os.path.exists(kmem))
        self.assertShellExitEquals(expected, ["./errno-read.py", kmem, '4096'])
        os.unlink(kmem)
        os.rmdir(dir)

    # Jaunty and newer
    def test_033_syn_cookies(self):
        '''SYN cookies is enabled'''

        expected = 1
        if not self.kernel_at_least('2.6.28'):
            self._skipped("only Jaunty and later")
            expected = 0

        self._test_sysctl_value('net/ipv4/tcp_syncookies', expected)

    # All kernels
    def test_040_pcaps(self):
        # FIXME: tighten the check to make sure more caps can't be added/lost
        '''init's CAPABILITY list is clean'''

        getpcaps = None
        for item in ['/sbin/getpcaps', '/usr/sbin/getpcaps']:
            if os.path.exists(item):
                getpcaps = item
        self.assertTrue(getpcaps is not None, "getpcaps missing (please install libcap-bin)")

        okay_removed = ['cap_sys_module', 'cap_sys_rawio', 'cap_setpcap']
        required_removed = []
        # CONFIG_SECURITY_FILE_CAPABILITIES was removed in 2.6.33
        if not self.kernel_at_least('2.6.33'):
            required_removed = ['cap_setpcap']

        rc, output = self.shell_cmd([getpcaps, '1'])
        self.assertEqual(rc, 0, output)
        # Capabilities for `1': =ep cap_sys_module,cap_sys_rawio-ep
        # libcap2 in focal drops the 'Capabilities for' prefix
        if self.lsb_release['Release'] < 20.04:
            self.assertTrue(output.startswith("Capabilities"), output)
        else:
            self.assertTrue(output.startswith("1:"), output)

        parts = output.strip().split(': ', 1)[1].split()
        self.assertTrue(len(parts) == 1 or len(parts) == 2, output)
        caps_removed = []
        if len(parts) == 1:
            self.assertEqual(parts[0], '=ep', output)
        elif len(parts) == 2:
            self.assertTrue(parts[0] == '=ep' or parts[0] == '=', output)
            if parts[1].endswith('-ep') or parts[1].endswith('-e'):
                caps_removed = parts[1].split('-', 1)[0].split(',')
            elif parts[1].endswith('+ep') or parts[1].endswith('+e'):
                # if cap list has +ep, we need to figure out which caps,
                # if any have been dropped; we do this be enumerating
                # all available caps and searching for each one in the
                # list of granted caps
                caps_added = parts[1].split('+', 1)[0].split(',')
                all_caps = testlib.enumerate_capabilities()
                for cap in all_caps:
                    if cap not in caps_added:
                        caps_removed.append(cap)
            else:
                raise self.failureException('Unknown capabilities suffix: %s' % output)

        okay = True
        for cap in required_removed:
            if cap not in caps_removed:
                okay = False
            else:
                caps_removed.remove(cap)
        for cap in caps_removed:
            if cap not in okay_removed:
                okay = False

        self.assertTrue(okay, "init capability mismatch (removals required: %s; removals okay: %s) -- got: %s" % (",".join(required_removed), ",".join(okay_removed), output))

    # Hardy and newer
    def test_050_personality(self):
        '''init missing READ_IMPLIES_EXEC'''
        # This is really only a concern for ia32, but it doesn't hurt to
        # check all architectures.  READ_IMPLIES_EXEC causes all PROT_READ
        # mmap calls to silently gain PROT_EXEC as well.  PROT_EXEC can also
        # be gained via ELF headers (readelf -l BIN).

        # ARM64 currently has READ_IMPLIES_EXEC set, see LP: #1501645

        expected = False
        if self.dpkg_arch == 'i386' and not self.kernel_at_least('2.6.24'):
            self._skipped("only non-i386 or Hardy and later")
            expected = True

        if not os.path.exists('/proc/1/personality'):
            self.announce("heap check")
            # So, there doesn't seem to be a way to query personality bits
            # prior to Jaunty.  As a work-around, we can examine the [heap]
            # section of init and verify that it lacks "x".
            rc, output = self.shell_cmd(['cat', '/proc/1/maps'])
            self.assertEqual(rc, 0, "Got %d (expected %d):\n%s" % (rc, 0, output))
            heap_exec = None
            for line in output.splitlines():
                line = line.strip()
                if '[heap]' in line:
                    perms = line.split(' ')[1]
                    if len(perms) == 4 and perms[0] == 'r' and perms[1] == 'w':
                        if perms[2] == 'x':
                            heap_exec = True
                        else:
                            heap_exec = False
            self.assertEqual(heap_exec, expected, "Heap executable?  Got %d (expected %d):\n%s" % (heap_exec, expected, output))
        else:
            self.announce("/proc/1/personality")
            rc, output = self.shell_cmd(['cat', '/proc/1/personality'])
            self.assertEqual(rc, 0, "Got %d (expected %d):\n%s" % (rc, 0, output))
            expected = '00000000'
            # ARM sets ADDR_LIMIT_32BIT
            if self.dpkg_arch in self.arm_archs:
                expected = '00800000'

            output = output.strip()
            self.assertEqual(output, expected, "/proc/1/personality contains %s (expected %s)" % (output, expected))

    # All kernels
    def test_060_nx(self):
        '''NX bit is working'''

        has_nx_flag = 'nx' in self.cpu_flags

        # Start by assuming fully functional NX hardware.
        stack_expected = expected = -11
        emulated = False
        if self.lsb_release['Distributor ID'] == "Ubuntu":
            if self.dpkg_arch == 'i386':
                if self._test_config('X86_PAE'):
                    if not has_nx_flag:
                        # i386, PAE, without NX hardware
                        if not self.kernel_at_least('2.6.31') or \
                           self.lsb_release['Release'] > 12.04:
                            # without NX emulation
                            self._skipped("CPU is not NX capable")
                            stack_expected = expected = 0
                        else:
                            # with NX emulation
                            self.announce("NX emulation, PIE-bss/data unsafe")
                            emulated = True
                    else:
                        # i386, PAE, with NX hardware
                        pass
                elif not self.kernel_at_least('2.6.31') or \
                     self.lsb_release['Release'] > 12.04:
                    # i386, no PAE, without NX emulation
                    self._skipped("Kernel lacks NX emulation")
                    stack_expected = expected = 0
                else:
                    # i386, no PAE, with NX emulation
                    self.announce("NX emulation, PIE-bss/data unsafe")
                    emulated = True
            elif self.dpkg_arch == 'amd64':
                if not has_nx_flag:
                    # x86_64 (PAE), without NX hardware
                    self._skipped("CPU is not NX capable")
                    stack_expected = expected = 0
                else:
                    # x86_64 (PAE), with NX hardware
                    pass
            elif self.dpkg_arch == 'arm64' and not self.kernel_at_least('4.4'):
                # this is LP: #1501645 / fixed in xenial(?) according to LP: #1665588
                self._skipped("ARM64 older than 4.4 used to have READ_IMPLIES_EXEC personality set, but no longer?")
                # stack is still no-exec
                # expected = 0
            elif self.dpkg_arch == 's390x':
                # Need to figure out nx-test assembly code for s390x
                # s390 has no dedicated RETURN code, usually it's an
                # unconditional branch to the contents of R14
                self._skipped("need to figure out return assembly code for s390x")
                return

        os.chdir('nx')
        self.assertShellExitEquals(0, ["make"])

        self.assertShellExitEquals(0, ["./nx-test", "mmap-exec"])
        self.assertShellExitEquals(expected, ["./nx-test", "data"])
        self.assertShellExitEquals(expected, ["./nx-test", "bss"])
        self.assertShellExitEquals(stack_expected, ["./nx-test", "stack"])
        self.assertShellExitEquals(expected, ["./nx-test", "brk"])
        self.assertShellExitEquals(expected, ["./nx-test", "mmap"])

        rie_expected = 0
        if self.dpkg_arch == 'ppc64el' or \
           self.dpkg_arch in ['amd64', 'arm64', 'armhf'] and self.kernel_at_least('5.8'):
            # On ppc64el marking stack executable doesn't imply that
            # all other sections will be executable. This is also true
            # for amd64 and arm64 starting in linux 5.8 with commit
            # ac7b34218a0021bafd1d4c11c54217b930f516b0, and for
            # armhf when the CPU supports NX.
            rie_expected = -11
        elif self.dpkg_arch in ['amd64', 'arm64'] and self.kernel_at_least('5.4'):
            # oracle 5.4 cloud kernels as of 5.4.0-1045.49 now include a
            # backport of ac7b34218a0021bafd1d4c11c54217b930f516b0,
            # which was necessary for improved arm support, I guess.
            # https://bugs.launchpad.net/qa-regression-testing/+bug/1928021
            # The same applies to gke...
            for flavour in ('-oracle', '-gke'):
                if self.kernel_version.endswith(flavour):
                    rie_expected = -11
            # And gcp kernels with its FIPS derivatives.
            if 'gcp' in self.kernel_version:
                rie_expected = -11

        # These will all work since READ_IMPLIES_EXEC gets set
        self.assertShellExitEquals(0, ["./nx-test-rie", "mmap-exec"])
        self.assertShellExitEquals(0, ["./nx-test-rie", "stack"])
        self.assertShellExitEquals(rie_expected, ["./nx-test-rie", "data"])
        self.assertShellExitEquals(rie_expected, ["./nx-test-rie", "bss"])
        self.assertShellExitEquals(rie_expected, ["./nx-test-rie", "brk"])
        self.assertShellExitEquals(rie_expected, ["./nx-test-rie", "mmap"])

        # Should always work sanely when PIE
        self.assertShellExitEquals(0, ["./nx-test-pie", "mmap-exec"])
        self.assertShellExitEquals(stack_expected, ["./nx-test-pie", "stack"])
        self.assertShellExitEquals(expected, ["./nx-test-pie", "mmap"])
        self.assertShellExitEquals(expected, ["./nx-test-pie", "brk"])
        # Can fail with emulation + PIE
        if emulated:
            for region in ['data', 'bss']:
                failed = False
                for i in range(0, 50):
                    rc, out = self.shell_cmd(["./nx-test-pie", region])
                    if rc == 0:
                        failed = True
                        break
                self.assertTrue(failed == emulated, "Emulation unexpectedly never failed %s region" % (region))
        else:
            self.assertShellExitEquals(expected, ["./nx-test-pie", "data"])
            self.assertShellExitEquals(expected, ["./nx-test-pie", "bss"])

    # All kernels
    def test_061_guard_page(self):
        '''Userspace stack guard page exists (CVE-2010-2240)'''

        os.chdir('guard-page')
        self.assertShellExitEquals(0, ["make"])

        # behavior changed in 3.19 kernel with:
        # commit 9c145c56d0c8a0b62e48c8d71e055ad0fb2012ba
        # Author: Linus Torvalds <torvalds@linux-foundation.org>
        # Date:   Thu Jan 29 11:15:17 2015 -0800
        #     vm: make stack guard page errors return VM_FAULT_SIGSEGV rather than SIGBUS
        expected_signals = [-signal.SIGSEGV, -signal.SIGBUS]

        self.assertShellExitIn(expected_signals, ["./guard-page"])

    def test_062_guard_page_split(self):
        '''Make sure the stack guard page does not split the stack on mlock'''

        expected = 0
        os.chdir('guard-page')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, self._unpriv_cmd(["./split-stack"]))

    def test_063_guard_page_CVE_2017_1000364_regression(self):
        '''Make sure the stack guard page fix for CVE-2017-1000364 does not crash java apps'''

        expected = 0
        os.chdir('guard-page')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, self._unpriv_cmd(["./stackcrash_jvm"]))

    def tearDown_072_strict_devmem(self):
        self.shell_cmd(["rmmod", "signpost"])
        self.shell_cmd(["make", "-C", "kernel-security/mem/signpost", "clean"])

    def test_072_strict_devmem(self):
        '''/dev/mem unreadable for kernel memory'''

        # if kernel doesn't have CONFIG_DEVMEM enabled at all, then
        # don't need to check for STRICT_DEVMEM, etc. CONFIG_DEVMEM only
        # became a configurable option in 3.19, however.
        if self.kernel_at_least('3.19') and not self._test_config('DEVMEM'):
            self._skipped("CONFIG_DEVMEM not enabled, skipping checks")
            return
        # module.sig_enforce and CONFIG_MODULE_SIG_FORCE will prevent
        # this test from inserting the test module
        with open("/proc/cmdline") as fh:
            cmdline = fh.read()
        if "module.sig_enforce" in cmdline or self._test_config('MODULE_SIG_FORCE'):
            self._skipped("Module signature enforced, skipping checks")
            return

        rc, output = self.shell_cmd(['mokutil', '--sb-state'])
        if rc == 0 and 'SecureBoot enabled' in output:
            self._skipped("Cannot load modules with SecureBoot enabled")
            return

        os.chdir('mem')
        target = None
        if self.kernel_is_ubuntu:
            self.assertShellExitEquals(0, ["make"])

            # Find a value to test in memory.
            self.shell_cmd(["rmmod", "signpost"])
            self.assertShellExitEquals(0, ["insmod", "signpost/signpost.ko"])
            self.teardowns.append(self.tearDown_072_strict_devmem)

            with open("/proc/signpost_phys") as signpost_phys:
                target = int(signpost_phys.read(), 16)
            with open("/proc/signpost_value") as signpost_value:
                value = int(signpost_value.read(), 16)
            self.assertEqual(value, 0xfeedface)
            self.announce("using %s" % (hex(target)))
        else:
            self.assertShellExitEquals(0, ["make", "readmem"])

        expected = [0]
        # FIXME: why does this work on Dapper??
        if not self.kernel_at_least('2.6.15'):
            self._skipped("only Dapper, Karmic and later")
            expected = [5]
        else:
            # Arch-specific
            if self.dpkg_arch not in ['i386', 'amd64', 'armel', 'armhf', 'arm64', 'ppc64el', 's390x']:
                self._skipped("x86, ARM, and ppc64el only")
                expected = [5]
            if self.dpkg_arch in self.arm_archs and \
               not self.kernel_at_least('2.6.38'):
                self._skipped("only 2.6.38 and later for ARM")
                expected = [4]
            if self.dpkg_arch == 'arm64' and \
               not self.kernel_at_least('3.16.0'):
                self._skipped("only 3.16 and later for ARM64")
                expected = [4, 7]
            # Xen and EC2 are weird. -virtual seems okay, though
            # Since EC2 /dev/mem behavior appears to depend at least partially on the
            # Xen _host_, we need to treat "ok" and "reads 0s" as okay.
            if self.kernel_version.endswith('-xen') or self.kernel_version.endswith('-ec2'):
                if self.lsb_release['Release'] == 8.04:
                    self.announce("weird on Hardy Xen")
                    expected = [0, 6]
                elif self.lsb_release['Release'] == 9.10:
                    self.announce("weird on Karmic EC2")
                    expected = [0, 6]
                elif self.lsb_release['Release'] == 10.04:
                    self.announce("weird on Lucid EC2")
                    expected = [0, 6]

        cmd = ['./readmem']
        if target:
            cmd += [hex(target)]
        rc, output = self.shell_cmd(cmd)
        self.announce("exit code %d" % (rc))
        self.assertTrue(rc in expected, 'exit code: %d (wanted %s). Output:\n%s' % (rc, ", ".join(["%d" % (x) for x in expected]), output))

    # Karmic and newer
    def test_082_stack_guard_kernel(self):
        '''Kernel stack guard'''

        expected = True
        if not self.kernel_at_least('2.6.31'):
            self._skipped("only Karmic and later")
            expected = False
        else:
            if self.dpkg_arch in self.arm_archs and \
               not self.kernel_at_least('2.6.35'):
                self._skipped("not available on ARM before 10.10")
                expected = False
            if self.dpkg_arch in ['arm64'] and \
               not self.kernel_at_least('4.4'):
                self._skipped("not available on ARM64 before xenial")
                expected = False
            if self.lsb_release['Release'] == 9.10 and self.kernel_version.endswith('-ec2'):
                self._skipped("ignored on Karmic EC2")
                expected = False
            if self.dpkg_arch in ['powerpc']:
                self._skipped("not available on 32-bit powerpc")
                expected = False
            if self.dpkg_arch in ['ppc64', 'ppc64el'] and \
               not self.kernel_at_least('4.20'):
                self._skipped("not available on powerpc before disco")
                expected = False
            if self.dpkg_arch in ['s390x']:
                self._skipped("not available on s390x")
                expected = False
        if self._get_config('MODULES') is None:
            self.announce("cannot check, non-modular")
            # Fall back to config test...
            self.assertTrue(self._get_config('CC_STACKPROTECTOR'))
            expected = False

        module = ""
        tmpdir = tempfile.mkdtemp(prefix='stack-guard-kernel-')
        for m in ['fs/befs/befs.ko', 'crypto/tcrypt.ko', 'fs/cifs/cifs.ko',
                  'net/ipv4/netfilter/arp_tables.ko',
                  'net/bridge/netfilter/ebtables.ko']:
            m = os.path.join('/lib/modules/%s/kernel/' % (self.kernel_version), m)
            if os.path.exists(m):
                module = m
                break
            if os.path.exists(m + '.zst'):
                module = os.path.join(tmpdir, os.path.basename(m))
                rc, output = self.shell_cmd(['zstd', '-d', '-o', module, m + '.zst'])
                self.assertEqual(rc, 0, output)
                break
        if expected:
            self.assertTrue(module, 'Could not find a suitable kernel module to test')

        rc, out = testlib.cmd(['readelf', '-s', module])
        if expected:
            self.assertEqual(rc, 0, out)
        shutil.rmtree(tmpdir, ignore_errors=True)
        self.assertEqual(expected, ' UND __stack_chk_fail\n' in out, '__stack_chk_fail missing from kernel (tested befs.ko)')

    # Karmic and newer
    def test_090_module_blocking(self):
        '''Sysctl to disable module loading exists'''

        expected = True
        if not self.kernel_at_least('2.6.31'):
            self._skipped("only Karmic and later")
            expected = False
        if self._get_config('MODULES') is None:
            self._skipped("non-modular")
            expected = False

        self.assertEqual(os.path.exists('/proc/sys/kernel/modules_disabled'), expected)

    def _check_symlinks(self, sticky, hardened=None):
        '''Performs the symlink following checks, either in sticky or non-sticky dir'''

        attacker = testlib.TestUser()
        noob = testlib.TestUser()

        # Validate we have three separate uids
        self.assertTrue(0 != attacker.uid)
        self.assertTrue(0 != noob.uid)
        self.assertTrue(attacker.uid != noob.uid)

        # Verify sudo is actually working to change euid
        self.assertShellOutputContains('(%s) ' % (attacker.login), ['sudo', '-u', attacker.login, 'id'])
        self.assertShellOutputContains('(%s) ' % (noob.login), ['sudo', '-u', noob.login, 'id'])

        # create testdir dir
        tmpdir = tempfile.mkdtemp(prefix='symlinks-')
        mode = 0o777
        if sticky:
            mode |= 0o1000
        os.chmod(tmpdir, mode)

        # Validate stickiness
        drop = os.path.join(tmpdir, 'remove.me')
        with open(drop, 'w') as drop_fh:
            drop_fh.write('I can be deleted in a non-sticky directory')
        if not hardened:
            hardened = False
            if sticky:
                expected = True
        expected = 0
        if sticky:
            expected = 1
        self.assertShellExitEquals(expected, ['sudo', '-u', attacker.login, 'rm', '-f', drop])
        self.assertEqual(sticky, os.path.exists(drop))

        # create world-readable target file
        message = 'sekrit\n'
        target = os.path.join(tmpdir, 'target')
        with open(target, 'w') as target_fh:
            target_fh.write(message)
        os.chmod(target, 0o644)

        # create symlinks to it as different users
        root_symlink = os.path.join(tmpdir, 'root.link')
        attacker_symlink = os.path.join(tmpdir, 'attacker.link')
        noob_symlink = os.path.join(tmpdir, 'noob.link')

        os.symlink(target, root_symlink)
        self.assertShellExitEquals(0, ['sudo', '-u', attacker.login, 'ln', '-s', target, attacker_symlink])
        self.assertShellExitEquals(0, ['sudo', '-u', noob.login, 'ln', '-s', target, noob_symlink])

        # Validate the link ownerships
        self.assertEqual(os.lstat(root_symlink).st_uid, 0)
        self.assertEqual(os.lstat(attacker_symlink).st_uid, attacker.uid)
        self.assertEqual(os.lstat(noob_symlink).st_uid, noob.uid)

        ### READING

        # Verify each user can see the target file contents directly
        self.assertShellOutputEquals(message, ['cat', target])
        self.assertShellOutputEquals(message, ['sudo', '-u', attacker.login, 'cat', target])
        self.assertShellOutputEquals(message, ['sudo', '-u', noob.login, 'cat', target])

        # Verify that users via their own symlink can read the file
        self.assertShellOutputEquals(message, ['cat', root_symlink])
        self.assertShellOutputEquals(message, ['sudo', '-u', noob.login, 'cat', noob_symlink])
        self.assertShellOutputEquals(message, ['sudo', '-u', attacker.login, 'cat', attacker_symlink])

        # Verify that each user can read the file via the root symlink (dir owner)
        self.assertShellOutputEquals(message, ['cat', root_symlink])
        self.assertShellOutputEquals(message, ['sudo', '-u', attacker.login, 'cat', root_symlink])
        self.assertShellOutputEquals(message, ['sudo', '-u', noob.login, 'cat', root_symlink])

        # Verify non-root users cannot read obvious unreadable files
        self.assertShellOutputContains('root', ['sudo', '-u', noob.login, 'cat', '/etc/shadow'], invert=True)
        self.assertShellOutputContains('root', ['sudo', '-u', attacker.login, 'cat', '/etc/shadow'], invert=True)

        # Verify users via a different user's symlink cannot read the file if sticky and hardened
        self.assertShellOutputEquals(message, ['sudo', '-u', noob.login, 'cat', attacker_symlink], invert=sticky and hardened)
        self.assertShellOutputEquals(message, ['sudo', '-u', attacker.login, 'cat', noob_symlink], invert=sticky and hardened)
        self.assertShellOutputEquals(message, ['cat', attacker_symlink], invert=sticky and hardened)
        self.assertShellOutputEquals(message, ['cat', noob_symlink], invert=sticky and hardened)

        ### WRITING

        # Verify users can write to the file directly
        os.unlink(target)
        self.assertShellExitEquals(0, ['sudo', '-u', noob.login, 'dd', 'if=/bin/dd', 'of=%s' % target])
        self.assertTrue(os.path.exists(target))
        os.unlink(target)
        self.assertShellExitEquals(0, ['sudo', '-u', attacker.login, 'dd', 'if=/bin/dd', 'of=%s' % target])
        self.assertTrue(os.path.exists(target))
        os.unlink(target)
        self.assertShellExitEquals(0, ['dd', 'if=/bin/dd', 'of=%s' % target])
        self.assertTrue(os.path.exists(target))

        # Verify users can write to the file via symlink to create target
        os.unlink(target)
        self.assertShellExitEquals(0, ['sudo', '-u', noob.login, 'dd', 'if=/bin/dd', 'of=%s' % noob_symlink])
        self.assertTrue(os.path.exists(target))
        os.unlink(target)
        self.assertShellExitEquals(0, ['sudo', '-u', attacker.login, 'dd', 'if=/bin/dd', 'of=%s' % attacker_symlink])
        self.assertTrue(os.path.exists(target))
        os.unlink(target)
        self.assertShellExitEquals(0, ['dd', 'if=/bin/dd', 'of=%s' % root_symlink])
        self.assertTrue(os.path.exists(target))

        # Verify non-root users can not write to the direct file
        self.assertShellExitEquals(1, ['sudo', '-u', noob.login, 'dd', 'if=/bin/dd', 'of=%s' % target])
        self.assertShellExitEquals(1, ['sudo', '-u', attacker.login, 'dd', 'if=/bin/dd', 'of=%s' % target])

        # Verify non-root users can not write to the symlink file
        self.assertShellExitEquals(1, ['sudo', '-u', noob.login, 'dd', 'if=/bin/dd', 'of=%s' % noob_symlink])
        self.assertShellExitEquals(1, ['sudo', '-u', attacker.login, 'dd', 'if=/bin/dd', 'of=%s' % attacker_symlink])

        # CREATING

        # Verify non-root users can not create files to the symlink target
        # when crossing uid
        expected = 0
        if sticky and hardened:
            expected = 1
        os.unlink(target)
        self.assertShellExitEquals(expected, ['sudo', '-u', noob.login, 'dd', 'if=/bin/dd', 'of=%s' % attacker_symlink])
        if os.path.exists(target):
            os.unlink(target)
        self.assertShellExitEquals(expected, ['sudo', '-u', attacker.login, 'dd', 'if=/bin/dd', 'of=%s' % noob_symlink])
        if os.path.exists(target):
            os.unlink(target)
        self.assertShellExitEquals(expected, ['dd', 'if=/bin/dd', 'of=%s' % noob_symlink])
        if os.path.exists(target):
            os.unlink(target)
        self.assertShellExitEquals(expected, ['dd', 'if=/bin/dd', 'of=%s' % attacker_symlink])
        if os.path.exists(target):
            os.unlink(target)

        # Verify users can create file through root's symlink
        self.assertShellExitEquals(0, ['sudo', '-u', noob.login, 'dd', 'if=/bin/dd', 'of=%s' % root_symlink])
        self.assertTrue(os.path.exists(target))
        os.unlink(target)
        self.assertShellExitEquals(0, ['sudo', '-u', attacker.login, 'dd', 'if=/bin/dd', 'of=%s' % root_symlink])
        self.assertTrue(os.path.exists(target))
        os.unlink(target)
        self.assertShellExitEquals(0, ['dd', 'if=/bin/dd', 'of=%s' % root_symlink])
        self.assertTrue(os.path.exists(target))

        # Clean up
        shutil.rmtree(tmpdir, ignore_errors=True)

    def tearDown_091_symlink_following_in_sticky_directories(self):
        self.set_sysctl_value(self.sysctl['symlink'], 1)

    def test_091_symlink_following_in_sticky_directories(self):
        '''Symlinks not followable across differing uids in sticky directories'''

        expected = True
        if not self.kernel_at_least('2.6.35'):
            self._skipped("only Maverick and later")
            expected = False
        elif not os.path.exists(self.sysctl['symlink']) and \
             not self._test_config('SECURITY_YAMA') and \
             not self.kernel_at_least('3.5'):
            self._skipped("built without Yama")
            expected = False

        if expected:
            self.teardowns.append(self.tearDown_091_symlink_following_in_sticky_directories)
            self._test_sysctl_value(self.sysctl['symlink'], 1)
        self._check_symlinks(sticky=False, hardened=expected)
        self._check_symlinks(sticky=True, hardened=expected)
        if expected:
            self.set_sysctl_value(self.sysctl['symlink'], 0)
        self._check_symlinks(sticky=False, hardened=False)
        self._check_symlinks(sticky=True, hardened=False)
        if expected:
            self.set_sysctl_value(self.sysctl['symlink'], 1)

    def _check_hardlinks(self, hardened=True):
        expected = 0
        if hardened:
            expected = 1

        tmpdir = tempfile.mkdtemp(prefix='hardlinks-', dir='/opt/')
        self.assertShellExitEquals(0, ['chown', os.environ['SUDO_USER'], tmpdir])

        secret = tempfile.NamedTemporaryFile(prefix="secret-", dir='/opt/')
        evil = '%s/evil' % (tmpdir)
        not_evil = '%s/not-evil' % (tmpdir)
        # Allow hardlink to self files
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'touch', '%s/mine' % (tmpdir)])
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/mine' % (tmpdir), '%s/okay' % (tmpdir)])

        # Disallow hardlink to unreadable files
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', secret.name, evil])
        if os.path.exists(evil):
            os.unlink(evil)

        # Disallow hardlink to only writable files
        self.assertShellExitEquals(0, ['chmod', 'a+r', secret.name])
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', secret.name, evil])
        if os.path.exists(evil):
            os.unlink(evil)

        # Allow hardlinkg to readable and writable files
        self.assertShellExitEquals(0, ['chmod', 'a+w', secret.name])
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', secret.name, not_evil])
        os.unlink(not_evil)

        # Disallow hardlinks to non-regular files
        self.assertShellExitEquals(0, ['mknod', '-m', '0666', '%s/null' % (tmpdir), 'c', '1', '3'])
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'cat', '%s/null' % (tmpdir)])
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/null' % (tmpdir), evil])
        if os.path.exists(evil):
            os.unlink(evil)

        # allow hardlinks to owned non-regular files
        self.assertShellExitEquals(0, ['chown', os.environ['SUDO_USER'], '%s/null' % (tmpdir)])
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/null' % (tmpdir), not_evil])
        os.unlink(not_evil)

        # allow hardlinks to owned setuid files
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'chmod', 'u+s', '%s/mine' % (tmpdir)])
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/mine' % (tmpdir), not_evil])
        os.unlink(not_evil)

        # Disallow hardlinks to non-owned setuid files
        self.assertShellExitEquals(0, ['touch', '%s/root-setuid' % (tmpdir)])
        self.assertShellExitEquals(0, ['chmod', 'u+s', '%s/root-setuid' % (tmpdir)])
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/root-setuid' % (tmpdir), evil])
        if os.path.exists(evil):
            os.unlink(evil)

        # allow hardlinks to owned exec setgid files
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'chmod', 'g+sx', '%s/mine' % (tmpdir)])
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/mine' % (tmpdir), not_evil])
        os.unlink(not_evil)

        # Disallow hardlinks to non-owned exec setgid files
        self.assertShellExitEquals(0, ['touch', '%s/root-setgid' % (tmpdir)])
        self.assertShellExitEquals(0, ['chmod', 'g+sx', '%s/root-setgid' % (tmpdir)])
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], 'ln', '%s/root-setgid' % (tmpdir), evil])
        if os.path.exists(evil):
            os.unlink(evil)

        # Can link with CAP_FOWNER
        self.assertShellExitEquals(0, ['ln', '%s/null' % (tmpdir), '%s/root-null' % (tmpdir)])

        shutil.rmtree(tmpdir, ignore_errors=True)

    def tearDown_092_hardlink_restriction(self):
        self.set_sysctl_value(self.sysctl['hardlink'], 1)

    def test_092_hardlink_restriction(self):
        '''Hardlink disallowed for unreadable/unwritable sources'''

        expected = True
        if not self.kernel_at_least('2.6.35'):
            self._skipped("only Maverick and later")
            expected = False
        elif not os.path.exists(self.sysctl['hardlink']) and \
             not self._test_config('SECURITY_YAMA') and \
             not self.kernel_at_least('3.5'):
            self._skipped("built without Yama")
            expected = False

        if expected:
            self.teardowns.append(self.tearDown_092_hardlink_restriction)
            self._test_sysctl_value(self.sysctl['hardlink'], 1)
        self._check_hardlinks(hardened=expected)
        if expected:
            self.set_sysctl_value(self.sysctl['hardlink'], 0)
        self._check_hardlinks(hardened=False)
        if expected:
            self.set_sysctl_value(self.sysctl['hardlink'], 1)

    def test_093_ptrace_restriction(self):
        '''ptrace allowed only on children or declared processes'''

        expected = 0
        if not self.kernel_at_least('2.6.35'):
            self._skipped("only Maverick and later")
            expected = 1
        elif not self._test_config('SECURITY_YAMA') and \
             not self.kernel_at_least('3.3'):
            self._skipped("built without Yama")
            expected = 1

        cmd = ['sudo', '-u', os.environ['SUDO_USER'], 'bash', '-x', './ptrace-restrictions.sh']
        if self.kernel_at_least('3.2'):
            cmd += ['--any']
        else:
            self.announce("skipping PR_SET_PTRACER_ANY")

        os.chdir('ptrace')
        self.assertShellExitEquals(0, ["make"])
        shelltimeout = testlib.TimeoutFunction(self.assertShellExitEquals, 10)
        try:
            with open("/dev/null") as dev_null:
                shelltimeout(expected, cmd, stdin=dev_null)
        except:
            # try to run this again if it timed out. haven't been able to
            # track down the cause yet.
            self.announce("timeout, backing off")
            time.sleep(5)
            # back off with a longer timeout, this may be needed for panda
            shelltimeout = testlib.TimeoutFunction(self.assertShellExitEquals, 60)
            shelltimeout(expected, cmd, stdin=open("/dev/null"))

    def test_093_ptrace_restriction_parent_via_thread(self):
        '''ptrace of child works from parent threads (LP: #737676)'''

        if not self.kernel_at_least('2.6.35'):
            self._skipped("only Maverick and later")
        expected = 0

        os.chdir('ptrace')
        # Works from main process
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], './thread-prctl', '0', '1'])
        # Works from thread
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], './thread-prctl', '0', '0'])

    def test_093_ptrace_restriction_prctl_via_thread(self):
        '''prctl(PR_SET_PTRACER) works from threads (LP: #729839)'''

        # on a failure "2" is seen
        expected = 0
        os.chdir('ptrace')
        # Works from main process
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], './thread-prctl', '1', '1'])
        # Works from thread
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], './thread-prctl', '2', '1'])

    def test_093_ptrace_restriction_extras(self):
        '''ptrace from thread on tracee that used prctl(PR_SET_PTRACER)'''

        # on a failure "2" is seen
        expected = 0
        os.chdir('ptrace')
        # prctl from main process
        self.assertShellExitEquals(0, ['sudo', '-u', os.environ['SUDO_USER'], './thread-prctl', '1', '0'])
        # prctl from thread
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], './thread-prctl', '2', '0'])

    def test_094_rare_net_autoload(self):
        '''rare network modules do not autoload'''

        proto = {
            'ax25': 3,
            'netrom': 6,
            'x25': 9,
            'rose': 11,
            'decnet': 12,
            'econet': 19,
            'rds': 21,
            'af_802154': 36,
        }
        # try AF_INET for the positive case
        raised = False
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        except Exception:
            raised = True
        finally:
            s.close()

        self.assertFalse(raised, msg="AF_INET not loadable")

        if self.lsb_release['Release'] < 11.04:
            self._skipped("only Natty and later")
            return

        for af in proto:
            # Dapper's python 2.4 doesn't have "with", so this is a bit ugly...
            raised = False
            try:
                # unload module before attempting to open the socket for
                # it, to ensure we have a clean environment. We do't
                # care about the result of the cmd because it will fail
                # as modules are dropped from the kernel entirely
                testlib.cmd(['modprobe', '-r', af])
                socket.socket(proto[af], socket.SOCK_STREAM, 0)
            except Exception as detail:
                self.assertTrue(isinstance(detail, socket.error), msg=af)
                self.assertEqual(detail.errno, 97, msg=af)
                raised = True
            self.assertTrue(raised, msg=af)

    def _read_twice(self, filename, transform, expected, retry=False, check=None):
        '''Return contents of a file as root and regular user'''

        self.assertNotEqual(expected, KPTRValues.KPTR_STRICT,
                            'KPTR_STRICT should not make it into _read_twice')

        if not os.path.exists(filename):
            self._skipped("No %s" % (filename))
            return

        # Make sure root can read it
        cmd = ['cat', filename]
        count = 0
        done = False
        while not done:
            rc, root = self.shell_cmd(cmd)
            self.assertEqual(rc, 0, root)

            if check and check not in root:
                self._skipped("No '%s' in root's %s" % (check, filename))
                return

            address = transform(root)
            if address in ['(____ptrval____)', '(ptrval)']:
                # at some point the kernel started hashing addresses,
                # and uses the two values above to indicate there was
                # not enough entropy to hash them. Convert them to a
                # non-zero number (LP: #1831873)
                address = "FFFFFFFF"

            if address == 'RETRY':
                if not retry or count >= 100:
                    self.assertTrue(False, "transformation failed on root-read data from %s:\n%s" % (filename, root))
                    done = True
                else:
                    count += 1
            elif expected in [KPTRValues.ALLOWED, KPTRValues.RESTRICTED]:
                self.assertFalse(0 == int(address, 16), "%s: root saw %s - contents:\n%s" % (filename, address, root))
                done = True
            elif expected is KPTRValues.ALWAYS_ZERO:
                self.assertEqual(0, int(address, 16), "%s: root saw %s - contents:\n%s" % (filename, address, root))
                done = True
            else:
                raise self.failureException("logic error, unexpected expected value")

        # ... and regular user can't
        cmd = ['sudo', '-u', os.environ['SUDO_USER']] + cmd
        count = 0
        done = False

        while not done:
            rc, regular = self.shell_cmd(cmd)
            self.assertEqual(rc, 0, regular)

            if check and check not in regular:
                self._skipped("No '%s' in user's %s" % (check, filename))
                return

            address = transform(regular)
            if address in ['(____ptrval____)', '(ptrval)']:
                # at some point the kernel started hashing addresses,
                # and uses the two values above to indicate there was
                # not enough entropy to hash them. Convert them to a
                # non-zero number (LP: #1831873)
                address = "FFFFFFFF"

            if address == 'RETRY':
                if not retry or count >= 100:
                    self.assertTrue(False, "transformation failed on user-read data from %s:\n%s" % (filename, regular))
                    done = True
                else:
                    count += 1
            elif expected in [KPTRValues.RESTRICTED, KPTRValues.ALWAYS_ZERO]:
                self.assertEqual(0, int(address, 16), "%s: user saw %s - contents:\n%s" % (filename, address, regular))
                done = True
            elif expected is KPTRValues.ALLOWED:
                self.assertFalse(0 == int(address, 16), "%s: user saw %s - contents:\n%s" % (filename, address, regular))
                done = True
            else:
                raise self.failureException("logic error, unexpected expected value")

        return root, regular

    # Check for %pK abilities
    def test_095_kernel_symbols_acl(self):
        '''/proc/sys/kernel/kptr_restrict is enabled'''

        # It's a default in the kernel in the 2.6.38 series only, otherwise
        # it's enforced vi procps sysctls.
        if self.lsb_release['Release'] > 10.10 or \
           (self.kernel_at_least('2.6.38') and not self.kernel_at_least('3.0')):
            expected = 1
            exists = 1
        else:
            expected = 0
            exists = 0
            if self.kernel_at_least('2.6.38'):
                exists = 1
            self._skipped("only Natty and later")

        self._test_sysctl_value('kernel/kptr_restrict', expected, exists=exists)

    def tearDown_095_kernel_symbols_missing(self):
        self.set_sysctl_value('kernel/kptr_restrict', 1)

    # Check for %pK abilities
    def _check_pK_files(self, test_function, expected=KPTRValues.RESTRICTED):
        # It's a default in the kernel in the 2.6.38 series only, otherwise
        # it's enforced vi procps sysctls.
        has_kptr_restrict = True

        # if allowed or always zero
        expected_restricted = expected_unrestricted = expected
        if expected == KPTRValues.RESTRICTED:
            expected_restricted = KPTRValues.RESTRICTED
            expected_unrestricted = KPTRValues.ALLOWED
        elif expected == KPTRValues.KPTR_STRICT:
            expected_restricted = expected_unrestricted = KPTRValues.RESTRICTED

        if has_kptr_restrict:
            self.set_sysctl_value('kernel/kptr_restrict', 1)
            self.teardowns.append(self.tearDown_095_kernel_symbols_missing)
        test_function(expected_restricted)
        if has_kptr_restrict:
            # Validate that disabling the feature restores kernel pointers
            self.set_sysctl_value('kernel/kptr_restrict', 0)
            test_function(expected_unrestricted)
            self.set_sysctl_value('kernel/kptr_restrict', 1)

    # Check for %pK abilities
    def _095_kernel_symbols_missing_kallsyms(self, expected):
        '''kernel addresses in kallsyms and modules are zeroed out'''

        if os.path.exists('/proc/kallsyms'):
            self._read_twice('/proc/kallsyms',
                             lambda x: x.splitlines().pop().split()[0],
                             expected)

    # Check for %pK abilities
    def _095_kernel_symbols_missing_proc_modules(self, expected):
        '''kernel addresses in /proc/modules are zeroed out'''

        def _split_proc_modules(x):
            line = x.splitlines().pop().split()
            ret = line.pop()
            if ret.startswith('(') and ret.endswith(')'):
                # Module is tainted so we'll have to pop off the taint flag
                # field to get the address
                ret = line.pop()
            return ret

        if os.path.exists('/proc/modules') and not testlib.is_empty_file('/proc/modules'):
            root, regular = \
                self._read_twice('/proc/modules',
                                 _split_proc_modules,
                                 expected)
            module = root.splitlines().pop().split()[0].strip()
            module_path = '/sys/module/%s/sections/.text' % (module)
            if not self._test_config('KALLSYMS'):
                self.assertFalse(os.path.exists(module_path),
                                 'Module text section %s *does* exist, despite CONFIG_KALLSYMS being unset' % module_path)
            else:
                self.assertTrue(os.path.exists(module_path),
                                'Module text section %s does not exist' % module_path)
                # kernel 4.15 made module text sections readable only to root
                if self.kernel_at_least('4.15'):
                    module_mode = os.stat(module_path).st_mode & 0o7777
                    self.assertEqual(module_mode, 0o400,
                                     'mode of %s: %s' % (module_path, oct(module_mode)))
                else:
                    self._read_twice(module_path,
                                     lambda x: x.splitlines().pop().split().pop(),
                                     expected)

    # Check for %pK abilities
    def _095_kernel_symbols_missing_proc_timer_list(self, expected):
        '''kernel addresses in /proc/timer_list are zeroed out'''

        # kernel 4.15 made /proc/timer_list readable only to root
        # same happened in 4.4.0-143.169
        if self.kernel_at_least('4.15') or (self.kernel_at_least('4.4') and not self.kernel_at_least('4.5')):
            timer_mode = os.stat('/proc/timer_list').st_mode & 0o7777
            self.assertEqual(timer_mode, 0o400, 'mode of %s: %s' % ('/proc/timer_list', oct(timer_mode)))
        else:
            # Make sure a timer is running
            sleeper = subprocess.Popen(['sleep', '120'])
            self._read_twice('/proc/timer_list',
                             lambda x: [y.split().pop() for y in x.splitlines()
                                        if 'base:' in y][0],
                             expected, check='base:')
            self._read_twice('/proc/timer_list',
                             lambda x: [y.split().pop(1).split('<')[1].split('>')[0]
                                        for y in x.splitlines()
                                        if re.search('#[0-9]+: <', y)][0],
                             expected)
            os.kill(sleeper.pid, 9)

    # Check for %pK abilities
    def _095_kernel_symbols_missing_proc_self_stack(self, expected):
        '''kernel addresses in /proc/self/stack are zeroed out'''

        def __self_stack_filter(content):

            # on s390x and ppc64el, the first one or more lines of
            # /proc/self/stack will sometimes be '(null)' which has
            # a 000 address, causing a false negative. If we can't find
            # any valid lines, we'll warn and indicate the read needs to
            # be retried.
            x = content.splitlines()
            for line in x:
                if line.split()[1] != '(null)':
                    return line.split()[0][2:-2]
            self._skipped("_check_pK_files(): couldn't find a non-null line in /proc/self/stack, retrying.")
            return "RETRY"

        if self.dpkg_arch == 'ppc64el' and self.kernel_at_least('3.19.0') \
                and not self.kernel_at_least('3.20.0'):
            self._skipped("/proc/self/stack check; contents bogus on ppc64el/3.19")
        elif not self._test_config('STACKTRACE'):
            self._skipped("CONFIG_STACKTRACE not enabled; ensuring /proc/self/stack does not exist.")
            self.assertFalse(os.path.exists("/proc/self/stack"),
                             '/proc/self/stack does not exist')
        else:
            self.assertTrue(os.path.exists("/proc/self/stack"),
                            '/proc/self/stack does not exist')
            # upstream commit f8a00cef17206ecd1b30d3d9f99e10d9fa707aa7 in 4.19
            # made /proc/self/stack readable only to root, also backported to
            # stable kernels
            stack_mode = os.stat('/proc/self/stack').st_mode & 0o7777
            if stack_mode == 0o400:
                self._skipped("/proc/self/stack readable only by root")
            else:
                self._read_twice('/proc/self/stack',
                                 __self_stack_filter,
                                 expected, retry=True)

    # Check for %pK abilities
    def _095_kernel_symbols_missing_proc_net_tcp(self, expected):
        '''kernel addresses in /proc/net/tcp are zeroed out'''
        self._read_twice('/proc/net/tcp',
                         lambda x: x.splitlines()[1].split()[11],
                         expected)

    # Check for %pK abilities
    def test_095_kernel_symbols_missing_kallsyms(self):
        '''kernel addresses in /proc/kallsyms are zeroed out'''
        expected = KPTRValues.RESTRICTED
        if (self.kernel_at_least('4.15')):
            expected = KPTRValues.KPTR_STRICT
            self.announce("In 4.15+, /proc/kallsyms always zeroed for users")
        self._check_pK_files(self._095_kernel_symbols_missing_kallsyms, expected=expected)

    # Check for %pK abilities
    def test_095_kernel_symbols_missing_proc_modules(self):
        '''kernel addresses in /proc/modules are zeroed out'''
        expected = KPTRValues.RESTRICTED
        if not self._test_config('KALLSYMS') and self.kernel_at_least('4.15'):
            # disabling KALSSYMS on newer kernels makes the module
            # addresses always zero
            expected = KPTRValues.ALWAYS_ZERO
            self.announce("CONFIG_KALLSYMS is unset, /proc/modules always zeroed")
        elif (self.kernel_at_least('4.15')):
            expected = KPTRValues.KPTR_STRICT
            self.announce("In 4.15+, /proc/modules always zeroed for users")
        self._check_pK_files(self._095_kernel_symbols_missing_proc_modules, expected=expected)

    # Check for %pK abilities
    def test_095_kernel_symbols_missing_proc_time_list(self):
        '''kernel addresses in /proc/timer_list are zeroed out'''
        self._check_pK_files(self._095_kernel_symbols_missing_proc_timer_list)

    # Check for %pK abilities
    def test_095_kernel_symbols_missing_proc_self_stack(self):
        '''kernel addresses in /proc/self/stack are zeroed out'''
        expected = KPTRValues.RESTRICTED
        if (self.kernel_at_least('4.15')):
            expected = KPTRValues.ALWAYS_ZERO
            self.announce("In 4.15+ /proc/self/stack always zeroed")
        self._check_pK_files(self._095_kernel_symbols_missing_proc_self_stack, expected=expected)

    # Check for %pK abilities
    def test_095_kernel_symbols_missing_proc_net_tcp(self):
        '''kernel addresses in /proc/net/tcp are zeroed out'''
        self._check_pK_files(self. _095_kernel_symbols_missing_proc_net_tcp)

    def test_096_boot_symbols_unreadable(self):
        '''kernel addresses in /boot are not world readable'''

        expected = 0
        if not self.kernel_at_least('2.6.38'):
            self._skipped("only Natty and later")
            expected = 0o044
        mask = 0o044

        # Check something readable just to be sure
        name = '/proc/cpuinfo'
        self.assertEqual(os.stat(name).st_mode & mask, 0o044, name)
        # Check something unreadable just to be sure
        name = '/proc/kpagecount'
        self.assertEqual(os.stat(name).st_mode & mask, 0o000, name)

        # Make sure kernel files are either missing or unreadable.
        for base in ['System.map', 'vmcoreinfo', 'vmlinuz', 'vmlinux']:
            for name in ['/%s' % (base),
                         '/boot/%s-%s' % (base, self.kernel_version),
                         '/boot/%s-%s.efi.signed' % (base, self.kernel_version)]:
                if not os.path.exists(name):
                    self._skipped("%s does not exist" % name)
                    continue
                self.assertEqual(os.stat(name).st_mode & mask, expected, '%s is world readable' % (name))

    # FIXME: merge proc and boot file perm checks
    def test_096_proc_entries_unreadable(self):
        '''sensitive files in /proc are not world readable'''

        expected = 0
        if self.lsb_release['Release'] < 11.04:
            self._skipped("only Natty and later")
            expected = 0o044
        mask = 0o044

        # Check something readable just to be sure
        name = '/proc/uptime'
        self.assertEqual(os.stat(name).st_mode & mask, 0o044, name)
        # Check something unreadable just to be sure
        name = '/proc/kcore'
        if not os.path.exists(name):
            # if kcore is missing, fall back to kmsg, should be 400 too
            name = '/proc/kmsg'
        self.assertEqual(os.stat(name).st_mode & mask, 0o000, name)

        proc_files = ['vmallocinfo', 'slabinfo']
        for dentry in proc_files:
            name = os.path.join('/proc', dentry)
            if self.kernel_version.endswith('-goldfish') or \
               self.kernel_version.endswith('-maguro') or \
               self.kernel_version.endswith('-mako') or \
               self.kernel_version.endswith('-manta') or \
               self.kernel_version.endswith('-flo'):
                # On Touch, the Android init.rc chowns slabinfo to 0440 and chmods
                # it to root:log. The log uid/gid is 1007 which, unfortunately,
                # overlaps with the traditional Ubuntu user uid/gid range but the
                # phablet uid/gid is 32011.
                expected = 0o040
                self.assertEqual(os.stat(name).st_gid, 1007, '%s is not group owned by Android\'s log user' % (name))
            if not os.path.exists(name):
                self._skipped("%s does not exist" % name)
                continue
            self.assertEqual(os.stat(name).st_mode & mask, expected, '%s is world readable' % (name))

    def test_100_keep_acpi_method_disabled(self):
        '''/sys/kernel/debug/acpi/custom_method stays disabled'''

        # If debugfs isn't known to the kernel, this is an okay state
        with open('/proc/filesystems') as proc_filesystems:
            filesystems = proc_filesystems.read()
            if '\tdebugfs\n' not in filesystems:
                self._skipped('No debugfs')
                return

        # Since it exists, it must be mounted to test for custom_method
        self.assertTrue(os.path.exists('/sys/kernel'))
        kernel = os.lstat('/sys/kernel')
        self.assertTrue(os.path.exists('/sys/kernel/debug'))
        debug = os.lstat('/sys/kernel/debug')
        needs_umount = False
        if kernel.st_dev == debug.st_dev:
            self.assertShellExitEquals(0, ["mount", "-t", "debugfs", "none", "/sys/kernel/debug"])
            needs_umount = True
            debug = os.lstat('/sys/kernel/debug')
        # Make sure /sys/kernel and /sys/kernel/debug are separate filesystems
        self.assertTrue(kernel.st_dev != debug.st_dev)

        # Make sure acpi/custom_method does not exist
        custom_method_exists = os.path.exists('/sys/kernel/debug/acpi/custom_method')
        if needs_umount:
            self.assertShellExitEquals(0, ["umount", "/sys/kernel/debug"])
        self.assertFalse(custom_method_exists)

    def test_101_proc_fd_leaks(self):
        '''/proc/$pid/ DAC bypass on setuid (CVE-2011-1020)'''

        bad = {
            'auxv': 'AT_BASE:',
            'syscall': ' 0x',
            'stack': '[<',
        }

        expected = True

        os.chdir('proc-leaks')
        for name in list(bad.keys()):
            # If it's not there, it can't leak, so skip missing ones
            # not present in earlier kernels.
            if not os.path.exists('/proc/self/%s' % (name)):
                continue
            self.assertShellOutputContains(bad[name], ['sudo', '-u', os.environ['SUDO_USER'], "sh", "-c", "echo '' | ./dac-bypass.py %s" % (name)], invert=expected)

    def test_110_seccomp_filter(self):
        '''seccomp_filter works'''

        # FIXME: these tests are based on an outdated api from
        # when seccomp was in development, and are only useful for
        # testing the 3.1ish era kernel. An improved set of tests
        # to exercise seccomp filtering would likely incorporate
        # https://github.com/redpig/seccomp before or after it goes
        # upstream into the kernel.

        expected = 0
        if self.dpkg_arch not in self.seccomp_filter_archs:
            self._skipped("only x86 on 3.0 kernel")
            expected = 1

        os.chdir('seccomp_filter')
        self.assertShellExitEquals(0, ["make"])
        shelltimeout = testlib.TimeoutFunction(self.assertShellExitEquals, 30)
        shelltimeout(expected, ["./seccomp_tests"])

    def test_120_smep_works(self):
        '''SMEP works'''

        if 'smep' not in self.cpu_flags:
            self._skipped("CPU does not support SMEP")
            return

        # module.sig_enforce and CONFIG_MODULE_SIG_FORCE will prevent
        # this test from inserting the test module
        with open("/proc/cmdline") as fh:
            cmdline = fh.read()
        if "module.sig_enforce" in cmdline or self._test_config('MODULE_SIG_FORCE'):
            self._skipped("Module signature enforced, skipping checks")
            return

        rc, output = self.shell_cmd(['mokutil', '--sb-state'])
        if rc == 0 and 'SecureBoot enabled' in output:
            self._skipped("Cannot load modules with SecureBoot enabled")
            return

        os.chdir('smep')
        if self.kernel_is_ubuntu:
            self.assertShellExitEquals(0, ["make", "clean"])
            self.assertShellExitEquals(0, ["make"])

            # Find a value to test in memory.
            self.shell_cmd(["rmmod", "execuser"])
            self.assertShellExitEquals(0, ["insmod", "execuser/execuser.ko"])
            # TODO: Magic goes here.
            self._skipped("unfinished test")
            self.assertShellExitEquals(0, ["rmmod", "execuser"])
        else:
            self._skipped("only on Ubuntu")

    def test_130_kexec_disabled_00_proc(self):
        '''kexec_disabled sysctl supported'''

        expected = 0
        exists = True
        if not self.kernel_at_least('3.11'):
            self._skipped("kexec disable sysctl did not exist before trusty")
            expected = 1
            exists = False

        # ARM64 does not currently support kexec.
        if self._test_config('KEXEC') is False:
            self._skipped("kexec config not enabled")
            expected = 1
            exists = False

        self._test_sysctl_value('kernel/kexec_load_disabled', expected, exists=exists)

    taint_exception_table = {
        'icp': 'PO',
        'nvidia_drm': 'PO',
        'spl': 'O',
        'zavl': 'PO',
        'zcommon': 'PO',
        'zfs': 'PO',
        'zlua': 'PO',
        'znvpair': 'PO',
        'zunicode': 'PO',
    }

    def _is_tainted(self, module, taint_field):
        '''checks for tainted module, with some known exceptions'''

        # no taint field at all
        if not (taint_field.startswith('(') and taint_field.endswith(')')):
            return False

        # drop first and last characters ('(' and ')')
        taint_value = taint_field[1:-1]

        # check for TAINT_CRAP
        if taint_value == 'C':
            return False

        # check in the exception table
        if module in self.taint_exception_table and self.taint_exception_table[module] == taint_value:
            return False

        # Ignore livepatch modules
        if module.startswith("kpatch_livepatch_"):
            return False

        # Son, we gots us an unexpectedly tainted kernel module here.
        return True

    def test_140_kernel_modules_not_tainted(self):
        '''kernel modules are not marked with a taint flag (especially 'E' for TAINT_UNSIGNED_MODULE)'''
        modules = '/proc/modules'

        if not os.path.exists(modules) or testlib.is_empty_file(modules):
            self._skipped('%s does not exist' % modules)

        with open(modules, 'r') as fh:
            for line in fh:
                fields = line.split()
                last_field = fields[-1]
                # Fail if the module is tainted. The one exception is TAINT_CRAP
                # (C), which is used to indicate the module comes from the staging
                # tree.
                if self._is_tainted(fields[0], last_field):
                    self.fail('Module \'%s\' is tainted: %s' % (fields[0], last_field))

    def test_020_aslr_00_proc(self):
        '''ASLR enabled'''

        expected = 2
        if not self.kernel_at_least('2.6.27'):
            self._skipped("boolean on Hardy and earlier")
            expected = 1

        self._test_sysctl_value('kernel/randomize_va_space', expected)

    def _test_aslr_rekey(self, area, target, name):
        '''Verify that CVE-2009-3238 is fixed'''
        self.announce("%s rekey" % (name))
        failures = 0
        report = ""
        for count in range(0, 100):
            rc, output = self.shell_cmd(['./%s' % (target), 'rekey', area, '--verbose'])
            if rc != 0:
                failures += 1
                report = "%s:\n%s" % (name, output)
        # Allow a 4-in-100 chance of repeated ASLR position on rekey, since
        # that's double the max value seen in practice.
        if failures <= 4:
            return 0, report
        return 1, report

    def _test_aslr_exec(self, area, expected, target, name):
        self.announce(name)
        aslr_expected = expected
        if (not self.kernel_at_least('5.19') and self.dpkg_arch in ['ppc64el'] and area in ['libs', 'vdso', 'mmap']
            and resource.getrlimit(resource.RLIMIT_STACK) == (resource.RLIM_INFINITY, resource.RLIM_INFINITY)):
            # ppc64el has broken aslr when stack is unlimited
            # https://github.com/linuxppc/linux/issues/59
            # Issue fixed with 3ba4289, which has been applied to 5.19+
            # however, the rekey portion of the test *succeeds* so we
            # need to adjust the expected value here.
            self._skipped("unlimited stack aslr broken on ppc64el, skipping")
            aslr_expected = 1
        self.assertShellExitEquals(aslr_expected, ["./%s" % (target), area, "--verbose"], msg="%s:\n" % name)
        rc, report = self._test_aslr_rekey(area, target, name)
        self.assertEqual(expected, rc, report)

    def _test_aslr_all(self, area, expected, environment):
        target = "aslr"
        name = "%s native" % (environment)
        self._test_aslr_exec(area, expected, target, name)
        target = "aslr32"
        # ppc64el doesn't have a 32bit abi, even though CONFIG_COMPAT is enabled
        # s390x doesn't have a 31bit abi (I guess), even though CONFIG_COMPAT is enabled
        # arm64 can run armhf bins, gotta figure out how to compile them
        #   on arm64, though; -m32 doesn't work (LP: #1650498)
        if self._test_config('COMPAT') is False or not os.path.exists(target):
            return
        name = "%s COMPAT" % (environment)
        self._test_aslr_exec(area, expected, target, name)

    def _test_aslr(self, area, expected):
        os.chdir('aslr')
        build = ["make"]
        self.assertShellExitEquals(0, build)

        self._test_aslr_all(area, expected, "default %s" % area)

        # These tests run last since they change the rlimit that is restored
        # during per-test tearDown.
        # http://hmarco.org/bugs/CVE-2016-3672-Unlimiting-the-stack-not-longer-disables-ASLR.html
        resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
        self._test_aslr_all(area, expected, "unlimited stack %s" % area)

    # Dapper has stack
    def test_020_aslr_dapper_stack(self):
        '''ASLR of stack'''

        self._test_aslr('stack', 0)

    # Dapper i386 has mmap, libs
    def test_021_aslr_dapper_mmap(self):
        '''ASLR of mmap'''

        expected = 0
        if self.dpkg_arch != 'i386' and not self.kernel_at_least('2.6.20'):
            self._skipped("only i386 or Feisty and later")
            expected = 1
        else:
            # Arch-specific
            if self.dpkg_arch not in self.aslr_archs:
                self._skipped("only x86 (and armel after 10.04)")
                expected = 1

        self._test_aslr('mmap', expected)

    def test_021_aslr_dapper_libs(self):
        '''ASLR of libs'''

        expected = 0
        if self.dpkg_arch != 'i386' and not self.kernel_at_least('2.6.20'):
            self._skipped("only i386 or Feisty and later")
            expected = 1
        else:
            # Arch-specific
            if self.dpkg_arch not in self.aslr_archs:
                self._skipped("only x86 (and ARM 10.10 and later")
                expected = 1

        self._test_aslr('libs', expected)

    # Hardy has all but brk
    def test_022_aslr_hardy_text(self):
        '''ASLR of text'''

        expected = 0
        if not self.kernel_at_least('2.6.24'):
            self._skipped("only Hardy and later")
            expected = 1
        else:
            # Arch-specific
            if self.dpkg_arch not in self.aslr_archs:
                self._skipped("only x86 (and ARM 10.10 and later)")
                expected = 1

        self._test_aslr('text', expected)

    def test_022_aslr_hardy_vdso(self):
        '''ASLR of vdso'''

        expected = 0
        if not self.kernel_at_least('2.6.24'):
            self._skipped("only Hardy and later")
            expected = 1
        else:
            # Arch-specific
            if self.dpkg_arch not in ['i386', 'amd64', 'ppc64el', 'arm64', 's390x']:
                self._skipped("only x86, ppc64el, arm64, and s390x")
                expected = 1

        self._test_aslr('vdso', expected)

    # Intrepid and newer have all
    def test_022_aslr_intrepid_brk(self):
        '''ASLR of brk'''

        expected = 0
        if not self.kernel_at_least('2.6.27'):
            self._skipped("only Intrepid and later")
            expected = 1
        else:
            # Arch-specific
            if self.dpkg_arch not in self.aslr_archs:
                self._skipped("only x86 (and ARM after 10.04)")
                expected = 1

        self._test_aslr('brk', expected)

    # Wily and newer have mmap/pie split ASLR
    def test_023_aslr_wily_pie(self):
        '''ASLR of text vs libs'''

        expected = 0
        if not self.kernel_at_least('4.1'):
            self._skipped("only Wily and later")
            expected = 1
            # disabling for now, it's hitting a false positive on older
            # kernels
            return

        self._test_aslr('pie', expected)

    def test_150_privileged_user_namespaces(self):
        '''test whether user namespaces work at all (with root)'''

        os.chdir('userns')

        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(0, ['./userns', '-U'])

    def test_150_unprivileged_user_namespaces(self):
        '''test whether user namespaces work as unprivileged user'''

        os.chdir('userns')
        expected = 0

        if not self.kernel_at_least('3.8'):
            self._skipped("unprivileged user ns was not allowed before trusty")
            expected = 1

        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, ['sudo', '-u', os.environ['SUDO_USER'], './userns', '-U'])

    def test_150_sysctl_disables_unpriv_userns(self):
        '''unprivileged_userns_clone sysctl supported'''

        expected = 1
        exists = True
        if not self.kernel_at_least('3.11'):
            self._skipped("unprivileged user ns disable sysctl did not exist before trusty")
            expected = 0
            exists = False

        self._test_sysctl_value('kernel/unprivileged_userns_clone', expected, exists=exists)

    def test_151_sysctl_disables_bpf_unpriv_userns(self):
        '''unprivileged_bpf_disabled sysctl supported'''

        expected = 2
        exists = True
        if not self.kernel_at_least('4.4'):
            self._skipped("unprivileged bpf disable sysctl did not exist before xenial")
            expected = 1
            exists = False

        self._test_sysctl_value('kernel/unprivileged_bpf_disabled', expected, exists=exists)

    def test_152_sysctl_disables_apparmor_unpriv_userns(self):
        '''unprivileged_userns_apparmor_policy sysctl supported'''

        expected = 1
        exists = True
        if not self.kernel_at_least('4.4'):
            self._skipped("unprivileged apparmor disable sysctl did not exist before xenial")
            exists = False

        self._test_sysctl_value('kernel/unprivileged_userns_apparmor_policy', expected, exists=exists)

    def test_160_setattr_CVE_2015_1350(self):
        '''Ensure unpriv user cannot strip setattr attributes via chown() (CVE-2015-1350)'''

        tmpdir = tempfile.mkdtemp(prefix='setattr-')
        os.chmod(tmpdir, 0o755)
        shutil.copy('/bin/true', tmpdir)

        user = os.environ['SUDO_USER']
        testbin = os.path.join(tmpdir, 'true')
        self.assertShellExitEquals(0, ['setcap', 'cap_sys_nice+ep', testbin])

        if testlib.dpkg_compare_installed_version('libcap2', 'ge', '1:2.42-2'):
            exp_output = '%s cap_sys_nice=ep\n' % testbin
        else:
            exp_output = '%s = cap_sys_nice+ep\n' % testbin
        self.assertShellOutputEquals(exp_output, ['sudo', '-u', user, 'getcap', testbin])

        # chown should fail, but also should not clear fs caps
        self.assertShellExitEquals(1, ['sudo', '-u', user, 'chown', user, testbin])

        if not self.kernel_at_least('4.4'):
            self._skipped("Kernels before 4.4 need to fix CVE-2015-1350")
            exp_output = ''
        self.assertShellOutputEquals(exp_output, ['sudo', '-u', user, 'getcap', testbin])

        shutil.rmtree(tmpdir, ignore_errors=True)

    def test_170_nf_conntrack_helper_CVE_2017_17448(self):
        '''Ensure unpriv userns can't access nf conntrack helper functions (CVE-2017-17448)'''

        if not self.lsb_release['Release'] > 14.04:
            self._skipped('nfct does not exist in 14.04 and older releases')
            return 0
        if not self._test_config('NF_CONNTRACK'):
            self._skipped('CONFIG_NF_CONNTRACK not enabled in kernel config')
            return 0

        nfct = '/usr/sbin/nfct'
        if not os.path.exists(nfct):
            self._skipped('nfct is not installed')
            return 0

        cmd = [nfct, 'helper', 'list']
        user = os.environ['SUDO_USER']

        # base case, should work as root
        self.assertShellExitEquals(0, cmd)

        # unpriv user
        unpriv_cmd = ['sudo', '-u', user] + cmd
        self.assertShellExitEquals(1, unpriv_cmd)

        # unpriv user in userns
        unshare_cmd = ['sudo', '-u', user, 'unshare', '--map-root-user', '--user', '--net'] + cmd
        self.assertShellExitEquals(1, unshare_cmd)

    def test_200_basic_setsockopt(self):
        '''Ensure basic setsockopt(SO_SNDBUF) works'''

        value = 10000
        exp_output = str(value * 2) + '\n'

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellOutputEquals(exp_output, ['./setsockopt', str(value)])

    def test_201_basic_unpriv_setsockopt(self):
        '''Ensure basic unpriv setsockopt(SO_SNDBUF) works'''

        value = 15000
        exp_output = str(value * 2) + '\n'
        cmd = ['sudo', '-u', os.environ['SUDO_USER'], './setsockopt', str(value)]

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellOutputEquals(exp_output, cmd)

    def test_202_negative_setsockopt_so_sndbuf(self):
        '''Ensure setsockopt(SO_SNDBUF) doesn't accept negative values'''

        expected = 0
        value = -10
        cmd = ['sudo', '-u', os.environ['SUDO_USER'], './setsockopt', '--', str(value)]

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        rc, report = testlib.cmd(cmd)
        result = 'Got exit code %d, expected %d\n' % (rc, expected)
        self.assertEqual(expected, rc, result + report)

        sndbuf = int(report)
        report = "setsockopt returned %s with input %d\n" % (report, value)
        self.assertGreater(sndbuf, 2000, report)
        self.assertLess(sndbuf, 10000000, report)

    def test_203_setsockopt_so_sndbuf_int_underflow(self):
        '''Ensure setsockopt(SO_SNDBUF) doesn't allow integer underflow (CVE-2012-6704)'''

        expected = 0
        value = -2100000000
        cmd = ['sudo', '-u', os.environ['SUDO_USER'], './setsockopt', '--', str(value)]

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        rc, report = testlib.cmd(cmd)
        result = 'Got exit code %d, expected %d\n' % (rc, expected)
        self.assertEqual(expected, rc, result + report)

        sndbuf = int(report)
        report = "setsockopt returned %s with input %d\n" % (report, value)
        self.assertGreater(sndbuf, 2000, report)
        self.assertLess(sndbuf, 10000000, report)

    def test_210_basic_setsockopt_sndbufforce(self):
        '''Ensure basic setsockopt(SO_SNDBUFFORCE) works'''

        value = 1000000
        exp_output = str(value * 2)

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellOutputContains(exp_output, ['./setsockopt', '-f', str(value)])

    def test_211_basic_unpriv_setsockopt_sndbufforce(self):
        '''Ensure basic unpriv setsockopt(SO_SNDBUFFORCE) is not permitted'''

        expected = 1
        value = 1500000
        cmd = ['sudo', '-u', os.environ['SUDO_USER'], './setsockopt', '-f', str(value)]

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        rc, report = testlib.cmd(cmd)
        result = 'Got exit code %d, expected %d\n' % (rc, expected)
        self.assertEqual(expected, rc, result + report)

    def test_212_basic_unpriv_namespace_setsockopt_sndbufforce(self):
        '''Ensure basic setsockopt(SO_SNDBUFFORCE) in a new unpriv namespace is not permitted'''

        # This will fail differently on precise/3.2 kernels where there aren't
        # unprivileged user namespaces.
        expected = 1
        value = 1400000
        cmd = ['sudo', '-u', os.environ['SUDO_USER'], './setsockopt', '-u', '-f', str(value)]

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        rc, report = testlib.cmd(cmd)
        result = 'Got exit code %d, expected %d\n' % (rc, expected)
        self.assertEqual(expected, rc, result + report)

    def test_213_setscokopt_sndbufforce_negative_value(self):
        '''Ensure setsockopt(SO_SNDBUFFORCE) does not accept negative values (CVE-2016-9793)'''

        expected = 0
        value = -40
        cmd = ['./setsockopt', '-f', '--', str(value)]

        os.chdir('setsockopt')
        self.assertShellExitEquals(0, ["make"])
        rc, report = testlib.cmd(cmd)
        result = 'Got exit code %d, expected %d\n' % (rc, expected)
        self.assertEqual(expected, rc, result + report)

        sndbuf = int(report)
        report = "setsockopt returned %s with input %d\n" % (report, value)
        self.assertGreater(sndbuf, 2000, report)
        self.assertLess(sndbuf, 10000000, report)

    def test_300_test_kaslr_base(self):
        '''Test to ensure base is not in default location where kaslr is enabled by default'''

        if not self._test_config('KALLSYMS') or not os.path.exists('/proc/kallsyms'):
            self._skipped('KALLSYMS is not enabled/available in this kernel')
            return

        default_address = 'ffffffff81000000'
        default_symbol = 'startup_64'

        if testlib.get_bits() == '32':
            default_address = 'c1000000'
            default_symbol = 'startup_32'
        elif not testlib.get_bits() == '64':
            raise self.failureException('Unexpected bit size for arch: %s' % testlib.get_bits())
        elif self.dpkg_arch in ['arm64']:
            default_address = '0000000000000000'
            default_symbol = 'stext'

        expected_equal = False
        if self.dpkg_arch not in ['amd64', 'i386', 'arm64']:
            # don't even bother with comparison
            self._skipped('kaslr is x86 and arm64 only ')
            return
        elif not self.kernel_at_least('4.15'):
            self._skipped('kaslr not enabled by default in kernels older than 4.15')
            expected_equal = True

        base_address = default_address
        with open('/proc/kallsyms', 'r') as proc_kallsyms:
            for addrline in proc_kallsyms:
                addr = addrline.strip().split()
                if addr[2] == default_symbol and addr[1] == 'T':
                    base_address = addr[0]

        if self.dpkg_arch in ['arm64']:
            self._skipped('FIXME: need to get a good default address for arm64')
            self._skipped('FIXME: address of stext: %s' % base_address)
            return

        self.assertEqual(base_address == default_address, expected_equal,
                         "The address of %s is '%s', non-kaslr epected %s, expected equality '%s'"
                         % (default_symbol, base_address, default_address, expected_equal))

    def test_350_retpolined_modules(self):
        '''Test to ensure all modules are built with retpoline on x86'''

        if self.dpkg_arch not in ['amd64', 'i386']:
            self._skipped('retpoline is x86 only ')
            return
        elif self.lsb_release['Release'] == 12.04:
            self._skipped("RETPOLINE compiler not in precise")
            return

        kernel_modules = self._get_all_kernel_modules()

        for module in kernel_modules:
            modinfo_output = self.assertShellExitEquals(0, ['modinfo', '-F', 'retpoline', module], bare_report=True)
            if modinfo_output.strip() != 'Y':
                # fallback is the vermagic field
                modinfo_output = self.assertShellExitEquals(0, ['modinfo', '-F', 'vermagic', module], bare_report=True)
                if 'retpoline' not in modinfo_output.strip().split():
                    error_output = self.assertShellExitEquals(0, ['modinfo', '-k', self.kernel_version, module])
                    raise self.failureException('Module %s not compiled with retpoline:\n%s' % (module, error_output))

    def test_360_stacksignal_memleak(self):
        '''Kernel memory does not leak to userspace in signalstack (CVE-2009-2847)'''

        expected = 0
        os.chdir('signalstack')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, self._unpriv_cmd(["./signal-stack"]))

    def test_361_memmove_leak(self):
        '''memmove does not leak bytes (CVE-2010-0415)'''

        os.chdir('memmove')
        self.assertShellExitEquals(0, ["make"])
        name = 'randomize_va_space'
        sysctl = '/proc/sys/kernel/%s' % (name)
        with open(sysctl) as fh:
            value = int(fh.read())
        self.assertNotEqual(value, 0, "%s must be non-zero for this test" % (sysctl))
        rc, report = testlib.cmd(self._unpriv_cmd(["./exp_sieve", name, '4']))
        if rc != 1:
            self.assertEqual(rc, 0, report)
            output = report.splitlines().pop().strip()
            self.assertTrue(output in ['00 00 00 00', 'ff ff ff ff'], report)

    def test_370_aio_CVE_2016_10044(self):
        '''ensure personality read-implies exec doesn't implicitly make mmap pages exec'''

        if self.kernel_is_ubuntu and \
           self.lsb_release['Release'] <= 12.04 and \
           not self.kernel_at_least('3.13'):
            return self._skipped("Skipped: 12.04 release kernel will remain unfixed")
        os.chdir('aio')
        self.assertShellExitEquals(0, ["make"])
        search = ' rw-s '
        self.assertShellOutputContains(search, self._unpriv_cmd(['./CVE-2016-10044']))

    def test_380_compat_syscall(self):
        '''Kernel correctly filters compat syscalls (CVE-2010-3301)'''

        os.chdir('compat')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellOutputContains("UID 0,", self._unpriv_cmd(["./CVE-2010-3301"]), invert=True)

    def test_381_compat_alloc_userspace(self):
        '''Kernel correctly calls access_ok on compat_alloc_userspace (CVE-2010-3081)'''

        if self.lsb_release['Release'] == 14.04:
            return self._skipped("Skipped: FTBFS on Trusty's GCC")

        os.chdir('compat')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(1, self._unpriv_cmd(['./CVE-2010-3081']))

    def test_400_kernel_security_lockdown(self):
        '''Kernel lockdown enabled in /sys/kernel/security/lockdown'''
        if not self.kernel_at_least('5.4'):
            return self._skipped("Kernel lockdown not available before 5.4")

        # if secure boot is not enabled, lockdown will not be enabled so skip
        # the test in that case as well
        rc, output = self.shell_cmd(['mokutil', '--sb-state'])
        if rc != 0 or 'SecureBoot enabled' not in output:
            return self._skipped("SecureBoot not enabled, lockdown will not be enabled")

        self.assertTrue(os.path.exists('/sys/kernel/security/lockdown'))
        expected = "none [integrity] confidentiality"
        with open('/sys/kernel/security/lockdown') as fh:
            self.assertEqual(fh.read().strip(), expected)


class KernelSecurityConfigTest(KernelSecurityBaseTest):
    '''Test kernel security related config options'''

    def test_010_kaslr_config(self):
        '''kernel ASLR enabled'''

        # FIXME: at runtime, kaslr currently is disabled because it
        # conflicts with hibernate and Ubuntu enables hibernate in its
        # kernel config. When that is fixed upstream, then we can add
        # a runtime test to ensure that kaslr is actually in effect.
        expected = True
        archs = ['i386', 'amd64']
        # ASLR support added for s390x in Linux 5.2
        if self.kernel_at_least('5.2'):
            archs += ['s390x']

        if not self.kernel_at_least('3.16.0'):
            self._skipped("kaslr is only utopic and later")
            expected = False
        elif self.dpkg_arch in ['arm64']:
            if not self.kernel_at_least('4.8.0'):
                self._skipped("kaslr in arm64 only in 4.10 and later")
                expected = False
        elif self.dpkg_arch not in archs:
            self._skipped("kaslr is x86 and s390x (since 5.2) only")
            expected = False
        self.assertKernelConfig('RANDOMIZE_BASE', expected)

    def test_020_kaslr_memory_config(self):
        '''kernel ASLR enabled for memory'''

        # FIXME: at runtime, kaslr currently is disabled because it
        # conflicts with hibernate and Ubuntu enables hibernate in its
        # kernel config. When that is fixed upstream, then we can add
        # a runtime test to ensure that kaslr is actually in effect.
        expected = True
        if not self.kernel_at_least('4.8.0'):
            self._skipped("kaslr memory is only yakkety and later")
            expected = False
        elif self.dpkg_arch not in ['amd64']:
            self._skipped("kaslr memory is amd64 only")
            expected = False
        self.assertKernelConfig('RANDOMIZE_MEMORY', expected)

    def test_030_config_brk(self):
        '''CONFIG_COMPAT_BRK disabled'''

        self.assertKernelConfigUnset('COMPAT_BRK')

    # Hardy and newer, but is a negative test so will pass on earlier
    def test_040_config_devkmem(self):
        '''CONFIG_DEVKMEM disabled'''

        expected = False
        if self.lsb_release['Release'] == 9.10 and self.kernel_version.endswith('-ec2'):
            self._skipped("ignored on Karmic EC2")
            expected = True

        self.assertKernelConfig('DEVKMEM', expected)

    # All releases
    def test_050_config_seccomp(self):
        '''CONFIG_SECCOMP enabled'''

        expected = True
        if self.dpkg_arch in self.arm_archs and \
           not self.kernel_at_least('2.6.38'):
            expected = False
            self._skipped("ignored ARM before 2.6.38")
        if self.dpkg_arch == 'arm64' and \
           not self.kernel_at_least('3.19.0'):
            expected = False
            self._skipped("ignored ARM64 before 3.19.0")
        self.assertKernelConfig('SECCOMP', expected)

    def test_055_config_seccomp_filter(self):
        '''CONFIG_SECCOMP_FILTER enabled'''

        expected = True
        if not self.kernel_at_least('3.2.0'):
            expected = False
            self._skipped("SECCOMP_FILTER introduced in 3.2 kernel")
        elif not self.kernel_at_least('3.19.0') and self.dpkg_arch == 'arm64':
            expected = False
            self._skipped("SECCOMP_FILTER not present in ARM64 before 3.19 kernels")
        elif not self.kernel_at_least('4.2.0') and self.dpkg_arch == 'ppc64el':
            expected = False
            self._skipped("SECCOMP_FILTER not present in ppc64 before 4.2 kernels")
        self.assertKernelConfig('SECCOMP_FILTER', expected)

    # All releases
    def test_060_config_syn_cookies(self):
        '''CONFIG_SYN_COOKIES enabled'''
        self.assertKernelConfigSet('SYN_COOKIES', nomodule=True)

    # All releases
    # FIXME: it'd be nice to test in a more direct fashion
    def test_070_config_security(self):
        '''CONFIG_SECURITY enabled'''
        self.assertKernelConfigSet('SECURITY', nomodule=True)

    # All releases
    # FIXME: it'd be nice to test in a more direct fashion
    def test_080_config_security_selinux(self):
        '''CONFIG_SECURITY_SELINUX enabled'''
        self.assertKernelConfigSet('SECURITY_SELINUX', nomodule=True)

    def test_081_config_security_selinux_disable(self):
        '''Ensure CONFIG_SECURITY_SELINUX_DISABLE is disabled (LP: #1680315)'''

        expected = False
        if not self.kernel_at_least('4.12'):
            # Don't bother checking before 4.12 because RO after init
            # LSM structs is not supported prior to then.
            self.reportConfig('SECURITY_SELINUX_DISABLE',
                              "Kernels before 4.12 don't support LSM hooks being RO after init, " +
                              "so disabling CONFIG_SECURITY_SELINUX_DISABLE is not necessary")
            return

        self.assertKernelConfig('SECURITY_SELINUX_DISABLE', expected)

    # Intrepid and newer
    # FIXME: it'd be nice to test in a more direct fashion
    def test_090_config_security_smack(self):
        '''CONFIG_SECURITY_SMACK enabled'''
        self.assertKernelConfigSet('SECURITY_SMACK', nomodule=True)

    # FIXME: it'd be nice to test in a more direct fashion
    def test_100_config_security_tomoyo(self):
        '''CONFIG_SECURITY_TOMOYO enabled'''
        self.assertKernelConfigSet('SECURITY_TOMOYO', nomodule=True)

    # Hardy and newer (Gutsy was a direct patch)
    def test_110_config_security_apparmor(self):
        '''CONFIG_SECURITY_APPARMOR enabled'''

        self.assertKernelConfigSet('SECURITY_APPARMOR', nomodule=True)

        # LSM stacking is partially supported upstream as of kernel version
        # 5.1. The patches were backported to Ubuntu's 5.0 kernel which was
        # originally shipped in Ubuntu 19.04. If upstream LSM stacking is not
        # supported, we need to verify the old config options.
        #
        # This block, which verifies the old config options, can be removed
        # once Ubuntu 18.04 is no longer supported/maintained in April 2028.
        if not self.kernel_at_least('5.1') and \
           not (self.kernel_is_ubuntu and self.kernel_at_least('5.0')):
            default_apparmor_option = 'DEFAULT_SECURITY_APPARMOR'
            if self.kernel_at_least('4.13') and not self.kernel_at_least('4.14'):
                default_apparmor_option = 'SECURITY_APPARMOR_STACKED'

            self.assertKernelConfigSet(default_apparmor_option, nomodule=True)
            self.assertEqual(self._get_config('SECURITY_APPARMOR_BOOTPARAM_VALUE'), '1')
            return

        self.assertTrue('apparmor' in self._get_config('LSM').strip('"').split(','))

    # Everything except i386 Gutsy
    def test_120_config_compat_vdso(self):
        '''CONFIG_COMPAT_VDSO disabled'''

        expected = False
        # CONFIG_COMPAT_VDSO added for s390x in 5.2 and cannot be deselected
        # (except when building with clang).
        if self.dpkg_arch == 's390x' and self.kernel_at_least('5.2') and \
           not self.kernel_at_least('5.5'):
            expected = True

        self.assertKernelConfig('COMPAT_VDSO', expected)

    # Gutsy and newer
    # FIXME: actually attempt to load a module that has a rwx data area
    def test_130_config_debug_rodata(self):
        '''CONFIG_DEBUG_RODATA/CONFIG_STRICT_KERNEL_RWX enabled'''

        expected = True
        option = 'DEBUG_RODATA'
        # DEBUG_RODATA renamed to STRICT_KERNEL_RWX in 4.11
        if self.kernel_at_least('4.11'):
            option = 'STRICT_KERNEL_RWX'
        elif not self._test_config('DEBUG_KERNEL'):
            # pre 4.11 strict RO data depended on the CONFIG_DEBUG_KERNEL option.
            self._skipped("DEBUG_KERNEL disabled on this kernel, DEBUG_RODATA depends on it")
            expected = False

        # Enabled in a security update for pre-Intrepid
        if not self.kernel_at_least('2.6.22'):
            self._skipped("only Gutsy and later")
            expected = False
        else:
            # powerpc never had it
            if self.dpkg_arch in ['powerpc']:
                self._skipped("Not supported/enabled on powerpc")
                expected = False
            # ppc6el support added in 5.13
            if self.dpkg_arch in ['ppc64el'] and not self.kernel_at_least('5.13'):
                self._skipped("Not enabled on ppc64el before 5.13")
                expected = False
            # s390x only enabled it in 4.8/yakkety (LP: #1653889)
            if self.dpkg_arch in ['s390x'] and not self.kernel_at_least('4.8'):
                self._skipped("Not enabled on s390x before yakkety/4.8")
                expected = False
            # Hardy Xen doesn't have it?
            if self.lsb_release['Release'] == 8.04 and \
               self.kernel_version.endswith('-xen'):
                self._skipped("ignored on Hardy Xen")
                expected = False

        self.assertKernelConfig(option, expected)

    # Natty and newer
    # FIXME: it'd be nice to test in a more direct fashion
    def test_140_config_debug_set_module_ronx(self):
        '''CONFIG_DEBUG_SET_MODULE_RONX/CONFIG_STRICT_MODULE_RWX enabled'''

        expected = True
        option = 'DEBUG_SET_MODULE_RONX'
        # DEBUG_SET_MODULE_RONX renamed to STRICT_MODULE_RWX in 4.11
        if self.kernel_at_least('4.11'):
            option = 'STRICT_MODULE_RWX'

        if not self._test_config('MODULES'):
            self._skipped("CONFIG_MODULES disabled on this kernel, DEBUG_SET_MODULE_RONX depends on it")
            expected = False
        elif not self.kernel_at_least('2.6.38'):
            self._skipped("only Natty and later")
            expected = False
        elif self.dpkg_arch not in self.module_ronx_archs:
            self._skipped("only x86")
            expected = False

        self.assertKernelConfig(option, expected)

    # Hardy and newer
    def test_150_config_strict_devmem(self):
        '''CONFIG_STRICT_DEVMEM enabled'''

        # if kernel doesn't have CONFIG_DEVMEM enabled at all, then
        # don't need to check for STRICT_DEVMEM, etc. CONFIG_DEVMEM only
        # became a configurable option in 3.19 however.
        if self.kernel_at_least('3.19') and not self._test_config('DEVMEM'):
            self._skipped("CONFIG_DEVMEM not enabled, skipping checks")
            return

        nonpromisc = False
        strict = True
        if not self.kernel_at_least('2.6.27'):
            strict = False
            if self.kernel_at_least('2.6.24'):
                # named "NONPROMISC_DEVMEM" in Hardy
                nonpromisc = True
            else:
                self._skipped("only Hardy and later")
        else:
            # Arch-specific
            if self.dpkg_arch not in ['i386', 'amd64', 'armel', 'armhf', 'arm64', 'ppc64el', 's390x']:
                self._skipped("x86, ppc64, and ARM only")
                strict = False
            if self.dpkg_arch in self.arm_archs and \
               not self.kernel_at_least('2.6.38'):
                self._skipped("only 2.6.38 and later for ARM")
                strict = False
            if self.dpkg_arch == 'arm64' and \
               not self.kernel_at_least('3.16.0'):
                self._skipped("only 3.16 and later for ARM64")
                strict = False

        self.assertKernelConfig('NONPROMISC_DEVMEM', nonpromisc)
        self.assertKernelConfig('STRICT_DEVMEM', strict)

    # Intrepid and newer
    # FIXME: it'd be nice to test in a more direct fashion
    def test_160_config_security_file_capabilities(self):
        '''CONFIG_SECURITY_FILE_CAPABILITIES enabled'''

        expected = True
        if not self.kernel_at_least('2.6.27') or self.kernel_at_least('2.6.35'):
            # Maverick and later have it always on
            self._skipped("only Intrepid through Lucid")
            expected = False

        self.assertKernelConfig('SECURITY_FILE_CAPABILITIES', expected)

    # FIXME: add direct capability testing

    # Jaunty and newer
    def test_170_config_security_default_mmap_min_addr(self):
        '''CONFIG_DEFAULT_MMAP_MIN_ADDR'''

        # Min expectation, based on architecture
        expected = '65536'
        # for arm64, see LP: #1415481
        if self.dpkg_arch in self.arm_archs or self.dpkg_arch == 'arm64':
            expected = '32768'
        if self.lsb_release['Release'] == 9.10 and self.kernel_version.endswith('-ec2'):
            # Karmic's EC2 has:
            #  CONFIG_DEFAULT_MMAP_MIN_ADDR=4096
            #  CONFIG_LSM_MMAP_MIN_ADDR=65536
            self.announce("weird: Karmic EC2")
            expected = '4096'

        config = 'DEFAULT_MMAP_MIN_ADDR'
        if not self.kernel_at_least('2.6.24'):
            config = 'SECURITY_' + config
            self.announce(config)

        if not self.kernel_at_least('2.6.24'):
            self._skipped("only Hardy and later")
            expected = None
            if self.kernel_at_least('2.6.21'):
                # Existed, but was still set to 0
                expected = '0'
        else:
            self.announce(expected)

        self.assertEqual(self._get_config(config), expected,
                         'config %s was expected to bet set to %s' % (config, expected))

    def is_stackprotector_available(self):

        result = True

        if not self.kernel_at_least('2.6.31'):
            if self.lsb_release['Release'] == 8.04 and self.dpkg_arch == 'amd64':
                pass
            else:
                self._skipped("only Hardy amd64 or Karmic and later")
                result = False
        else:
            if self.dpkg_arch in self.arm_archs and \
               not self.kernel_at_least('2.6.35'):
                self._skipped("not available on ARM before 10.10")
                result = False
            if self.dpkg_arch in ['arm64'] and \
               not self.kernel_at_least('4.4'):
                self._skipped("arm64 didn't get stack-protector enabled until after 3.13")
                result = False
            if self.lsb_release['Release'] == 9.10 and self.kernel_version.endswith('-ec2'):
                self._skipped("ignored on Karmic EC2")
                result = False
            if self.dpkg_arch in ['powerpc']:
                self._skipped("not available on 32-bit powerpc")
                result = False
            if self.dpkg_arch in ['ppc64', 'ppc64el'] and \
               not self.kernel_at_least('4.20'):
                self._skipped("not available on powerpc before disco")
                result = False
            if self.dpkg_arch in ['s390x']:
                self._skipped("not available on s390x")
                result = False
            if self.dpkg_arch in ['riscv64'] and not self.kernel_at_least('5.9'):
                self._skipped("not available on riscv64")
                result = False

        return result

    def test_180_config_stack_protector(self):
        '''CONFIG_CC_STACKPROTECTOR set'''

        config_option = 'CC_STACKPROTECTOR'
        if self.kernel_at_least('4.18'):
            config_option = 'STACKPROTECTOR'
        elif self.kernel_at_least('4.16'):
            # 4.16-4.17 is a goofy special case, where the plain version
            # does not exist. Use CC_STACKPROTECTOR_STRONG instead
            config_option = 'CC_STACKPROTECTOR_STRONG'

        expected = 'y'
        if not self.is_stackprotector_available():
            expected = None

        self.assertKernelConfig(config_option, expected)

    def test_185_config_stack_protector_strong(self):
        '''CONFIG_CC_STACKPROTECTOR_STRONG set'''

        config_option = 'CC_STACKPROTECTOR_STRONG'
        if self.kernel_at_least('4.18'):
            config_option = 'STACKPROTECTOR_STRONG'

        expected = 'y'
        if not self.is_stackprotector_available():
            expected = None
        if not self.kernel_at_least('3.16') or not self.lsb_release['Release'] > 14.04:
            # trusty's 3.13 has support for stackprotector strong but
            # only has regular enabled because gcc-4.8 does not support
            # the option.
            # FIXME - should test for availability in gcc instead.
            self._skipped("STACKPROTECTOR_STRONG introduced in 3.14,")
            self._skipped("-fstack-protector-strong introduced in gcc-4.9,")
            expected = None

        self.assertKernelConfig(config_option, expected)

    def test_190_config_have_stack_protector(self):
        '''CONFIG_HAVE_CC_STACKPROTECTOR set'''

        config_option = 'HAVE_CC_STACKPROTECTOR'
        if self.kernel_at_least('4.18'):
            config_option = 'HAVE_STACKPROTECTOR'

        expected = True
        # precise's kernel did not have the auto detected config option
        if not self.kernel_at_least('3.13') or not self.is_stackprotector_available():
            expected = False

        self.assertKernelConfig(config_option, expected)

    def test_200_config_security_acl_ext3(self):
        '''CONFIG_EXT3_FS_SECURITY set (LP: #1295948)'''

        # if CONFIG_EXT4_USE_FOR_EXT23, then we can rely on the
        # CONFIG_EXT4_FS_SECURITY check
        if self.kernel_at_least('4.3'):
            self._skipped("4.3 and later are only ext4 for ext3")
        elif self._test_config('EXT4_USE_FOR_EXT23'):
            self._skipped("Kernel is configured to use ext4 for ext3")
        else:
            self.assertKernelConfigSet('EXT3_FS_SECURITY')

    def test_210_config_security_acl_ext4(self):
        '''CONFIG_EXT4_FS_SECURITY set (LP: #1295948)'''
        self.assertKernelConfigSet('EXT4_FS_SECURITY')

    def test_220_config_security_ecryptfs(self):
        '''CONFIG_ECRYPT_FS is set'''
        self.assertKernelConfigSet('ECRYPT_FS')

    # Taken from strongSwan wiki:
    # http://wiki.strongswan.org/projects/strongswan/wiki/KernelModules
    def test_230_config_security_ipsec(self):
        '''Config options for IPsec'''
        configs = [
            'XFRM_USER', 'NET_KEY', 'INET', 'IP_ADVANCED_ROUTER',
            'IP_MULTIPLE_TABLES', 'INET_AH', 'INET_ESP', 'INET_IPCOMP',
            'IPV6', 'INET6_AH', 'INET6_ESP', 'INET6_IPCOMP',
            'IPV6_MULTIPLE_TABLES', 'NETFILTER', 'NETFILTER_XTABLES',
            'NETFILTER_XT_MATCH_POLICY'
        ]
        if not self.kernel_at_least('5.2'):
            # 5.2 kernel dropped these configs (commit
            # 4c145dce26013763490df88f2473714f5bc7857d)
            configs.extend([
                'INET_XFRM_MODE_TRANSPORT', 'INET_XFRM_MODE_TUNNEL',
                'INET_XFRM_MODE_BEET', 'INET6_XFRM_MODE_TRANSPORT',
                'INET6_XFRM_MODE_TUNNEL', 'INET6_XFRM_MODE_BEET',
            ])
            self._skipped("Before 5.2: adding specific XFRM configs to check")

        for config in configs:
            self.assertKernelConfigSet(config)

    def test_240_SLAB_freelist_randomization(self):
        '''Ensure CONFIG_SLAB_FREELIST_RANDOM is set'''
        config_name = 'SLAB_FREELIST_RANDOM'
        if not self.kernel_at_least('4.8'):
            self._skipped("CONFIG_SLAB_FREELIST_RANDOM enabled in linux v4.8")
        elif not (self._test_config('SLAB') or self._test_config('SLUB')):
            self._skipped("freelist randomization requires SLAB or SLUB allocators")
            self.assertKernelConfigUnset(config_name)
        else:
            self.assertKernelConfigSet(config_name)

    def test_250_SLAB_freelist_hardening(self):
        '''Ensure CONFIG_SLAB_FREELIST_HARDENED is set'''
        config_name = 'SLAB_FREELIST_HARDENED'
        if not self.kernel_at_least('4.14'):
            self._skipped("CONFIG_SLAB_FREELIST_HARDENED only in linux v4.14 and newer")
            self.assertKernelConfigUnset(config_name)
        elif not self._test_config('SLUB'):
            self._skipped("CONFIG_SLAB_FREELIST_HARDENED depends on CONFIG_SLUB")
            self.assertKernelConfigUnset(config_name)
        else:
            self.assertKernelConfigSet(config_name)

    def test_260_config_PTI(self):
        '''Ensure kernel page table isolation is set appropriately'''

        expected = True
        archs = ['amd64']
        # KPTI for i386 landed upstream in 4.19 and was backported to the
        # Bionic 4.15 kernel starting with 4.15.0-48.51. It has not been
        # backported to the Cosmic 4.18 kernel.
        if self.kernel_at_least('4.19') or \
           (self.kernel_is_ubuntu and self.kernel_at_least('4.15') and \
            not self.kernel_at_least('4.16')):
            archs += ['i386']
        if self.dpkg_arch not in archs:
            self._skipped("KPTI only in amd64 and i386 (4.19 and later)")
            expected = False
        if self.kernel_at_least('6.9'):
            self._skipped("KPTI renamed to MITIGATION_PAGE_TABLE_ISOLATION since v6.9 (commit ea4654e upstream)")
            expected = False
        self.assertKernelConfig('PAGE_TABLE_ISOLATION', expected)

    def test_261_config_MPTI(self):
        '''Ensure CPU mitigations related kernel page table isolation is set appropriately'''

        expected = True
        archs = ['amd64']
        # PAGE_TABLE_ISOLATION renamed into MITIGATION_PAGE_TABLE_ISOLATION since v6.9
        # commit ea4654e088 upstream
        if not self.kernel_at_least('6.9'):
            self._skipped("KMPTI is called PAGE_TABLE_ISOLATION before v6.9")
            expected = False
        if self.dpkg_arch not in archs:
            self._skipped("KMPTI only in amd64")
            expected = False
        self.assertKernelConfig('MITIGATION_PAGE_TABLE_ISOLATION', expected)

    def test_265_config_retpoline(self):
        '''Ensure retpoline configuration option is set'''

        expected = True
        if self.dpkg_arch not in ['i386', 'amd64']:
            self._skipped("RETPOLINE is x86-only")
            expected = False
        elif not self.kernel_at_least('3.3'):
            # We enable RETPOLINE in the linux-lts-trusty/3.13 kernel to
            # gain some protections even though precise's compiler does
            # not support retpoline
            self.reportConfig('RETPOLINE', "RETPOLINE config not supported in precise/3.2 kernel")
            return
        elif self.kernel_at_least('6.8'):
            # RETPOLINE was renamed into MITIGATION_RETPOLINE since v6.8
            # commit aefb2f2e61 upstream
            self.reportConfig('RETPOLINE', "RETPOLINE config was renamed into MITIGATION_RETPOLINE since v6.8")
            return

        self.assertKernelConfig('RETPOLINE', expected)

    def test_266_config_mitigation_retpoline(self):
        '''Ensure mitigation retpoline configuration option is set'''

        expected = True
        if self.dpkg_arch not in ['i386', 'amd64']:
            self._skipped("RETPOLINE is x86-only")
            expected = False
        elif not self.kernel_at_least('6.9'):
            # MITIGATION_RETPOLINE was renamed from RETPOLINE since v6.9
            # commit aefb2f2e61 upstream
            self.reportConfig('MITIGATION_RETPOLINE', "MITIGATION_RETPOLINE config was renamed from RETPOLINE since v6.9")
            return

        self.assertKernelConfig('MITIGATION_RETPOLINE', expected)

    def test_270_config_PTI_arm64(self):
        '''Ensure kernel page table isolation is set'''

        expected = True
        if self.dpkg_arch not in ['arm64'] or not self.kernel_at_least('4.13'):
            self._skipped("KPTI only in arm64 4.13 and newer")
            expected = False
        self.assertKernelConfig('UNMAP_KERNEL_AT_EL0', expected)

    def test_280_config_vmap_stack(self):
        '''Ensure kernel stack isolation is set'''

        expected = True
        if not (self.dpkg_arch == 'amd64' and self.kernel_at_least('4.9')) and \
           not (self.dpkg_arch == 'arm64' and self.kernel_at_least('4.13')) and \
           not (self.dpkg_arch == 's390x' and self.kernel_at_least('4.20')):
            self._skipped("CONFIG_VMAP_STACK only in amd64, arm64, and s390x")
            expected = False
        self.assertKernelConfig('VMAP_STACK', expected)

    def test_290_config_hardened_usercopy(self):
        '''Ensure CONFIG_HARDENED_USERCOPY is set'''

        config_name = 'HARDENED_USERCOPY'
        if not ((self.kernel_at_least('6.5') or self._test_config('HAVE_HARDENED_USERCOPY_ALLOCATOR')) and
                self._test_config('STRICT_DEVMEM')):
            self._skipped("HARDENED_USERCOPY depends on the allocator and strict devmem")
            self.assertKernelConfigUnset(config_name)
        else:
            self.assertKernelConfigSet(config_name)

    def test_300_config_kernel_fortify(self):
        '''Ensure CONFIG_FORTIFY_SOURCE is set'''

        config_name = 'FORTIFY_SOURCE'
        if not self._test_config('ARCH_HAS_FORTIFY_SOURCE'):
            self._skipped("CONFIG_FORTIFY_SOURCE depends on the arch supporting it")
            self.assertKernelConfigUnset(config_name)
        else:
            self.assertKernelConfigSet(config_name)

    # XXX: should add tests that check the implementation of this
    def test_310_config_security_perf_events_restrict(self):
        '''Ensure CONFIG_SECURITY_PERF_EVENTS_RESTRICT is set'''

        # This config option is added by the commit subject:
        # UBUNTU: SAUCE: security,perf: Allow further restriction of perf_event_open

        config_name = 'SECURITY_PERF_EVENTS_RESTRICT'
        expected = True
        if not self.kernel_at_least('4.8'):
            self._skipped("CONFIG_SECURITY_PERF_EVENTS_RESTRICT only in 4.8 and newer")
            expected = False
        elif not self._test_config('PERF_EVENTS'):
            self._skipped("CONFIG_SECURITY_PERF_EVENTS_RESTRICT depends on CONFIG_PERF_EVENTS being set")
            expected = False

        self.assertKernelConfig(config_name, expected)

    # XXX: should add tests that check the implementation of this
    def test_320_config_arm_pan(self):
        '''Ensure PAN for arm processors is set'''

        expected = True
        config_name = 'ARM64_SW_TTBR0_PAN'

        if not (self.dpkg_arch in self.arm_archs or self.dpkg_arch == 'arm64'):
            self._skipped("PAN is an arm arch feature only")
            expected = False
        elif self.dpkg_arch in self.arm_archs:
            config_name = 'CONFIG_CPU_SW_DOMAIN_PAN'
            if not self.kernel_at_least('4.4'):
                self._skipped('CONFIG_CPU_SW_DOMAIN_PAN added/enabled in 4.4 and newer')
                expected = False
            else:
                self.announce('32bit arm processor, looking for CONFIG_CPU_SW_DOMAIN_PAN')
        elif not self.kernel_at_least('4.10'):
            self._skipped('CONFIG_ARM64_SW_TTBR0_PAN added/enabled in 4.15 and newer')
            expected = False
        else:
            self.announce('arm64 processor, looking for CONFIG_ARM64_SW_TTBR0_PAN')

        self.assertKernelConfig(config_name, expected)

    @unittest.skipIf(
        testlib.manager.dpkg_arch != 'arm64',
        "CONFIG_ARM64_PTR_AUTH is arm64 only"
    )
    def test_325_config_arm64_ptr_auth(self):
        '''Ensure ARM64_PTR_AUTH for arm64 processors is set'''

        expected = True
        if not self.kernel_at_least('5.0'):
            self._skipped("CONFIG_ARM64_PTR_AUTH introduced in 5.0 kernels")
            expected = False
        self.assertKernelConfig('ARM64_PTR_AUTH', expected)

    @unittest.skipIf(
        testlib.manager.dpkg_arch != 'arm64',
        "CONFIG_ARM64_PTR_AUTH_KERNEL is arm64 only"
    )
    def test_326_config_arm64_ptr_auth_kernel(self):
        '''Ensure ARM64_PTR_AUTH_KERNEL for arm64 processors is set'''

        expected = True
        if not self.kernel_at_least('5.14'):
            self._skipped("CONFIG_ARM64_PTR_AUTH_KERNEL introduced in 5.14 kernels")
            expected = False
        self.assertKernelConfig('ARM64_PTR_AUTH_KERNEL', expected)

    def test_330_config_debug_wx(self):
        '''Ensure DEBUG_WX is set'''

        expected = True
        if not (self.dpkg_arch in ['amd64', 'i386', 'arm64'] or
                (self.dpkg_arch in ['s390x'] and self.kernel_at_least('5.10')) or
                (self.dpkg_arch in ['ppc64el'] and self.kernel_at_least('5.15'))):
            self._skipped("DEBUG_WX is an x86, arm64, s390x (5.10 and later) and ppc64el (5.15 and later) arch feature only")
            expected = False
        elif not self.kernel_at_least('4.4'):
            # commit for DEBUG_WX was backported to 4.4, but only
            # enabled in linux-kvm kernel. Generic and other derived
            # kernels only got it enabled in 4.13. See LP: #1788338
            self._skipped('CONFIG_DEBUG_WX added in 4.4 and newer')
            expected = False
        elif not self.kernel_at_least('4.13') and not self.kernel_version.endswith('-kvm'):
            self._skipped('CONFIG_DEBUG_WX added/enabled in 4.13 and newer, for non-kvm kernels')
            expected = False
        self.assertKernelConfig('DEBUG_WX', expected)

    def test_340_config_vmap_stack(self):
        '''Ensure VMAP_STACK is set'''

        expected = True
        if not self._test_config('HAVE_ARCH_VMAP_STACK'):
            self._skipped('Arch does not support vmalloced stack')
            expected = False
        self.assertKernelConfig('VMAP_STACK', expected)

    def test_350_config_thread_info_in_stack(self):
        '''Ensure THREAD_INFO_IN_TASK is set'''

        expected = True
        archs = ['amd64', 'i386', 'arm64', 's390x']
        # THREAD_INFO_IN_TASK enabled for ppc64el in 5.1
        if self.kernel_at_least('5.1'):
            archs += ['ppc64el']
        if self.dpkg_arch not in archs:
            self._skipped("THREAD_INFO_IN_TASK is an x86, arm64, ppc64el (since 5.1), and s390x arch feature only")
            expected = False
        elif not self.kernel_at_least('4.9'):
            self._skipped('THREAD_INFO_IN_TASK added/enabled in 4.9 and newer')
            expected = False
        self.assertKernelConfig('THREAD_INFO_IN_TASK', expected)

    def test_360_config_security_yama(self):
        '''Ensure CONFIG_SECURITY_YAMA is set'''
        self.assertKernelConfigSet('SECURITY_YAMA')

    def test_370_config_acpi_custom_method(self):
        '''Ensure ACPI_CUSTOM_METHOD is NOT set'''
        self.assertKernelConfigUnset('ACPI_CUSTOM_METHOD')

    def test_380_config_sched_stack_end_check(self):
        '''Ensure SCHED_STACK_END_CHECK is set'''
        expected = True
        if not self.kernel_at_least('3.18'):
            self._skipped('SCHED_STACK_END_CHECK added/enabled in 3.18 and newer')
            expected = False
        self.assertKernelConfig('SCHED_STACK_END_CHECK', expected)

    def test_400_refcount_config(self):
        '''Ensure kernel refcount protections are enabled'''

        # In the 5.5 kernel series, the generic refcount_t
        # implementation was improved enough to be enabled everywhere,
        # and thus the ARCH_HAS_REFCOUNT and REFCOUNT_FULL config
        # options were removed in merge commit
        # 168829ad09ca9cdfdc664b2110d0e3569932c12d
        # This change has been backported to our Focal kernel since
        # 5.4.0-128.144, with commit 44120274bdc2
        # Thus we don't need to do anything for this test.
        if self.kernel_at_least('5.4.0'):
            self._skipped("5.4 kernels and newer use refcount_t everywhere")
            return

        # For x86, with refcount_t, we just need to check
        # ARCH_HAS_REFCOUNT config option (we could enable REFCOUNT_FULL
        # there, but the additional effort doesn't gain much
        # meaningfully. ARM64 and later ARM default to REFCOUNT_FULL on
        # For ppc64el and s390x, need to address LP: #1811162
        expected = True
        config_name = 'REFCOUNT_FULL'
        if self.dpkg_arch in ['amd64', 'i386']:
            config_name = 'ARCH_HAS_REFCOUNT'
            if not self.kernel_at_least('4.14'):
                self._skipped("ARCH_HAS_REFCOUNT is 4.14+ in amd64/i386 only")
                expected = False
        elif self.dpkg_arch in ['arm64']:
            if not self.kernel_at_least('4.15'):
                self._skipped("REFCOUNT_FULL is 4.15+ for arm64")
                expected = False
        elif self.dpkg_arch in ['armhf']:
            if not self.kernel_at_least('4.16'):
                self._skipped("REFCOUNT_FULL is 4.16+ for armhf")
                expected = False
        else:
            self._skipped("REFCOUNT_FULL not enabled for this arch, see LP: #1811162")
            expected = False

        self.assertKernelConfig(config_name, expected)

    def test_410_config_lock_down_kernel(self):
        '''Ensure kernel efi lockdown is enabled'''
        expected = True
        config_name = 'LOCK_DOWN_KERNEL'
        if self.kernel_at_least('5.4'):
            config_name = 'SECURITY_LOCKDOWN_LSM'
        elif not self.kernel_at_least('4.13'):
            self._skipped('CONFIG_LOCK_DOWN_KERNEL only included in 4.13 and newer')
            expected = False
        elif self.dpkg_arch in ['s390x'] and not self.kernel_at_least('5.2'):
            self._skipped('CONFIG_LOCK_DOWN_KERNEL not enabled for s390x before 5.2')
            expected = False
        elif self.dpkg_arch in ['ppc64el']:
            self._skipped('CONFIG_LOCK_DOWN_KERNEL not enabled for ppc64el')
            expected = False
        self.assertKernelConfig(config_name, expected)

    def test_420_config_page_poisoning(self):
        '''Ensure page poisoning is enabled (LP: #1783651)'''
        expected = True
        if not self.kernel_at_least('4.18'):
            self._skipped('CONFIG_PAGE_POISONING enabled in 4.18 and newer')
            expected = False
        self.assertKernelConfig('PAGE_POISONING', expected)

    def test_421_config_page_poisoning_zero(self):
        '''Ensure page poisoning to zero is enabled (LP: #1783651)'''
        # at some point in the future, we could disable this
        expected = True
        if not self.kernel_at_least('4.18'):
            self._skipped('CONFIG_PAGE_POISONING_ZERO enabled in 4.18 and newer')
            expected = False
        if self.kernel_at_least('5.11'):
            self._skipped('CONFIG_PAGE_POISONING_ZERO removed in 5.11 and newer')
            expected = False
        self.assertKernelConfig('PAGE_POISONING_ZERO', expected)

    def test_421_config_page_poisoning_no_sanity(self):
        '''Ensure page poisoning allocation sanity checking is disabled (LP: #1783651)'''
        # at some point in the future, we should enable sanity checking
        expected = True
        if not self.kernel_at_least('4.18'):
            self._skipped('CONFIG_PAGE_POISONING_NO_SANITY enabled in 4.18 and newer')
            expected = False
        if self.kernel_at_least('5.11'):
            self._skipped('CONFIG_PAGE_POISONING_NO_SANITY removed in 5.11 and newer')
            expected = False
        self.assertKernelConfig('PAGE_POISONING_NO_SANITY', expected)

    def test_430_config_module_sign(self):
        '''Ensure module signing is enabled'''
        expected = True
        if not self.kernel_at_least('3.13'):
            self._skipped('CONFIG_MODULE_SIG enabled in 3.13 and newer')
            expected = False
        self.assertKernelConfig('MODULE_SIG', expected)

    def test_440_config_module_sign_all(self):
        '''Ensure module signing automatically at build time is enabled'''
        expected = True
        if not self.kernel_at_least('3.13'):
            self._skipped('CONFIG_MODULE_SIG_ALL enabled in 3.13 and newer')
            expected = False
        self.assertKernelConfig('MODULE_SIG_ALL', expected)

    def test_450_config_disables_bpf_unpriv_default(self):
        '''unprivileged_bpf_disabled sysctl supported'''

        expected = True
        if not self.kernel_at_least('4.4'):
            self._skipped("unprivileged bpf disable sysctl did not exist before xenial")
            expected = False

        self.assertKernelConfig('BPF_UNPRIV_DEFAULT_OFF', expected)

    def test_500_config_pae(self):
        '''Ensure PAE/NX is enabled for i386'''

        expected = True
        if not self.dpkg_arch == 'i386':
            self._skipped('CONFIG_X86_PAE is i386 only')
            expected = False
        elif not self.kernel_at_least('3.13') and not self.kernel_version.endswith('-pae'):
            self._skipped('CONFIG_X86_PAE is generic-pae only')
            expected = False
        self.assertKernelConfig('X86_PAE', expected)

    def test_510_config_oabi_compat_disable(self):
        '''Ensure OABI_COMPAT is disabled for armhf'''

        expected = False
        if not self.dpkg_arch == 'armhf':
            self._skipped('CONFIG_OABI_COMPAT is armhf only')
        self.assertKernelConfig('OABI_COMPAT', expected)

    def test_520_config_random_trust_cpu(self):
        '''Ensure RANDOM_TRUST_CPU is enabled (LP: #1823754)'''

        expected = True
        # This config is now supported by all architectures
        # and is backported upstream up to v4.9 stable trees
        # See LP: #1990090
        # The only exception is ARM64, RANDOM_TRUST_CPU depends on
        # ARCH_RANDOM which is only available in v5.6 stable for ARM64
        if self.kernel_at_least('6.2'):
            self._skipped('RANDOM_TRUST_CPU has been dropped in v6.2')
            expected = False
        elif self.dpkg_arch == 'arm64' and not self._test_config('ARCH_RANDOM'):
            self._skipped('arm64 does not support ARCH_RANDOM before v5.6')
            expected = False
        elif not self.kernel_at_least('4.9'):
            expected = False

        self.assertKernelConfig('RANDOM_TRUST_CPU', expected)

    def test_530_config_binfmt_aout(self):
        '''Ensure BINFMT_AOUT is disabled (LP: #1818552)'''

        expected = False
        if self.dpkg_arch == 'i386' and not self.kernel_at_least('4.4'):
            expected = True
        self.assertKernelConfig('BINFMT_AOUT', expected)

    def test_550_config_random_kmalloc(self):
        '''Ensure CONFIG_RANDOM_KMALLOC_CACHES is enabled'''
        # Introduced in upstream commit 3c6152940584 "Randomized slab
        # caches for kmalloc()" (v6.8)
        expected = True
        if not self.kernel_at_least('6.8'):
            self._skipped('CONFIG_RANDOM_KMALLOC_CACHES introduced in v6.8')
            expected = False
        self.assertKernelConfig('RANDOM_KMALLOC_CACHES', expected)

    def test_600_config_net_cls_rsvp(self):
        '''Ensure NET_CLS_RSVP is disabled/removed (CVE-2023-42755)'''

        # 265b4da82dbf ("net/sched: Retire rsvp classifier") should have
        # been backported everywhere
        self.assertKernelConfigUnset('NET_CLS_RSVP')

    def test_601_config_net_cls_rsvp6(self):
        '''Ensure NET_CLS_RSVP6 is disabled/removed (CVE-2023-42755)'''

        # 265b4da82dbf ("net/sched: Retire rsvp classifier") should have
        # been backported everywhere
        self.assertKernelConfigUnset('NET_CLS_RSVP6')

class KernelNonSecurityTest(KernelSecurityBaseTest):
    '''Test kernel for non-security-feature regressions'''

    # Clean up all builds here, and make them on a per-test basis.
    def test_000_make(self):
        '''Prepare to build helper tools'''

        self.announce("%s" % (self.gcc_version))
        self.assertShellExitEquals(0, ["make", "clean"])

    def test_10_bad_syscall_returns_ENOSYS(self):
        '''syscall(666666) returns ENOSYS (LP: #339743)'''

        expected = 0
        if self.dpkg_arch not in ['i386', 'amd64']:
            return self._skipped("only x86")

        if self.dpkg_arch == "amd64":
            # If IA32 emulation is disabled on amd64, the `int $0x80` instruction
            # in the bad-syscall test causes a general protection fault since
            # it's an IA32-exclusive interrupt instruction.
            can_exec_ia32 = os.path.join(self.fs_dir, "can-exec-ia32")
            rc, _ = self.shell_cmd([can_exec_ia32, "cc"])
            if rc != 0:
                self._skipped("IA32 emulation disabled")
                return

        os.chdir('bad-syscall')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, self._unpriv_cmd(["./bad-syscall"]))

    def test_inotify_leak(self):
        '''inotify does not leak descriptors (LP: #485556)'''

        expected = 0
        if self.lsb_release['Release'] < 8.04:
            self._skipped("only Hardy and later")
            expected = 127

        os.chdir('inotify')
        self.assertShellExitEquals(0, ["make"])
        self.assertShellExitEquals(expected, self._unpriv_cmd(["./inotify-leak"]))

    def test_ulimit_stack_small(self):
        '''Ensure small stack limits are enforced'''

        '''Origin of test https://bugzilla.redhat.com/show_bug.cgi?id=1463241 '''

        page_size = resource.getpagesize()
        if page_size >= 65536:
            '''https://bugs.launchpad.net/bugs/1814295 (ppc64el, CONFIG_PPC_64K_PAGES=y)
               https://bugs.launchpad.net/bugs/1949645 (arm64, CONFIG_ARM64_64K_PAGES=y)'''
            return self._skipped('skipped on 64K page size envs (LP: #1814295, #1949645)')

        expected = [139]
        if not self.kernel_at_least('4.4'):
            expected += [137]
        self.assertShellExitIn(expected, self._unpriv_cmd(["sh", "-c", "ulimit -s 1 && /bin/true"]))

    def test_ulimit_stack_reasonable(self):
        '''Ensure reasonably small stack limits do not fail'''

        '''Origin of test https://bugzilla.redhat.com/show_bug.cgi?id=1463241 '''
        expected = 0
        self.assertShellExitEquals(expected, self._unpriv_cmd(["sh", "-c", "ulimit -s 512 && /bin/true"]))


if __name__ == '__main__':
    testlib.require_sudo()
    unittest.main()