File: 10-bash.jinja

package info (click to toggle)
scap-security-guide 0.1.76-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 110,644 kB
  • sloc: xml: 241,883; sh: 73,777; python: 32,527; makefile: 27
file content (2692 lines) | stat: -rw-r--r-- 106,332 bytes parent folder | download
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
{{#
Pass strings that correspond to XCCDF value names as arguments to this macro::

    bash_instantiate_variables("varname1", "varname2")

Then, assume that variables of that names are defined and contain the correct value, e.g.::

        echo "Setting=$varname1" >> config_file

#}}
{{%- macro bash_instantiate_variables() -%}}
{{%- for name in varargs -%}}
{{{ name }}}='(bash-populate {{{ name }}})'
{{% endfor -%}}
{{%- endmacro -%}}


{{#
    Make sure that we have a line like this in pamFile (additional options are left as-is):
    type control module option=valueRegexArg

:param pamFile:         PAM config file
:type pamFile: str
:param type:            PAM module interface
:type type: str
:param control:         PAM control flags
:type control: str
:param module:          PAM module name
:type module: str
:param option:          PAM module option
:type option: str
:param valueRegexArg:   PAM module option argument regex pattern
:type valueRegexArg: str
:param defaultValueArg: PAM module option argument default value
:type defaultValueArg: str

#}}
{{%- macro bash_ensure_pam_module_options(pamFile, type, control, module, option, valueRegexArg, defaultValueArg) -%}}
if [ -e "{{{ pamFile }}}" ] ; then
    valueRegex="{{{ valueRegexArg }}}" defaultValue="{{{ defaultValueArg }}}"
    # non-empty values need to be preceded by an equals sign
    [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
    # add an equals sign to non-empty values
    [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

    # fix 'type' if it's wrong
    if grep -q -P "^\\s*(?"'!'"{{{ type }}}\\s)[[:alnum:]]+\\s+[[:alnum:]]+\\s+{{{ module }}}" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*)[[:alnum:]]+(\\s+[[:alnum:]]+\\s+{{{ module }}})/\\1{{{ type }}}\\2/" "{{{ pamFile }}}"
    fi

    # fix 'control' if it's wrong
    if grep -q -P "^\\s*{{{ type }}}\\s+(?"'!'"{{{ control }}})[[:alnum:]]+\\s+{{{ module }}}" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+)[[:alnum:]]+(\\s+{{{ module }}})/\\1{{{ control }}}\\2/" "{{{ pamFile }}}"
    fi

    # fix the value for 'option' if one exists but does not match 'valueRegex'
    if grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}(?"'!'"${valueRegex}(\\s|\$))" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s){{{ option }}}=[^[:space:]]*/\\1{{{ option }}}${defaultValue}/" "{{{ pamFile }}}"

    # add 'option=default' if option is not set
    elif grep -q -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" &&
            grep    -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" | grep -q -E -v "\\s{{{ option }}}(=|\\s|\$)" ; then

        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}[^\\n]*)/\\1 {{{ option }}}${defaultValue}/" "{{{ pamFile }}}"
    # add a new entry if none exists
    elif ! grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}${valueRegex}(\\s|\$)" < "{{{ pamFile }}}" ; then
        echo "{{{ type }}} {{{ control }}} {{{ module }}} {{{ option }}}${defaultValue}" >> "{{{ pamFile }}}"
    fi
else
    echo "{{{ pamFile }}} doesn't exist" >&2
fi
{{%- endmacro -%}}


{{#
    Make sure that we have a line with given type, control and module has the given option in pamFile (additional options are left as-is):
    `type control module option=valueRegexArg`

:param pamFile: PAM config file
:type pamFile: str
:param type: PAM module interface
:type type: str
:param control: PAM control flags
:type control: str
:param module: PAM module name
:type module: str
:param option: PAM module option
:type option: str
:param valueRegexArg: PAM module option argument regex pattern
:type valueRegexArg: str
:param defaultValueArg: PAM module option argument default value
:type defaultValueArg: str

#}}
{{%- macro bash_provide_pam_module_options(pamFile, type, control, module, option, valueRegexArg, defaultValueArg) -%}}
if [ -e "{{{ pamFile }}}" ] ; then
    valueRegex="{{{ valueRegexArg }}}" defaultValue="{{{ defaultValueArg }}}"
    # non-empty values need to be preceded by an equals sign
    [ -n "${valueRegex}" ] && valueRegex="=${valueRegex}"
    # add an equals sign to non-empty values
    [ -n "${defaultValue}" ] && defaultValue="=${defaultValue}"

    # fix the value for 'option' if one exists but does not match 'valueRegex'
    if grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}(?"'!'"${valueRegex}(\\s|\$))" < "{{{ pamFile }}}" ; then
        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s){{{ option }}}=[^[:space:]]*/\\1{{{ option }}}${defaultValue}/" "{{{ pamFile }}}"

    # add 'option=default' if option is not set
    elif grep -q -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" &&
            grep    -E "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}" < "{{{ pamFile }}}" | grep -q -E -v "\\s{{{ option }}}(=|\\s|\$)" ; then

        sed --follow-symlinks -i -E -e "s/^(\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}[^\\n]*)/\\1 {{{ option }}}${defaultValue}/" "{{{ pamFile }}}"
    # add a new entry if none exists
    elif ! grep -q -P "^\\s*{{{ type }}}\\s+{{{ control }}}\\s+{{{ module }}}(\\s.+)?\\s+{{{ option }}}${valueRegex}(\\s|\$)" < "{{{ pamFile }}}" ; then
        echo "{{{ type }}} {{{ control }}} {{{ module }}} {{{ option }}}${defaultValue}" >> "{{{ pamFile }}}"
    fi
else
    echo "{{{ pamFile }}} doesn't exist" >&2
fi
{{%- endmacro -%}}


{{%- set in_chrooted_environment = 'test "$(stat -c %d:%i /)" != "$(stat -c %d:%i /proc/1/root/.)"' -%}}
{{#
    Set a parameter

:param path: Path to file
:type path: str
:param parameter: Parameter to set
:type parameter: str
:param value: Value to set
:type value: str
:param no_quotes: If true the value is not quoted. Default is false.
:type no_quotes: bool

#}}
{{%- macro bash_shell_file_set(path, parameter, value, no_quotes=false) -%}}
{{% if no_quotes -%}}
  {{% if "$" in value %}}
    {{% set value = '%s' % value.replace("$", "\\$") %}}
  {{% endif %}}
{{%- else -%}}
  {{% if "$" in value %}}
    {{% set value = '\\"%s\\"' % value.replace("$", "\\$") %}}
  {{% else %}}
    {{% set value = "'%s'" % value %}}
  {{% endif %}}
{{%- endif -%}}
{{{ set_config_file(
        path=path,
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="^#\s*" ~ parameter,
        insensitive=false,
        separator="=",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
    Set set a parameter in /etc/sshd_config

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_sshd_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/ssh/sshd_config",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="BOF",
        insensitive=true,
        separator=" ",
        separator_regex="\s\+",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
        Set set a parameter in /etc/sshd_config or /etc/ssh/sshd_config.d/

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str
:parameter config_is_distributed: If true, will ok look in /etc/ssh/sshd_config.d
:type config_is_distributed: str
:parameter config_basename: Filename of configuration file when using distributed configuration
:type config_basename: str

#}}
{{% macro bash_sshd_remediation(parameter, value, config_is_distributed="false", config_basename="00-complianceascode-hardening.conf") -%}}
{{%- set sshd_config_path = "/etc/ssh/sshd_config" %}}
{{%- set sshd_config_dir = "/etc/ssh/sshd_config.d" -%}}

{{%- if config_is_distributed == "true" %}}
{{%- set prefix_regex = "^\s*" -%}}
{{%- set separator_regex = "\s\+" -%}}
{{%- set hardening_config_basename = config_basename %}}
{{%- set line_regex = prefix_regex ~ parameter ~ separator_regex %}}
mkdir -p {{{ sshd_config_dir }}}
touch {{{ sshd_config_dir }}}/{{{ hardening_config_basename }}}
chmod 0600 {{{ sshd_config_dir }}}/{{{ hardening_config_basename }}}
{{{ lineinfile_absent(sshd_config_path, line_regex, insensitive=true) }}}
{{{ lineinfile_absent_in_directory(sshd_config_dir, line_regex, insensitive=true, filename_glob="*.conf") }}}
{{{ set_config_file(
        path=sshd_config_dir ~ "/" ~ hardening_config_basename,
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="BOF",
        insensitive=true,
        separator=" ",
        separator_regex=separator_regex,
        prefix_regex=prefix_regex)
    }}}
{{%- else %}}
{{% if product in ["ol8", "ol9"] %}}
# Find the include keyword, extract from the line the glob expression representing included files.
# And if it is a relative path prepend '/etc/ssh/'
included_files=$(grep -oP "^\s*(?i)include.*" /etc/ssh/sshd_config | sed -e 's/\s*include\s*//I' | sed -e 's|^[^/]|/etc/ssh/&|')
for included_file in ${included_files} ; do
    {{{ lineinfile_absent("$included_file", "^\s*" ~ parameter, insensitive=true) | indent(4) }}}
done
{{% endif %}}
{{{ bash_sshd_config_set(parameter=parameter, value=value) }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
    Macro that copies the audit rules into a file.
    The purpose is to create exactly the same content in the file specified by filename argument
    as in https://github.com/linux-audit/audit-userspace/blob/master/rules/30-ospp-v42.rules

:param filename:    Name of the file to print the information to; written do directory specified by the filename
:type filename: str

#}}
{{%- macro bash_create_audit_remediation_unsuccessful_file_modification_detailed(filename) -%}}
mkdir -p "$(dirname '{{{ filename }}}')"
cat <<EOF > "{{{ filename }}}"
{{{ audit_remediation_unsuccessful_file_modification_detailed_audit_file_content() }}}
EOF
{{%- endmacro -%}}


{{#
   Set parameter in /etc/audit/auditd.conf

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_auditd_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/audit/auditd.conf",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator=" = ",
        separator_regex="\s*=\s*",
        prefix_regex="^\s*")
    }}}
{{%- endmacro -%}}


{{#
   Set parameter in /etc/systemd/coredump.conf.
   For SLE platforms put remediation in drop-in configuration file /etc/systemd/coredump.conf.d/oscap-autoremedy.conf.

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_coredump_config_set(parameter, value) -%}}
{{% if 'sle' in product %}}
mkdir -p /etc/systemd/coredump.conf.d/
if [ ! -f "/etc/systemd/coredump.conf.d/oscap-autoremedy.conf" ]; then
   echo "[Coredump]" > "/etc/systemd/coredump.conf.d/oscap-autoremedy.conf"
fi
{{%- set target_path="/etc/systemd/coredump.conf.d/oscap-autoremedy.conf" -%}}
{{% else %}}
{{%- set target_path="/etc/systemd/coredump.conf" -%}}
{{% endif %}}
{{{ bash_ensure_ini_config(target_path, section="Coredump", key=parameter, value=value) }}}
{{%- endmacro -%}}


{{#
   Set parameter in /etc/selinux/config

:parameter parameter: Parameter to set
:type parameter: str
:parameter value: The value to set
:type value: str

#}}
{{%- macro bash_selinux_config_set(parameter, value) -%}}
{{{ set_config_file(
        path="/etc/selinux/config",
        parameter=parameter,
        value=value,
        create=true,
        insert_after="",
        insert_before="",
        insensitive=true,
        separator="=",
        separator_regex="=",
        prefix_regex="^")
    }}}
{{%- endmacro -%}}


{{#
    Macro to fix audit file system object watch rule for given path:

    * if rule exists, also verifies the -w bits match the requirements
    * if rule doesn't exist yet, appends expected rule form to $files_to_inspect
      audit rules file, depending on the tool which was used to load audit rules

    Example macro invocation::

          {{{ bash_fix_audit_watch_rule("auditctl", "/etc/localtime", "wa", "audit_time_rules") }}}

:param tool:                 tool used to load audit rules, either 'auditctl', or 'augenrules'
:type tool: str
:param path:                 value of -w audit rule's argument
:type path: str
:param required_access_bits: value of -p audit rule's argument
:type required_access_bits: str
:param key:                  value of -k audit rule's argument
:type key: str

#}}
{{%- macro bash_fix_audit_watch_rule(tool, path, required_access_bits, key) -%}}
# Create a list of audit *.rules files that should be inspected for presence and correctness
# of a particular audit rule. The scheme is as follows:
#
# -----------------------------------------------------------------------------------------
# Tool used to load audit rules	| Rule already defined	|  Audit rules file to inspect	  |
# -----------------------------------------------------------------------------------------
#	auditctl		|     Doesn't matter	|  /etc/audit/audit.rules	  |
# -----------------------------------------------------------------------------------------
# 	augenrules		|          Yes		|  /etc/audit/rules.d/*.rules	  |
# 	augenrules		|          No		|  /etc/audit/rules.d/$key.rules  |
# -----------------------------------------------------------------------------------------
files_to_inspect=()

{{% if tool == "auditctl" %}}
# If the audit tool is 'auditctl', then add '/etc/audit/audit.rules'
# into the list of files to be inspected
files_to_inspect+=('/etc/audit/audit.rules')
{{%- elif tool == "augenrules" -%}}
# If the audit is 'augenrules', then check if rule is already defined
# If rule is defined, add '/etc/audit/rules.d/*.rules' to list of files for inspection.
# If rule isn't defined, add '/etc/audit/rules.d/{{{ key }}}.rules' to list of files for inspection.
readarray -t matches < <(grep -HP "[\s]*-w[\s]+{{{ path }}}" /etc/audit/rules.d/*.rules)

# For each of the matched entries
for match in "${matches[@]}"
do
    # Extract filepath from the match
    rulesd_audit_file=$(echo $match | cut -f1 -d ':')
    # Append that path into list of files for inspection
    files_to_inspect+=("$rulesd_audit_file")
done
# Case when particular audit rule isn't defined yet
if [ "${#files_to_inspect[@]}" -eq "0" ]
then
    # Append '/etc/audit/rules.d/{{{ key }}}.rules' into list of files for inspection
    key_rule_file="/etc/audit/rules.d/{{{ key }}}.rules"
    # If the {{{ key }}}.rules file doesn't exist yet, create it with correct permissions
    if [ ! -e "$key_rule_file" ]
    then
        touch "$key_rule_file"
        chmod 0600 "$key_rule_file"
    fi
    files_to_inspect+=("$key_rule_file")
fi
{{%- else -%}}
{{{ raise("Unknown tool used: " + tool) }}}
{{%- endif %}}

# Finally perform the inspection and possible subsequent audit rule
# correction for each of the files previously identified for inspection
for audit_rules_file in "${files_to_inspect[@]}"
do
    # Check if audit watch file system object rule for given path already present
    if grep -q -P -- "^[\s]*-w[\s]+{{{ path }}}" "$audit_rules_file"
    then
        # Rule is found => verify yet if existing rule definition contains
        # all of the required access type bits

        # Define BRE whitespace class shortcut
        sp="[[:space:]]"
        # Extract current permission access types (e.g. -p [r|w|x|a] values) from audit rule
        current_access_bits=$(sed -ne "s#$sp*-w$sp\+{{{ path }}} $sp\+-p$sp\+\([rxwa]\{1,4\}\).*#\1#p" "$audit_rules_file")
        # Split required access bits string into characters array
        # (to check bit's presence for one bit at a time)
        for access_bit in $(echo "{{{ required_access_bits }}}" | grep -o .)
        do
            # For each from the required access bits (e.g. 'w', 'a') check
            # if they are already present in current access bits for rule.
            # If not, append that bit at the end
            if ! grep -q "$access_bit" <<< "$current_access_bits"
            then
                # Concatenate the existing mask with the missing bit
                current_access_bits="$current_access_bits$access_bit"
            fi
        done
        # Propagate the updated rule's access bits (original + the required
        # ones) back into the /etc/audit/audit.rules file for that rule
        sed -i "s#\($sp*-w$sp\+{{{ path }}}$sp\+-p$sp\+\)\([rxwa]\{1,4\}\)\(.*\)#\1$current_access_bits\3#" "$audit_rules_file"
    else
        # Rule isn't present yet. Append it at the end of $audit_rules_file file
        # with proper key

        echo "-w {{{ path }}} -p {{{ required_access_bits }}} -k {{{ key }}}" >> "$audit_rules_file"
    fi
done
{{%- endmacro -%}}


{{#
    Install a package

    Uses the right command based on pkg_manager property defined in product.yml.

:param package: name of the package
:type package: str

#}}
{{%- macro bash_package_install(package) -%}}
{{%- if pkg_manager is defined -%}}
{{%- if pkg_manager == "yum" or pkg_manager == "dnf" -%}}
if ! rpm -q --quiet "{{{ package }}}" ; then
    {{{ pkg_manager }}} install -y "{{{ package }}}"
fi
{{%- elif pkg_manager == "apt_get" -%}}
DEBIAN_FRONTEND=noninteractive apt-get install -y "{{{ package }}}"
{{%- elif pkg_manager == "zypper" -%}}
zypper install -y "{{{ package }}}"
{{%- else -%}}
{{{ die("Can't generate a remediation for " + pkg_manager) }}}
{{%- endif -%}}
{{%- else -%}}
{{{ die("Can't generate a remediation for product " + product + ", because there is no pkg_manager set in product.yml") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Remove a package

    Uses the right command based on pkg_manager property defined in product.yml.
    When used in a test scenario, the macro will remove even protected packages.

:param package: name of the package
:type package: str

#}}
{{%- macro bash_package_remove(package) -%}}
{{%- if pkg_manager is defined -%}}
{{%- if pkg_manager == "yum" or pkg_manager == "dnf" -%}}
if rpm -q --quiet "{{{ package }}}" ; then
{{% if SSG_TEST_SUITE_ENV %}}
    rpm -e --nodeps "{{{ package }}}"
{{% else %}}
    {{%- if pkg_manager == "dnf" -%}}
        dnf remove -y --noautoremove "{{{ package }}}"
    {{%- else -%}}
        {{{ pkg_manager }}} remove -y "{{{ package }}}"
    {{%- endif -%}}

{{% endif %}}
fi
{{%- elif pkg_manager == "apt_get" -%}}
DEBIAN_FRONTEND=noninteractive apt-get remove -y "{{{ package }}}"
{{%- elif pkg_manager == "zypper" -%}}
zypper remove -y "{{{ package }}}"
{{%- else -%}}
{{{ die("Can't generate a remediation for " + pkg_manager) }}}
{{%- endif -%}}
{{%- else -%}}
{{{ die("Can't generate a remediation for product " + product + ", because there is no pkg_manager set in product.yml") }}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Macro to perform remediation for the 'adjtimex', 'settimeofday', and 'stime' audit
    system calls on RHEL, Fedora or OL systems.
    Remediation performed for both possible tools: 'auditctl' and 'augenrules'.

     Note: 'stime' system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
     therefore excluded from the list of time group system calls to be audited on this arch

    Example macro invocation::

      {{{ bash_perform_audit_adjtimex_settimeofday_stime_remediation() }}}

#}}
{{%- macro bash_perform_audit_adjtimex_settimeofday_stime_remediation() -%}}
# Retrieve hardware architecture of the underlying system
[ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

for ARCH in "${RULE_ARCHS[@]}"
do
    # Create expected audit group and audit rule form for particular system call & architecture
    if [ ${ARCH} = "b32" ]
    then
        ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
        # stime system call is known at 32-bit arch (see e.g "$ ausyscall i386 stime" 's output)
        # so append it to the list of time group system calls to be audited
        SYSCALL="adjtimex settimeofday stime"
        SYSCALL_GROUPING="adjtimex settimeofday stime"
    elif [ ${ARCH} = "b64" ]
    then
        ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
        # stime system call isn't known at 64-bit arch (see "$ ausyscall x86_64 stime" 's output)
        # therefore don't add it to the list of time group system calls to be audited
        SYSCALL="adjtimex settimeofday"
        SYSCALL_GROUPING="adjtimex settimeofday"
    fi
    OTHER_FILTERS=""
    AUID_FILTERS=""
    KEY="audit_time_rules"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    {{{ bash_fix_audit_syscall_rule("augenrules", "$ACTION_ARCH_FILTERS", "$OTHER_FILTERS", "$AUID_FILTERS", "$SYSCALL", "$SYSCALL_GROUPING", "$KEY") | indent(4) }}}
    {{{ bash_fix_audit_syscall_rule("auditctl", "$ACTION_ARCH_FILTERS", "$OTHER_FILTERS", "$AUID_FILTERS", "$SYSCALL", "$SYSCALL_GROUPING", "$KEY") | indent(4) }}}
done
{{%- endmacro -%}}


{{#
    Disable prelinking in sysconfig

#}}
{{%- macro bash_disable_prelink() -%}}
# prelink not installed
if test -e /etc/sysconfig/prelink -o -e /usr/sbin/prelink; then
    if grep -q ^PRELINKING /etc/sysconfig/prelink
    then
        sed -i 's/^PRELINKING[:blank:]*=[:blank:]*[:alpha:]*/PRELINKING=no/' /etc/sysconfig/prelink
    else
        printf '\n' >> /etc/sysconfig/prelink
        printf '%s\n' '# Set PRELINKING=no per security requirements' 'PRELINKING=no' >> /etc/sysconfig/prelink
    fi

    # Undo previous prelink changes to binaries if prelink is available.
    if test -x /usr/sbin/prelink; then
        /usr/sbin/prelink -ua
    fi
fi
{{%- endmacro -%}}


{{#
    Macro to configure DConf settings for RHEL and Fedora systems.

    If files contain ibus or distro, ignore them.

#}}
{{%- macro bash_dconf_settings(path, key, value, db, setting_file) -%}}
# Check for setting in any of the DConf db directories
# If files contain ibus or distro, ignore them.
# The assignment assumes that individual filenames don't contain :
readarray -t SETTINGSFILES < <(grep -r "\\[{{{ path }}}\\]" "/etc/dconf/db/" \
                                | grep -v 'distro\|ibus\|{{{ db }}}' | cut -d":" -f1)
DCONFFILE="/etc/dconf/db/{{{ db }}}/{{{ setting_file }}}"
DBDIR="/etc/dconf/db/{{{ db }}}"

mkdir -p "${DBDIR}"

# Comment out the configurations in databases different from the target one
if [ "${#SETTINGSFILES[@]}" -ne 0 ]
then
    if grep -q "^\\s*{{{ key }}}\\s*=" "${SETTINGSFILES[@]}"
    then
        {{% if '/' in key %}}
        {{{ raise("Key (" + key + ") uses sed path separator (/) in " + rule_id) }}}
        {{% endif %}}
        sed -Ei "s/(^\s*){{{ key }}}(\s*=)/#\1{{{ key }}}\2/g" "${SETTINGSFILES[@]}"
    fi
fi

[ ! -z "${DCONFFILE}" ] && echo "" >> "${DCONFFILE}"
if ! grep -q "\\[{{{ path }}}\\]" "${DCONFFILE}"
then
    printf '%s\n' "[{{{ path }}}]" >> ${DCONFFILE}
fi

escaped_value="$(sed -e 's/\\/\\\\/g' <<< "{{{ value }}}")"
if grep -q "^\\s*{{{ key }}}\\s*=" "${DCONFFILE}"
then
        sed -i "s/\\s*{{{ key }}}\\s*=\\s*.*/{{{ key }}}=${escaped_value}/g" "${DCONFFILE}"
    else
        sed -i "\\|\\[{{{ path }}}\\]|a\\{{{ key }}}=${escaped_value}" "${DCONFFILE}"
fi

{{%- if 'ubuntu' in product %}}
# Make sure permissions allow regular users to read dconf settings.
# Also define the umask to avoid `dconf update` changing permissions.
chmod -R u=rwX,go=rX /etc/dconf/db
(umask 0022 && dconf update)
{{%- else %}}
dconf update
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Macro to configure DConf locks for RHEL and Fedora systems.

#}}
{{%- macro bash_dconf_lock(key, setting, db, lock_file) -%}}
# Check for setting in any of the DConf db directories
LOCKFILES=$(grep -r "^/{{{ key }}}/{{{ setting }}}$" "/etc/dconf/db/" \
            | grep -v 'distro\|ibus\|{{{ db }}}' | grep ":" | cut -d":" -f1)
LOCKSFOLDER="/etc/dconf/db/{{{ db }}}/locks"

mkdir -p "${LOCKSFOLDER}"

# Comment out the configurations in databases different from the target one
if [[ ! -z "${LOCKFILES}" ]]
then
    sed -i -E "s|^/{{{ key }}}/{{{ setting }}}$|#&|" "${LOCKFILES[@]}"
fi

if ! grep -qr "^/{{{ key }}}/{{{ setting }}}$" /etc/dconf/db/{{{ db }}}/
then
    echo "/{{{ key }}}/{{{ setting }}}" >> "/etc/dconf/db/{{{ db }}}/locks/{{{ lock_file }}}"
fi

{{%- if 'ubuntu' in product %}}
# Make sure permissions allow regular users to read dconf settings.
# Also define the umask to avoid `dconf update` changing permissions.
chmod -R u=rwX,go=rX /etc/dconf/db
(umask 0022 && dconf update)
{{%- else %}}
dconf update
{{%- endif %}}
{{%- endmacro -%}}


{{#
Macro to enable or disable a particular service.

    Examples::

        bash_service_command("enable", "bluetooth")
        bash_service_command("disable", "bluetooth.service")
        bash_service_command("disable", "rsh.socket", xinetd="rsh")

:param service_state: Desired state of the service
:type service_state: str
:param service: The service to change
:type service: str
:param xinetd: Set the xinetd for the service. Defaults to empty string.
:type xinetd: str

#}}
{{%- macro bash_service_command(service_state, service, xinetd="") -%}}
{{#
# If systemctl is installed, use systemctl command; otherwise, use the
# service/chkconfig commands
#}}
{{%- if init_system == "systemd" -%}}
  {{%- if service_state == "disable" -%}}
if [[ $(/usr/bin/systemctl is-system-running) != "offline" ]]; then
/usr/bin/systemctl stop "{{{ service }}}"
fi
/usr/bin/systemctl disable "{{{ service }}}"
  {{%- else -%}}
/usr/bin/systemctl enable "{{{ service }}}"
if [[ $(/usr/bin/systemctl is-system-running) != "offline" ]]; then
/usr/bin/systemctl start "{{{ service }}}"
fi
  {{%- endif %}}
# The service may not be running because it has been started and failed,
# so let's reset the state so OVAL checks pass.
# Service should be 'inactive', not 'failed' after reboot though.
if /usr/bin/systemctl --failed | grep -q "{{{ service }}}"; then
    /usr/bin/systemctl reset-failed "{{{ service }}}"
fi
{{%- endif -%}}

{{%- if xinetd != "" -%}}
grep -qi disable "/etc/xinetd.d/$xinetd" && \
    {{%- if service_state == "disable" -%}}
sed -i "s/disable.*/disable         = no/gI" "/etc/xinetd.d/$xinetd"
    {{%- else -%}}
sed -i "s/disable.*/disable         = yes/gI" "/etc/xinetd.d/$xinetd"
    {{%- endif -%}}
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Macro to ensure that the ntp/chrony config file contains valid server entries.

:param config_file: Path to the ntp/chrony config file
:type config_file: str
:param servers_list: Comma-separated list of servers
:type servers_list: str

#}}
{{%- macro bash_ensure_there_are_servers_in_ntp_compatible_config_file(config_file, servers_list) -%}}
if ! grep -q '#[[:space:]]*server' "{{{ config_file }}}" ; then
  for server in $(echo "{{{ servers_list }}}" | tr ',' '\n') ; do
    printf '\nserver %s' "$server" >> "{{{ config_file }}}"
  done
else
  sed -i 's/#[ \t]*server/server/g' "{{{ config_file }}}"
fi
{{%- endmacro -%}}


{{#
    Macro used to apply changes on authselect profiles. The command automatically creates a backup
    of the current settings before applying the changes. It is possible to inform a custom backup
    name through the "backup_name" parameter. If the "backup_name" parameter is not defined, the
    authselect default name is used. The default name is formed by the current date and time
    suffixed by 6 random alphanumeric characters. The authselect backups are stored in sub-folders
    inside the "/var/lib/authselect/backups" folder, identified by their respective backup names.
    Note: An existing backup can be overwritten if the same backup name is informed. If this is
    not desired, avoid defining a backup name.

:param backup_name:        Changes the default backup name used by authselect.
:type backup_name: str

#}}
{{% macro bash_apply_authselect_changes(backup_name='') -%}}
{{%- if backup_name == '' %}}
authselect apply-changes -b
{{%- else %}}
authselect apply-changes -b --backup={{{ backup_name }}}
{{%- endif %}}
{{%- endmacro %}}


{{#
    Disable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.
#}}
{{%- macro bash_disable_authselect_feature(feature) -%}}
{{{ bash_check_authselect_integrity() }}}
authselect disable-feature {{{ feature }}}
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Enable authselect feature if the authselect current profile is intact or inform that its
    integrity check failed.
#}}
{{%- macro bash_enable_authselect_feature(feature) -%}}
{{{ bash_check_authselect_integrity() }}}
authselect enable-feature {{{ feature }}}
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Enable pam_faillock.so PAM module using authselect.
    If an authselect profile is not selected or the selected profile is not intact, the operation is aborted.
    If the operation is aborted, an informative message is shown in the remediation report.

#}}
{{%- macro bash_enable_pam_faillock_with_authselect() -%}}
{{{ bash_enable_authselect_feature('with-faillock') }}}
{{%- endmacro -%}}


{{#
    Enable pam_faillock.so PAM module by directly editing PAM files.
    This option is only recommended when authselect tool is not available for the system.

#}}
{{%- macro bash_enable_pam_faillock_directly_in_pam_files() -%}}
{{% if 'debian' in product %}}
pam_file="/etc/pam.d/common-auth"
if ! grep -qE '^\s*auth\s+required\s+pam_faillock\.so\s+preauth.*$' "$pam_file" ; then
    # insert at the top
    sed -i --follow-symlinks '/^# here are the per-package modules/i auth        required      pam_faillock.so preauth' "$pam_file"
fi
if ! grep -qE '^\s*auth\s+\[default=die\]\s+pam_faillock\.so\s+authfail.*$' "$pam_file" ; then

    num_lines=$(sed -n 's/^\s*auth.*success=\([1-9]\).*pam_unix\.so.*/\1/p' "$pam_file")
    if [ ! -z "$num_lines" ]; then

        # Add pam_faillock (authfail) module below pam_unix, skipping N-1 lines, where N is
        # the number of jumps in the pam_unix success=N statement. Ignore commented and empty lines.

        append_position=$(cat -n "${pam_file}" \
                          | grep -P "^\s+\d+\s+auth\s+.*$" \
                          | grep -w "pam_unix.so" -A $(( num_lines - 1 )) \
                          | tail -n 1 | cut -f 1 | tr -d ' '
                         )
        sed -i --follow-symlinks ''${append_position}'a auth        [default=die]      pam_faillock.so authfail' "$pam_file"
    else
        sed -i --follow-symlinks '/^auth.*pam_unix\.so.*/a auth        [default=die]      pam_faillock.so authfail' "$pam_file"
    fi
fi
if ! grep -qE '^\s*auth\s+sufficient\s+pam_faillock\.so\s+authsucc.*$' "$pam_file" ; then
    sed -i --follow-symlinks '/^auth.*pam_faillock\.so.*authfail.*/a auth        sufficient      pam_faillock.so authsucc' "$pam_file"
fi

pam_file="/etc/pam.d/common-account"
if ! grep -qE '^\s*account\s+required\s+pam_faillock\.so.*$' "$pam_file" ; then
    echo 'account   required     pam_faillock.so' >> "$pam_file"
fi
{{% elif 'ubuntu' in product %}}
conf_name=cac_faillock

if [ ! -f /usr/share/pam-configs/"$conf_name" ]; then
    cat << EOF > /usr/share/pam-configs/"$conf_name"
Name: Enable pam_faillock to deny access
Default: yes
Conflicts: faillock
Priority: 0
Auth-Type: Primary
Auth:
    [default=die]                   pam_faillock.so authfail
EOF
fi

if [ ! -f /usr/share/pam-configs/"$conf_name"_notify ]; then
    cat << EOF > /usr/share/pam-configs/"$conf_name"_notify
Name: Notify of failed login attempts and reset count upon success
Default: yes
Conflicts: faillock_notify
Priority: 1025
Auth-Type: Primary
Auth:
    requisite                       pam_faillock.so preauth
Account-Type: Primary
Account:
    required                        pam_faillock.so
EOF
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update

{{% else %}}
AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
for pam_file in "${AUTH_FILES[@]}"
do
    if ! grep -qE '^\s*auth\s+required\s+pam_faillock\.so\s+(preauth silent|authfail).*$' "$pam_file" ; then
        sed -i --follow-symlinks '/^auth.*sufficient.*pam_unix\.so.*/i auth        required      pam_faillock.so preauth silent' "$pam_file"
        sed -i --follow-symlinks '/^auth.*required.*pam_deny\.so.*/i auth        required      pam_faillock.so authfail' "$pam_file"
        sed -i --follow-symlinks '/^account.*required.*pam_unix\.so.*/i account     required      pam_faillock.so' "$pam_file"
    fi
    sed -Ei 's/(auth.*)(\[default=die\])(.*pam_faillock\.so)/\1required     \3/g' "$pam_file"
done
{{% endif %}}
{{%- endmacro -%}}


{{%- macro bash_pam_faillock_enable() -%}}
if [ -f /usr/bin/authselect ]; then
    {{{ bash_enable_pam_faillock_with_authselect() }}}
else
    {{{ bash_enable_pam_faillock_directly_in_pam_files() }}}
fi
{{%- endmacro -%}}


{{#
    Enable pam_pwquality.so PAM module by using pam-auth-update.
    This option is only recommended when pam-auth-update tool is available for the system.
#}}
{{%- macro bash_pam_pwquality_enable() -%}}
conf_name=cac_pwquality
if [ ! -f /usr/share/pam-configs/"$conf_name" ]; then
    cat << EOF > /usr/share/pam-configs/"$conf_name"
Name: Pwquality password strength checking
Default: yes
Priority: 1025
Conflicts: cracklib, pwquality
Password-Type: Primary
Password:
    requisite                   pam_pwquality.so
EOF
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update
{{%- endmacro -%}}


{{#
    Enable pam_unix.so PAM module by using pam-auth-update.
    This option is only recommended when pam-auth-update tool is available for the system.
#}}
{{%- macro bash_pam_unix_enable() -%}}
conf_name=cac_unix
conf_path="/usr/share/pam-configs"

if [ ! -f "$conf_path"/"$conf_name" ]; then
    if [ -f "$conf_path"/unix ]; then
        if grep -q "$(md5sum "$conf_path"/unix | cut -d ' ' -f 1)" /var/lib/dpkg/info/libpam-runtime.md5sums;then
            cp "$conf_path"/unix "$conf_path"/"$conf_name"
            sed -i 's/Priority: [0-9]\+/Priority: 257\
Conflicts: unix/' "$conf_path"/"$conf_name"
            DEBIAN_FRONTEND=noninteractive pam-auth-update
        else
            echo "Not applicable - checksum of $conf_path/unix does not match the original." >&2
        fi
    else
        echo "Not applicable - $conf_path/unix does not exist" >&2
    fi
fi

{{%- endmacro -%}}


{{#
    Validate an authselect custom profile integrity and ensures the correct file path is defined
    in the "PAM_FILE_PATH" variable. The macros which change PAM files are the same regardless of
    using authselect or not. The only change is the file path. However, this file path can change
    depending on the custom profile name used in the system. So, based on the informed PAM file,
    the macro will properly locate the correct profile and file to be edited in the authselect
    context. This sequence of commands is used in multiple PAM related macros.

:param pam_file:    PAM config file.
:type pam_file: str

#}}
{{%- macro bash_ensure_pam_variables_and_authselect_profile(pam_file) -%}}
{{{ bash_check_authselect_integrity() }}}
{{# the following macro ensures the CURRENT_PROFILE variable is properly set #}}
{{{ bash_ensure_authselect_custom_profile() }}}
PAM_FILE_NAME=$(basename "{{{ pam_file }}}")
PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"
{{{ bash_apply_authselect_changes() }}}
{{%- endmacro -%}}


{{#
    Ensure pam_lastlog.so PAM module shows the failed logins according to the system capabilities.
    If authselect is present and the "with-silent-lastlog" feature is available, the feature will be disabled.
    If authselect is present but the "with-silent-lastlog" feature is not yet available, a custom profile will be used.
    If authselect is not present, PAM files will be directly edited.

:param pam_file:    PAM config file.
:type pam_file: str
:param control:     PAM control flags.
:type control: str
:param after_match: Regex used as reference to append a line, if necessary. Optional parameter.
                    Note: For this macro, there is a special value used to include a line at
                    the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_pam_lastlog_enable_showfailed(pam_file, control, after_match='') -%}}
if [ -f /usr/bin/authselect ]; then
    if authselect list-features sssd | grep -q with-silent-lastlog; then
        {{{ bash_disable_authselect_feature('with-silent-lastlog') | indent(8) }}}
    else
        {{# the following macro ensures the PAM_FILE_PATH variable is properly set #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
        {{{ bash_ensure_pam_module_configuration("$PAM_FILE_PATH", 'session', control, 'pam_lastlog.so', 'showfailed', '', after_match) | indent(8) }}}
        {{{ bash_remove_pam_module_option_configuration("$PAM_FILE_PATH", 'session', control, 'pam_lastlog.so', 'silent') | indent(8) }}}
    fi
else
    {{{ bash_ensure_pam_module_configuration(pam_file, 'session', control, 'pam_lastlog.so', 'showfailed', '', after_match) | indent(8) }}}
    {{{ bash_remove_pam_module_option_configuration(pam_file, 'session', control, 'pam_lastlog.so', 'silent') | indent(8) }}}
fi
{{%- endmacro -%}}


{{#
    Enable pam_pwhistory.so PAM module according to the system capabilities.
    If authselect is present and the "with-pwhistory" feature is available, the feature will be enabled.
    If authselect is present but the "with-pwhistory" feature is not yet available, a custom profile will be used.
    If authselect is not present, PAM files will be directly edited.

:param pam_file:    PAM config file.
:type pam_file: str
:param control:     PAM control flags.
:type control: str
:param after_match: Regex used as reference to append a line, if necessary. Optional parameter.
                    Note: For this macro, there is a special value used to include a line at
                    the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_pam_pwhistory_enable(pam_file, control, after_match='') -%}}
if [ -f /usr/bin/authselect ]; then
    if authselect list-features sssd | grep -q with-pwhistory; then
        {{{ bash_enable_authselect_feature('with-pwhistory') | indent(8) }}}
    else
        {{# the following macro ensures the PAM_FILE_PATH variable is properly set #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
        {{{ bash_ensure_pam_module_line("$PAM_FILE_PATH", 'password', control, 'pam_pwhistory.so', after_match) | indent(8) }}}
    fi
else
{{% if 'ubuntu' in product %}}
conf_name={{{ pam_file }}}
conf_path="/usr/share/pam-configs"

if [ ! -f "$conf_path"/"$conf_name" ]; then
    cat << EOF > "$conf_path"/"$conf_name"
Name: pwhistory password history checking
Default: yes
Priority: 1024
Password-Type: Primary
Password: {{{ control }}} pam_pwhistory.so remember=24 enforce_for_root try_first_pass use_authtok
Password-Initial: {{{ control }}} pam_pwhistory.so remember=24 enforce_for_root try_first_pass
EOF
fi

DEBIAN_FRONTEND=noninteractive pam-auth-update
{{% else %}}
    {{{ bash_ensure_pam_module_line(pam_file, 'password', control, 'pam_pwhistory.so', after_match) | indent(4) }}}
{{% endif %}}
fi
{{%- endmacro -%}}


{{#
    Set pam_pwhistory.so PAM module options and values. In case the file
    /etc/security/pwhistory.conf is present in the system, the option is ensured there and removed
    from pam files to avoid conflicts or confusion.

:param pam_file:    PAM config file.
:type pam_file: str
:param option:      pwhistory option e.g.: remember, retry, debug
:type option: str
:param value:       value of option
:type value: str

#}}
{{%- macro bash_pam_pwhistory_parameter_value(pam_file, option, value='') -%}}
PWHISTORY_CONF="/etc/security/pwhistory.conf"
if [ -f $PWHISTORY_CONF ]; then
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $PWHISTORY_CONF; then
        echo $line >> $PWHISTORY_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $PWHISTORY_CONF
    fi
    {{%- endif %}}
    {{{ bash_remove_pam_module_option_configuration(pam_file, 'password', '', 'pam_pwhistory.so', option ) | indent(4) }}}
else
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{{ bash_ensure_pam_module_option("$PAM_FILE_PATH", 'password', 'requisite', 'pam_pwhistory.so', option, value, '') | indent(4) }}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
fi
{{%- endmacro -%}}


{{#
    Sets PAM faillock module options and values. In case the file
    /etc/security/faillock.conf is present in the system, the option is removed from pam files
    since it is not needed there in that case.
    It also adds pam_faillock.so as required module for account.

:param option: faillock option eg. deny, unlock_time, fail_interval
:type option: str
:param value: value of option
:type value: str
:param authfail: check the pam_faillock.so conf line with authfail
:type authfail: bool

#}}
{{%- macro bash_pam_faillock_parameter_value(option, value='', authfail=True) -%}}
{{% if 'ubuntu' in product %}}
AUTH_FILES=("/etc/pam.d/common-auth")
SKIP_FAILLOCK_CHECK=true
{{% else %}}
AUTH_FILES=("/etc/pam.d/system-auth" "/etc/pam.d/password-auth")
SKIP_FAILLOCK_CHECK=false
{{% endif %}}
FAILLOCK_CONF="/etc/security/faillock.conf"
if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $FAILLOCK_CONF; then
        echo $line >> $FAILLOCK_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $FAILLOCK_CONF
    fi
    {{%- endif %}}
    {{% if 'ubuntu' not in product %}}
    for pam_file in "${AUTH_FILES[@]}"
    do
        {{{ bash_remove_pam_module_option_configuration("$pam_file",'auth','','pam_faillock.so', option ) | indent(8) }}}
    done
    {{% endif %}}
else
    for pam_file in "${AUTH_FILES[@]}"
    do
        if ! grep -qE '^\s*auth.*pam_faillock\.so (preauth|authfail).*{{{ option }}}' "$pam_file"; then
            {{%- if value == '' %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*silent.*/ s/$/ {{{ option }}}/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ {{{ option }}}/' "$pam_file"
            {{%- endif %}}
            {{%- else %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*silent.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ {{{ option }}}='"{{{ value }}}"'/' "$pam_file"
            {{%- endif %}}
            {{%- endif %}}
        {{%- if value == '' %}}
        fi
        {{%- else %}}
        else
            sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*silent.*\)\('"{{{ option }}}"'=\)[0-9]\+\(.*\)/\1\2'"{{{ value }}}"'\3/' "$pam_file"
            {{%- if authfail %}}
            sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"{{{ option }}}"'=\)[0-9]\+\(.*\)/\1\2'"{{{ value }}}"'\3/' "$pam_file"
            {{%- endif %}}
        fi
        {{%- endif %}}
    done
fi
{{%- endmacro -%}}


{{#
    Sets PAM pwquality module options and values. The module argument is not removed from pam files
    since it is not inserted there in Ubuntu case.
    It also assume pam_pwquality.so is added as required module for account.

:param option: pwquality option eg. retry, minlen, dcredit
:type option: str
:param value: value of option
:type value: str

#}}
{{%- macro bash_pam_pwquality_parameter_value(option, value='') -%}}
PWQUALITY_CONF="/etc/security/pwquality.conf"
    {{%- if value == '' %}}
    regex="^\s*{{{ option }}}"
    line="{{{ option }}}"
    {{%- else %}}
    regex="^\s*{{{ option }}}\s*="
    line="{{{ option }}} = {{{ value }}}"
    {{%- endif %}}
    if ! grep -q $regex $PWQUALITY_CONF; then
        echo $line >> $PWQUALITY_CONF
    {{%- if value == '' %}}
    fi
    {{%- else %}}
    else
        sed -i --follow-symlinks 's|^\s*\({{{ option }}}\s*=\s*\)\(\S\+\)|\1'"{{{ value }}}"'|g' $PWQUALITY_CONF
    fi
    {{%- endif %}}
{{%- endmacro -%}}


{{#
    Print a message to stderr and exit the shell

:param message: The message to print.
:type message: str
:param rc: The error code (optional, default is 1)
:type rc: int
:param action: What to do (optional, default is 'exit', can be also 'return' or anything else)
:type action: str

#}}
{{% macro die(message, rc=1, action="exit") -%}}
printf '%s\n' "{{{ message | replace('"', '\\"') }}}" >&2
{{{ action }}} {{{ rc }}}
{{%- endmacro %}}


{{#
    Add an entry to a text configuration file

:param path: path of the configuration file
:type path: str
:param parameter: the parameter to be set in the configuration file
:type parameter: str
:param value: the value of the parameter to be set in the configuration file
:type value: str
:param create: whether create the file specified by path if the file does not exits
:type create: bool
:param insert_after: inserts the entry right after first line that matches regular expression specified by this argument, set to EOF to insert at the end of the file
:type insert_after: str
:param insert_before: inserts the entry right before first line that matches regular expression specified by this argument, set to BOF to insert at the beginning of the file
:type insert_before: str
:param insensitive: ignore case
:type insensitive: bool
:param separator: separates parameter from the value (literal)
:type separator: str
:param separator_regex: regular expression that describes the separator and surrounding whitespace
:type separator_regex: str
:param prefix_regex: regular expression describing allowed leading characters at each line
:type prefix_regex: str
:param sed_path_separator:
:type sed_path_separator: char

#}}
{{%- macro set_config_file(path, parameter, value, create, insert_after, insert_before, insensitive=true, separator=" ", separator_regex="\s\+", prefix_regex="^\s*", sed_path_separator="/") -%}}
    {{%- set new_line = parameter+separator~value -%}}
    {{#- An escaped dollar in the parameter is escaped because of its significance for the shell, so when making a regex out of the parameter, we remove the shell escape, as the regex escape will do its thing. -#}}
    {{%- set line_regex = prefix_regex + ((parameter | replace("\\$", "$") | escape_regex) | replace("/", "\/")) + separator_regex -%}}
if [ -e "{{{ path }}}" ] ; then
    {{{ lineinfile_absent(path, line_regex, insensitive, sed_path_separator=sed_path_separator) | indent(4) }}}
else
    {{%- if create %}}
    touch "{{{ path }}}"
    {{%- else %}}
    {{{ die("Path '" + path + "' wasn't found on this system. Refusing to continue.", action="return") | indent(4) }}}
    {{%- endif %}}
fi
{{{ lineinfile_present(path, new_line, insert_after, insert_before, insensitive, sed_path_separator=sed_path_separator) }}}
{{%- endmacro -%}}


{{%- macro lineinfile_absent(path, regex, insensitive=true, sed_path_separator="/") -%}}
    {{%- if insensitive -%}}
        {{%- set modifier="Id" -%}}
    {{%- else -%}}
        {{%- set modifier="d" -%}}
    {{%- endif -%}}
    {{% if sed_path_separator in regex %}}
    {{{ raise("regex (" + regex + ") uses sed path separator (" + sed_path_separator + ") in " + rule_id) }}}
    {{% endif %}}
LC_ALL=C sed -i "{{{ sed_path_separator }}}{{{ regex }}}{{{ sed_path_separator }}}{{{ modifier }}}" "{{{ path }}}"
{{%- endmacro -%}}


{{%- macro lineinfile_absent_in_directory(dirname, regex, insensitive=true, filename_glob="*") -%}}
    {{%- if insensitive -%}}
        {{%- set modifier="Id" -%}}
    {{%- else -%}}
        {{%- set modifier="d" -%}}
    {{%- endif -%}}
LC_ALL=C sed -i "/{{{ regex }}}/{{{ modifier }}}" "{{{ dirname }}}"/{{{ filename_glob }}}
{{%- endmacro -%}}


{{%- macro lineinfile_present(path, line, insert_after="", insert_before="", insensitive=true, sed_path_separator="/") -%}}
    {{%- if insensitive -%}}
        {{%- set grep_args="-q -m 1 -i" -%}}
    {{%- else -%}}
        {{%- set grep_args="-q -m 1" -%}}
    {{%- endif -%}}
# make sure file has newline at the end
sed -i -e '$a\' "{{{ path }}}"

cp "{{{ path }}}" "{{{ path }}}.bak"
    {{%- if not (insert_after or insert_before)  or insert_after == "EOF" %}}
# Insert at the end of the file
printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    {{%- elif insert_before == "BOF" %}}
# Insert at the beginning of the file
printf '%s\n' "{{{ line }}}" > "{{{ path }}}"
cat "{{{ path }}}.bak" >> "{{{ path }}}"
    {{%- elif insert_after %}}
# Insert after the line matching the regex '{{{ insert_after }}}'
line_number="$(LC_ALL=C grep -n "{{{ insert_after }}}" "{{{ path }}}.bak" | LC_ALL=C sed 's{{{sed_path_separator}}}:.*{{{sed_path_separator}}}{{{sed_path_separator}}}g')"
if [ -z "$line_number" ]; then
    # There was no match of '{{{ insert_after }}}', insert at
    # the end of the file.
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
else
    head -n "$(( line_number ))" "{{{ path }}}.bak" > "{{{ path }}}"
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    tail -n "+$(( line_number + 1 ))" "{{{ path }}}.bak" >> "{{{ path }}}"
fi
    {{%- elif insert_before %}}
# Insert before the line matching the regex '{{{ insert_before }}}'.
line_number="$(LC_ALL=C grep -n "{{{ insert_before }}}" "{{{ path }}}.bak" | LC_ALL=C sed 's{{{sed_path_separator}}}:.*{{{sed_path_separator}}}{{{sed_path_separator}}}g')"
if [ -z "$line_number" ]; then
    # There was no match of '{{{ insert_before }}}', insert at
    # the end of the file.
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
else
    head -n "$(( line_number - 1 ))" "{{{ path }}}.bak" > "{{{ path }}}"
    printf '%s\n' "{{{ line }}}" >> "{{{ path }}}"
    tail -n "+$(( line_number ))" "{{{ path }}}.bak" >> "{{{ path }}}"
fi
    {{%- else %}}
{{{ die("This remediation has been generated incorrectly.") }}}
    {{%- endif %}}
# Clean up after ourselves.
rm "{{{ path }}}.bak"
{{%- endmacro -%}}


{{#
  Generates bash script code that puts 'contents' into a file at 'filepath'

:param filepath: Filepath of the file to check
:type filepath: str
:param contents:  Contents that should be in the file
:type contents: str

#}}
{{%- macro bash_file_contents(filepath='', contents='') %}}
cat << 'EOF' > {{{ filepath }}}
{{{ contents }}}
EOF
{{%- endmacro %}}


{{# Strips anchors regex around the banner text #}}
{{% macro bash_deregexify_banner_anchors(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/^\^\(.*\)\$$/\1/g')
{{%- endmacro %}}


{{# Strips multibanner regex and keeps only the first banner #}}
{{% macro bash_deregexify_multiple_banners(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/^(\(.*\.\)|.*)$/\1/g')
{{%- endmacro %}}


{{# Strips whitespace or newline regex #}}
{{% macro bash_deregexify_banner_space(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/\[\\s\\n\]+/ /g')
{{%- endmacro %}}


{{# Strips newline or newline escape sequence regex #}}
{{% macro bash_deregexify_banner_newline(banner_var_name, newline) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/(?:\[\\n\]+|(?:\\\\n)+)/{{{ newline }}}/g')
{{%- endmacro %}}


{{# Strips newline token for a newline escape sequence regex #}}
{{% macro bash_deregexify_banner_newline_token(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/(n)\*/\\n/g')
{{%- endmacro %}}


{{# Strips backslash regex #}}
{{% macro bash_deregexify_banner_backslash(banner_var_name) -%}}
{{{ banner_var_name }}}=$(echo "${{{ banner_var_name }}}" | sed 's/\\//g')
{{%- endmacro %}}


{{% macro bash_ini_file_set(filename, section, key, value) -%}}
{{% set config_dir = "/".join(filename.split("/")[:-1]) %}}
# Try find '[{{{ section }}}]' and '{{{ key }}}' in '{{{ filename }}}', if it exists, set
# to '{{{ value }}}', if it isn't here, add it, if '[{{{ section }}}]' doesn't exist, add it there
if grep -qzosP '[[:space:]]*\[{{{ section }}}]([^\n\[]*\n+)+?[[:space:]]*{{{ key }}}' '{{{ filename }}}'; then
    {{% if '/' in key %}}
    {{{ raise("key (" + key + ") uses sed path separator (/) in " + rule_id) }}}
    {{% elif '/' in value %}}
    {{{ raise("value (" + value + ") uses sed path separator (/) in " + rule_id) }}}
    {{% endif %}}
    sed -i "s/{{{ key }}}[^(\n)]*/{{{ key }}}={{{ value }}}/" '{{{ filename }}}'
elif grep -qs '[[:space:]]*\[{{{ section }}}]' '{{{ filename }}}'; then
    sed -i "/[[:space:]]*\[{{{ section }}}]/a {{{ key }}}={{{ value }}}" '{{{ filename }}}'
else
    if test -d "{{{ config_dir }}}"; then
        printf '%s\n' '[{{{ section }}}]' "{{{ key }}}={{{ value }}}" >> '{{{ filename }}}'
    else
        echo "Config file directory '{{{ config_dir }}}' doesnt exist, not remediating, assuming non-applicability." >&2
    fi
fi
{{%- endmacro %}}


{{%- macro bash_sudo_remove_config(parameter, pattern) -%}}
for f in /etc/sudoers /etc/sudoers.d/* ; do
  if [ ! -e "$f" ] ; then
    continue
  fi
  matching_list=$(grep -P '^(?!#).*[\s]+{{{ pattern }}}.*$' $f | uniq )
  if ! test -z "$matching_list"; then
    while IFS= read -r entry; do
      # comment out "{{{ parameter }}}" matches to preserve user data
      sed -i "s/^${entry}$/# &/g" $f
    done <<< "$matching_list"

    /usr/sbin/visudo -cf $f &> /dev/null || echo "Fail to validate $f with visudo"
  fi
done
{{%- endmacro -%}}

{{% macro bash_sssd_ldap_config(parameter, value) -%}}
SSSD_CONF="/etc/sssd/sssd.conf"
LDAP_REGEX='[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*{{{ parameter }}}'
AD_REGEX='[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*id_provider[[:space:]]*=[[:space:]]*((?i)ad)[[:space:]]*$'
DOMAIN_REGEX="[[:space:]]*\[domain\/[^]]*]"

# Check if id_provider is not set to ad (Active Directory) which makes start_tls not applicable, note the -v option to invert the grep.
# Try to find [domain/..] and {{{ parameter }}} in sssd.conf, if it exists, set to '{{{ value }}}'
# if {{{ parameter }}} isn't here, add it
# if [domain/..] doesn't exist, add it here for default domain
if grep -qvzosP $AD_REGEX $SSSD_CONF; then
        if grep -qzosP $LDAP_REGEX $SSSD_CONF; then
                {{% if '#' in parameter %}}
                {{{ raise("parameter (" + parameter + ") uses sed path separator (#) in " + rule_id) }}}
                {{% endif %}}
                sed -i "s#{{{ parameter }}}[^(\n)]*#{{{ parameter }}} = {{{ value }}}#" $SSSD_CONF
        elif grep -qs $DOMAIN_REGEX $SSSD_CONF; then
                sed -i "/$DOMAIN_REGEX/a {{{ parameter }}} = {{{ value }}}" $SSSD_CONF
        else
                if test -f "$SSSD_CONF"; then
                        echo -e "[domain/default]\n{{{ parameter }}} = {{{ value }}}" >> $SSSD_CONF
                else
                        echo "Config file '$SSSD_CONF' doesnt exist, not remediating, assuming non-applicability." >&2
                fi
        fi
fi

readarray -t SSSD_CONF_D_FILES < <(find /etc/sssd/conf.d/ -name "*.conf")
for SSSD_CONF_D_FILE in "${SSSD_CONF_D_FILES[@]}"; do
    sed -i "s#{{{ parameter }}}[^(\n)]*#{{{ parameter }}} = {{{ value }}}#" "$SSSD_CONF_D_FILE"
done

{{%- endmacro %}}


{{#
    Check whether or not a package is installed.
#}}
{{%- macro bash_package_installed(pkgname) -%}}
{{%- if pkg_manager == "apt_get" -%}}
dpkg-query --show --showformat='${db:Status-Status}\n' "{{{ pkgname }}}" 2>/dev/null | grep -q ^installed
{{%- else -%}}
rpm --quiet -q "{{{ pkgname }}}"
{{%- endif -%}}
{{%- endmacro -%}}


{{#
    Set rule CCE value

    This macro gets the var cce_identifiers from the environment created by the build scripts.
    The cce_identifiers is a dictionary that contains either the 'cce':'CCENUM' record for the
    product this remediation is being built for, or it is empty.

#}}
{{%- macro set_cce_value() -%}}
{{% if cce_identifiers and 'cce' in cce_identifiers -%}}
cce="{{{ cce_identifiers['cce'] }}}"
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Ensure file ends with newline

    Do not modify file at all if there already is newline. Always follows
    symlinks.

:param file:     file to check
:type file: str

#}}
{{%- macro bash_ensure_nl_at_eof(file) -%}}
{{#- Plain sed '$a\' updates stat even if it dones not change the file. -#}}
if [[ -s "{{{ file }}}" ]] && [[ -n "$(tail -c 1 -- "{{{ file }}}" || true)" ]]; then
    LC_ALL=C sed -i --follow-symlinks '$a'\\ "{{{ file }}}"
fi
{{%- endmacro -%}}


{{#
    Macro to replace configuration setting in config file or add the configuration setting if
    it does not exist.

    Example Calls:

      With default format of 'key = value'::

        {{{ bash_replace_or_append('/etc/sysctl.conf', '^kernel.randomize_va_space', '2') }}}

      With custom key/value format::

        {{{ bash_replace_or_append('/etc/sysconfig/selinux', '^SELINUX=', 'disabled', '%s=%s') }}}

      With a variable::

        {{{ bash_replace_or_append('/etc/sysconfig/selinux', '^SELINUX=', "$var_selinux_state", '%s=%s') }}}

:param config_file: Configuration file that will be modified
:type config_file: str
:param key: Configuration option to change
:type key: str
:param value: Value of the configuration option to change
:type value: str
:param format: Optional argument, The printf-like format string that will be given stripped key and value as arguments, so e.g. ``%s=%s` will result in key=value substitution (i.e. without spaces around =)
:type format: str

#}}

{{%- macro bash_comment_config_line(config_file, key) -%}}
# If the key exists, comment it. Otherwise do nothing
# We search for the key string followed by a blank space,
# so if we search for 'setting', 'setting2' won't match.
if LC_ALL=C grep -q -m 1 -i -e "{{{ key }}}[[:blank:]]" "{{{ config_file }}}"; then
    LC_ALL=C sed -i --follow-symlinks "s/{{{ key }}}[[:blank:]].*/#&/gi" "{{{ config_file }}}"
fi
{{%- endmacro -%}}



{{%- macro bash_replace_or_append(config_file, key, value, format='%s = %s') -%}}
# Strip any search characters in the key arg so that the key can be replaced without
# adding any search characters to the config file.
stripped_key=$(sed 's/[\^=\$,;+]*//g' <<< "{{{ key }}}")

# shellcheck disable=SC2059
printf -v formatted_output "{{{ format }}}" "$stripped_key" "{{{ value }}}"

# If the key exists, change it. Otherwise, add it to the config_file.
# We search for the key string followed by a word boundary (matched by \>),
# so if we search for 'setting', 'setting2' won't match.
if LC_ALL=C grep -q -m 1 -i -e "{{{ key }}}\\>" "{{{ config_file }}}"; then
    escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
    LC_ALL=C sed -i --follow-symlinks "s/{{{ key }}}\\>.*/$escaped_formatted_output/gi" "{{{ config_file }}}"
else
    {{{ bash_ensure_nl_at_eof(config_file) | indent }}}
    {{%- if cce_identifiers and 'cce' in cce_identifiers %}}
    {{{ set_cce_value() }}}
    printf '# Per %s: Set %s in %s\n' "${cce}" "${formatted_output}" "{{{ config_file }}}" >> "{{{ config_file }}}"
    {{%- endif %}}
    printf '%s\n' "$formatted_output" >> "{{{ config_file }}}"
fi
{{%- endmacro -%}}


{{#
    Macro to restrict permissions in home directories of interactive users.

#}}
{{%- macro bash_restrict_permissions_home_directories(recursive=false) -%}}
for home_dir in $(awk -F':' '{ if ($3 >= {{{ uid_min }}} && $3 != {{{ nobody_uid }}} && $6 != "/") print $6 }' /etc/passwd); do
    # Only update the permissions when necessary. This will avoid changing the inode timestamp when
    # the permission is already defined as expected, therefore not impacting in possible integrity
    # check systems that also check inodes timestamps.
    {{%- if recursive %}}
    find "$home_dir" -perm /7027 \! -type l -exec chmod u-s,g-w-s,o=- {} \;
    {{%- else %}}
    find "$home_dir" -maxdepth 0 -perm /7027 \! -type l -exec chmod u-s,g-w-s,o=- {} \;
    {{%- endif %}}
done
{{%- endmacro -%}}


{{#
    To see how args corresponds to an :code:`/etc/fstab` entry, see
    `bash_ensure_mount_option_for_vfstype <#template-bash_ensure_mount_option_in_fstab>`_
    documentation

:param vfstype:     type of filesystem
:type vfstype: str
:param mount_opt:   mount point option which we are checking
:type mount_opt: str
:param fs_spec:     identification of the filesystem to be mounted (LABEL, UUID, device name etc.)
:type fs_spec: str
:param type:        mount type of new mount point (used when adding new entry in fstab)
:type type: str

#}}
{{% macro bash_ensure_mount_option_for_vfstype(vfstype, mount_opt, fs_spec, type) -%}}
vfstype_points=()
readarray -t vfstype_points < <(grep -E "[[:space:]]{{{ vfstype }}}[[:space:]]" /etc/fstab | awk '{print $2}')

for vfstype_point in "${vfstype_points[@]}"
do
    {{{ bash_ensure_mount_option_in_fstab("${vfstype_point//\\\\/\\\\\\\\}", mount_opt, fs_spec, type) | indent(4) }}}
done
{{%- endmacro %}}


{{#
Ensures that given mount point is in :code:`/etc/fstab`.

    If we look at an example invocation of this macro::

        {{{ bash_ensure_mount_option_in_fstab("/home", "auto_da_alloc", "LABEL=t-home2", "ext4") }}}}

    The resulting :code:`/etc/fstab` entry could look like this::

        LABEL=t-home2   /home      ext4    defaults,auto_da_alloc      0  2

:param mount_point: mount point
:type mount_point: str
:param mount_opt:   mount point option whose presence in /etc/fstab we are ensuring
:type mount_opt: str
:param fs_spec:     identification of the filesystem to be mounted (LABEL, UUID, device name etc.)
:type fs_spec: str
:param type:        mount type of mount point (used when adding new entry in fstab)
:type type: str

#}}
{{% macro bash_ensure_mount_option_in_fstab(mount_point, mount_opt, fs_spec, type) -%}}
mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" {{{ mount_point }}})"

# If the mount point is not in /etc/fstab, get previous mount options from /etc/mtab
if ! grep -q "$mount_point_match_regexp" /etc/fstab; then
    # runtime opts without some automatic kernel/userspace-added defaults
    previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/mtab | head -1 |  awk '{print $4}' \
                | sed -E "s/(rw|defaults|seclabel|{{{ mount_opt }}})(,|$)//g;s/,$//")
    [ "$previous_mount_opts" ] && previous_mount_opts+=","
    # In iso9660 filesystems mtab could describe a "blocksize" value, this should be reflected in
    # fstab as "block".  The next variable is to satisfy shellcheck SC2050.
    fs_type="{{{ type }}}"
    if [  "$fs_type" == "iso9660" ] ; then
        previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
    fi
    echo "{{{ fs_spec }}} {{{ mount_point }}} {{{ type }}} defaults,${previous_mount_opts}{{{ mount_opt }}} 0 0" >> /etc/fstab
# If the mount_opt option is not already in the mount point's /etc/fstab entry, add it
elif ! grep "$mount_point_match_regexp" /etc/fstab | grep -q "{{{ mount_opt }}}"; then
    previous_mount_opts=$(grep "$mount_point_match_regexp" /etc/fstab | awk '{print $4}')
    sed -i "s|\(${mount_point_match_regexp}.*${previous_mount_opts}\)|\1,{{{ mount_opt }}}|" /etc/fstab
fi
{{%- endmacro %}}


{{#
    Check whether mount_point is present in /etc/fstab; print err to stderr and return 1 if not

#}}
{{% macro bash_assert_mount_point_in_fstab(mount_point) -%}}
mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "{{{ mount_point }}}")"
{{#
    This macro gets expanded to code that will return 1 if MOUNTPOINT is not in /etc/fstab;
    This is consistent with the behavior prior to converting this function to a jinja macro
#}}
grep "$mount_point_match_regexp" -q /etc/fstab \
    || { echo "The mount point '{{{ mount_point }}}' is not even in /etc/fstab, so we can't set up mount options" >&2;
            echo "Not remediating, because there is no record of {{{ mount_point }}} in /etc/fstab" >&2; return 1; }
{{%- endmacro %}}


{{#
  Ensure that partition is mounted at mount_point with correct options, but only if the partition
  is already mounted.

#}}
{{% macro bash_ensure_partition_is_mounted(mount_point) -%}}
if mkdir -p "{{{ mount_point }}}"; then
    if mountpoint -q "{{{ mount_point }}}"; then
        mount -o remount --target "{{{ mount_point }}}"
    fi
fi
{{%- endmacro %}}


{{#
Based on example audit syscall rule definitions as outlined in
:code:`/usr/share/doc/audit-2.3.7/stig.rules` file provided with the audit
package. It will combine multiple system calls belonging to the same
syscall group into one audit rule (rather than to create audit rule per
different system call) to avoid audit infrastructure performance penalty
in the case of 'one-audit-rule-definition-per-one-system-call'. See:

  https://www.redhat.com/archives/linux-audit/2014-November/msg00009.html

for further details.

Notes:

* The 2-nd up to 4-th arguments are used to determine how many existing audit
  rules will be inspected for resemblance with the new audit rule the macro
  is going to add.
* The macro's similarity check uses the 5-th argument to optimize audit rules
  definitions (merge syscalls of the same group into one rule) to avoid the
  "single-syscall-per-audit-rule" performance penalty.
* The key argument (7-th argument) is not used when the syscall is grouped to
  an existing audit rule. The audit rule will retain the key it already had.

:param tool:  tool used to load audit rules, either 'auditctl', or 'augenrules
:type tool: str
:param action_arch_filters: The action and arch filters of the rule. For example, "-a always,exit -F arch=b64"
:type action_arch_filters: str
:param other_filters: Other filters that may characterize the rule. For example, "-F a2&03 -F path=/etc/passwd"
:type other_filters: str
:param auid_filters: The auid filters of the rule. For example, "-F auid>=" ~ uid_min ~ " -F auid!=unset"
:type auid_filters: str
:param syscall: The syscall to ensure presense among audit rules. For example, "chown"
:type syscall: str
:param syscall_groupings: Other syscalls that can be grouped with 'syscall' as a space separated list. For example, "fchown lchown fchownat"
:type syscall_groupings: str
:param key: The key to use when appending a new rule
:type key: str

#}}
{{% macro bash_fix_audit_syscall_rule(tool, action_arch_filters, other_filters, auid_filters, syscall, syscall_groupings, key) -%}}

unset syscall_a
unset syscall_grouping
unset syscall_string
unset syscall
unset file_to_edit
unset rule_to_edit
unset rule_syscalls_to_edit
unset other_string
unset auid_string
unset full_rule

# Load macro arguments into arrays
read -a syscall_a <<< {{{ syscall }}}
read -a syscall_grouping <<< {{{ syscall_groupings }}}

# Create a list of audit *.rules files that should be inspected for presence and correctness
# of a particular audit rule. The scheme is as follows:
#
# -----------------------------------------------------------------------------------------
#  Tool used to load audit rules | Rule already defined  |  Audit rules file to inspect    |
# -----------------------------------------------------------------------------------------
#        auditctl                |     Doesn't matter    |  /etc/audit/audit.rules         |
# -----------------------------------------------------------------------------------------
#        augenrules              |          Yes          |  /etc/audit/rules.d/*.rules     |
#        augenrules              |          No           |  /etc/audit/rules.d/$key.rules  |
# -----------------------------------------------------------------------------------------
#
files_to_inspect=()

{{% if tool == "auditctl" %}}
# If audit tool is 'auditctl', then add '/etc/audit/audit.rules'
# file to the list of files to be inspected
default_file="/etc/audit/audit.rules"
files_to_inspect+=('/etc/audit/audit.rules' )
{{%- else -%}}
# If audit tool is 'augenrules', then check if the audit rule is defined
# If rule is defined, add '/etc/audit/rules.d/*.rules' to the list for inspection
# If rule isn't defined yet, add '/etc/audit/rules.d/$key.rules' to the list for inspection
default_file="/etc/audit/rules.d/{{{ key }}}.rules"
# As other_filters may include paths, lets use a different delimiter for it
# The "F" script expression tells sed to print the filenames where the expressions matched
readarray -t files_to_inspect < <(sed -s -n -e "/^{{{ action_arch_filters }}}/!d" -e "\#{{{ other_filters }}}#!d" -e "/{{{ auid_filters }}}/!d" -e "F" /etc/audit/rules.d/*.rules)
# Case when particular rule isn't defined in /etc/audit/rules.d/*.rules yet
if [ ${#files_to_inspect[@]} -eq "0" ]
then
    file_to_inspect="/etc/audit/rules.d/{{{ key }}}.rules"
    files_to_inspect=("$file_to_inspect")
    if [ ! -e "$file_to_inspect" ]
    then
        touch "$file_to_inspect"
        chmod 0600 "$file_to_inspect"
    fi
fi
{{%- endif %}}

# After converting to jinja, we cannot return; therefore we skip the rest of the macro if needed instead
skip=1

for audit_file in "${files_to_inspect[@]}"
do
    # Filter existing $audit_file rules' definitions to select those that satisfy the rule pattern,
    # i.e, collect rules that match:
    # * the action, list and arch, (2-nd argument)
    # * the other filters, (3-rd argument)
    # * the auid filters, (4-rd argument)
    readarray -t similar_rules < <(sed -e "/^{{{ action_arch_filters }}}/!d"  -e "\#{{{ other_filters }}}#!d" -e "/{{{ auid_filters }}}/!d" "$audit_file")

    candidate_rules=()
    # Filter out rules that have more fields then required. This will remove rules more specific than the required scope
    for s_rule in "${similar_rules[@]}"
    do
        # Strip all the options and fields we know of,
        # than check if there was any field left over
        extra_fields=$(sed -E -e "s/^{{{ action_arch_filters }}}//"  -e "s#{{{ other_filters }}}##" -e "s/{{{ auid_filters }}}//" -e "s/((:?-S [[:alnum:],]+)+)//g" -e "s/-F key=\w+|-k \w+//"<<< "$s_rule")
        grep -q -- "-F" <<< "$extra_fields" || candidate_rules+=("$s_rule")
    done

    if [[ ${#syscall_a[@]} -ge 1 ]]
    then
        # Check if the syscall we want is present in any of the similar existing rules
        for rule in "${candidate_rules[@]}"
        do
            rule_syscalls=$(echo "$rule" | grep -o -P '(-S [\w,]+)+' | xargs)
            all_syscalls_found=0
            for syscall in "${syscall_a[@]}"
            do
                grep -q -- "\b${syscall}\b" <<< "$rule_syscalls" || {
                   # A syscall was not found in the candidate rule
                   all_syscalls_found=1
                   }
            done
            if [[ $all_syscalls_found -eq 0 ]]
            then
                # We found a rule with all the syscall(s) we want; skip rest of macro
                skip=0
                break
            fi

            # Check if this rule can be grouped with our target syscall and keep track of it
            for syscall_g in "${syscall_grouping[@]}"
            do
                if grep -q -- "\b${syscall_g}\b" <<< "$rule_syscalls"
                then
                    file_to_edit=${audit_file}
                    rule_to_edit=${rule}
                    rule_syscalls_to_edit=${rule_syscalls}
                fi
            done
        done
    else
        # If there is any candidate rule, it is compliant; skip rest of macro
        if [ "${#candidate_rules[@]}" -gt 0 ]
        then
            skip=0
        fi
    fi

    if [ "$skip" -eq 0 ]; then
        break
    fi
done

if [ "$skip" -ne 0 ]; then
    # We checked all rules that matched the expected resemblance pattern (action, arch & auid)
    # At this point we know if we need to either append the $full_rule or group
    # the syscall together with an exsiting rule

    # Append the full_rule if it cannot be grouped to any other rule
    if [ -z ${rule_to_edit+x} ]
    then
        # Build full_rule while avoid adding double spaces when other_filters is empty
        if [ "${#syscall_a[@]}" -gt 0 ]
        then
            syscall_string=""
            for syscall in "${syscall_a[@]}"
            do
                syscall_string+=" -S $syscall"
            done
        fi
        other_string=$([[ {{{ other_filters }}} ]] && echo " {{{ other_filters }}}") || /bin/true
        auid_string=$([[ {{{ auid_filters }}} ]] && echo " {{{ auid_filters }}}") || /bin/true
        full_rule="{{{ action_arch_filters }}}${syscall_string}${other_string}${auid_string} -F key={{{ key }}}" || /bin/true
        echo "$full_rule" >> "$default_file"
        chmod 0600 ${default_file}
    else
        # Check if the syscalls are declared as a comma separated list or
        # as multiple -S parameters
        if grep -q -- "," <<< "${rule_syscalls_to_edit}"
        then
            delimiter=","
        else
            delimiter=" -S "
        fi
        new_grouped_syscalls="${rule_syscalls_to_edit}"
        for syscall in "${syscall_a[@]}"
        do
            grep -q -- "\b${syscall}\b" <<< "${rule_syscalls_to_edit}" || {
               # A syscall was not found in the candidate rule
               new_grouped_syscalls+="${delimiter}${syscall}"
               }
        done

        # Group the syscall in the rule
        sed -i -e "\#${rule_to_edit}#s#${rule_syscalls_to_edit}#${new_grouped_syscalls}#" "$file_to_edit"
    fi
fi
{{%- endmacro %}}


{{#
    Ensures that /etc/default/grub file contains the arg_name_value.

:param arg_name: name of the grub parameter, e.g.: "audit"
:type arg_name: str
:param arg_name_value: parameter together with the value to ensure, e.g.: "audit=1"
:type arg_name_value: str

#}}
{{%- macro update_etc_default_grub_manually(arg_name, arg_name_value) -%}}
# Correct the form of default kernel command line in GRUB
if grep -q '^\s*GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"'  '/etc/default/grub' ; then
       # modify the GRUB command-line if an {{{ arg_name }}}= arg already exists
       sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\){{{ arg_name }}}=[^[:space:]]\+\(.*\"\)/\1{{{ arg_name_value }}}\2/"  '/etc/default/grub'
# Add to already existing GRUB_CMDLINE_LINUX parameters
elif grep -q '^\s*GRUB_CMDLINE_LINUX='  '/etc/default/grub' ; then
       # no {{{ arg_name }}}=arg is present, append it
       sed -i "s/\(^\s*GRUB_CMDLINE_LINUX=\".*\)\"/\1 {{{ arg_name_value }}}\"/"  '/etc/default/grub'
# Add GRUB_CMDLINE_LINUX parameters line
else
       echo "GRUB_CMDLINE_LINUX=\"{{{ arg_name_value }}}\"" >> '/etc/default/grub'
fi
{{%- endmacro %}}


{{#
Macro for Bash remediation for adding a kernel command line argument to the GRUB 2 bootloader.
Part of the grub2_bootloader_argument template.

:param arg_name: Kernel command line argument
:type arg_name: str
:param arg_name_value: Kernel command line argument concatenated with the value of this argument using an equal sign, eg. "noexec=off".
:type arg_name_value: str

#}}
{{% macro grub2_bootloader_argument_remediation(arg_name, arg_name_value) %}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['ol7', 'sle12', 'sle15'] %}}
{{{ update_etc_default_grub_manually(arg_name, arg_name_value) }}}
{{% endif -%}}
{{{ grub_command("add", arg_name_value) }}}
{{% endmacro %}}


{{#
    Ensures that /etc/default/grub file does not contain the arg_name_value.

:param arg_name: name of the grub parameter, e.g.: "audit"
:type arg_name: str

#}}
{{%- macro update_etc_default_grub_manually_absent(arg_name) -%}}
# Correct the form of default kernel command line in GRUB
if grep -q '^GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"'  '/etc/default/grub' ; then
       sed -i 's/\(^GRUB_CMDLINE_LINUX=".*\){{{ arg_name }}}=\?[^[:space:]]*\(.*"\)/\1 \2/' '/etc/default/grub'
fi
{{%- endmacro %}}


{{#
Macro for Bash remediation for removing a kernel command line argument from the GRUB 2 bootloader.
Part of the grub2_bootloader_argument_absent template.

:param arg_name: Name of the kernel command line argument that will be removed from GRUB 2 configuration.
:type arg_name: str

#}}
{{% macro grub2_bootloader_argument_absent_remediation(arg_name) %}}
{{% if 'ubuntu' in product or product in ['ol7', 'sle12', 'sle15', 'slmicro5'] %}}
{{{ update_etc_default_grub_manually_absent(arg_name) }}}
{{% endif -%}}
{{{ grub_command("remove", arg_name) }}}
{{% endmacro %}}


{{#
This macro creates a bash conditional which is used to determine if a
remediation is applicable. The macro takes package as an argument and chooses
appropriate package manager. If the package is installed and satisfies the
optional version restricion, the Bash remediation will be applied. The macro
respects `platform_package_overrides` variable.

:param package: package name
:type package: str
:param op: version comparison operator (optional argument, "<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
:type ver: str

#}}
{{%- macro bash_pkg_conditional(package, op=None, ver=None) -%}}
{{%- if package in platform_package_overrides -%}}
  {{%- set package = platform_package_overrides[package] -%}}
{{%- endif -%}}
  {{% if pkg_system is defined %}}
    {{%- if pkg_system == "rpm" -%}}
        {{{ bash_pkg_conditional_rpm(package, op, ver) }}}
    {{%- elif pkg_system == "dpkg" -%}}
        {{{ bash_pkg_conditional_dpkg(package, op, ver) }}}
    {{%- else -%}}
JINJA MACRO ERROR - Unknown package system '{{{ pkg_system }}}'.
    {{%- endif -%}}
{{% endif %}}
{{%- endmacro -%}}


{{#
This macro generates code that gets version of an installed RPM package.

:param package: package name
:type package: str

#}}
{{%- macro bash_get_rpm_package_version(package) -%}}
$(epoch=$(rpm -q --queryformat '%{EPOCH}' {{{ package }}}); version=$(rpm -q --queryformat '%{VERSION}' {{{ package }}}); [ "$epoch" = "(none)" ] && echo "0:$version" || echo "$epoch:$version")
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional that compares version of the package
with a given version.

Description of the algorithm:

#. Get the actual version of the given package and store it in `real`.
#. Store the expected version in `ver`.
#. Perform the comparison and return the result.
   Comparison method is different based on the comparison operator. The method
   code is chosen at the build time during Jinja expansion. Therefore, the
   algorithm doesn't use the operator at all.
   Based on the operator, these operations are performed:

   #. "<": real != ver && is_sorted([real, ver])
   #. "<=": is_sorted([real, ver])
   #. "==": real == ver
   #. "!=": real != ver
   #. ">=" real != ver && is_sorted([ver, real])
   #. ">" is_sorted([ver, real])

   where is_sorted returns true if the given list parameter is a sorted list of version numbers.

The implementation uses the GNU `sort` version ordering, which is described at:
https://www.gnu.org/software/coreutils/manual/coreutils.html#Version-sort-ordering

:param real: real package version
:type real: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param expected: expected package version
:type expected: str

#}}
{{%- macro bash_pkg_conditional_compare(real, op, expected) -%}}
{ real="{{{ real }}}"; expected="{{{ expected }}}"; {{{ bash_compare_version("$real", op, "$expected") }}}; }
{{%- endmacro -%}}


{{#
This macro generates comparison code based on the operator.

Assumptions:

* Version arguments are either literal, or they expand to versions (e.g. the argument is a deferenced variable)
* Either all versions have epoch, or none of them has.

  * Violation of this results in undefined behavior.
  * If one has epoch e.g. 0, and the other one has no epoch, they will not be treated as equal.

:param real: real package version
:type real: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param expected: expected package version
:type expected: str

#}}
{{%- macro bash_compare_version(real, op, expected) -%}}
{{%- if op == "<" -%}}
[[ "{{{ real }}}" != "{{{ expected }}}" ]] && printf "%s\n%s" "{{{ real }}}" "{{{ expected }}}" | sort -VC
{{%- elif op == "<=" -%}}
printf "%s\n%s" "{{{ real }}}" "{{{ expected }}}" | sort -VC
{{%- elif op == "==" -%}}
[[ "{{{ real }}}" == "{{{ expected }}}" ]]
{{%- elif op == "!=" -%}}
[[ "{{{ real }}}" != "{{{ expected }}}" ]]
{{%- elif op == ">" -%}}
[[ "{{{ real }}}" != "{{{ expected }}}" ]] && printf "%s\n%s" "{{{ expected }}}" "{{{ real }}}" | sort -VC
{{%- elif op == ">=" -%}}
printf "%s\n%s" "{{{ expected }}}" "{{{ real }}}" | sort -VC
{{%- endif -%}}
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional which uses rpm to check if a package passed as a parameter is installed.

:param package: package name
:type package: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
    The version always needs to contain epoch. If the package has no epoch, please prepend "0:".
:type ver: str

#}}
{{%- macro bash_pkg_conditional_rpm(package, op=None, ver=None) -%}}
{{%- if ver -%}}
rpm --quiet -q {{{ package }}} && {{{ bash_pkg_conditional_compare(bash_get_rpm_package_version(package), op, ver) }}}
{{%- else -%}}
rpm --quiet -q {{{ package }}}
{{%- endif -%}}
{{%- endmacro %}}


{{#
This macro generates code that gets version of an installed DEB package.

:param package: package name
:type package: str

#}}
{{%- macro bash_get_dpkg_package_version(package) -%}}
{{# We don't take the "release" part into account. #}}
dpkg-query -f='${Version}\n' --show {{{ package }}} | cut -f1 -d-
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional that compares version of the DEB package
with a given version.

:param package: package name
:type package: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
:type ver: str

#}}
{{%- macro bash_compare_version_dpkg(package, op, ver) -%}}
{{%- set op_codes = ({"<":"lt", "<=":"le", "==":"eq", "!=":"ne", ">":"gt", ">=":"ge"}) -%}}
{ real="$({{{ bash_get_dpkg_package_version(package) }}})"; ver="{{{ ver }}}"; dpkg --compare-versions "$real" "{{{ op_codes[op] }}}" "$ver"; }
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional which uses dpkg to check if a package passed as a parameter is installed.

:param package: package name
:type package: str
:param op: version comparison operator (optional argument, "<", "<=", "==", "!=", ">", ">=")
:type op: str
:param ver: package version (optional argument, use together with "op")
:type ver: str

#}}
{{%- macro bash_pkg_conditional_dpkg(package, op=None, ver=None) -%}}
{{%- if ver -%}}
dpkg-query --show --showformat='${db:Status-Status}\n' '{{{ package }}}' 2>/dev/null | grep -q '^installed' && {{{ bash_compare_version_dpkg(package, op, ver) }}}
{{%- else -%}}
dpkg-query --show --showformat='${db:Status-Status}\n' '{{{ package }}}' 2>/dev/null | grep -q '^installed'
{{%- endif -%}}
{{%- endmacro -%}}


{{#
Macro to replace configuration setting(s) in the Chromium stig policy (.json) file or add the
preference if it does not exist.

Example macro invocation::

    {{{ bash_chromium_pol_setting("chrome_stig_policy.json", "/etc/chromium/policies/managed/", "ExtensionInstallBlacklist", "\[\"*\"\]") }}}

:param chrome_pol_file:      Policy file to that will be modified
:type chrome_pol_file: str
:param chrome_pol_dir:       Directory where the policy file is located
:type chrome_pol_dir: str
:param pol_setting:          The setting that will be modified
:type pol_setting: str
:param pol_setting_val:      Value of the setting to replace the current value with
:type pol_setting_val: str
:param pol_setting_val_edit: Value of the setting to be inserted if setting and value not present
:type pol_setting_val_edit: str

#}}
{{%- macro bash_chromium_pol_setting(chrome_pol_file, chrome_pol_dir, pol_setting, pol_setting_val, pol_setting_val_edit=None) %}}
{{% if not pol_setting_val_edit %}}
{{% set pol_setting_val_edit = pol_setting_val %}}
{{% endif %}}

if ! grep -q {{{ pol_setting }}} {{{ chrome_pol_dir }}}{{{ chrome_pol_file }}}; then
   sed -i -e '/{/a \  "'{{{ pol_setting }}}'": '{{{ pol_setting_val_edit }}}',' {{{ chrome_pol_dir }}}{{{ chrome_pol_file }}}
else
   sed -i -e 's/\"'{{{ pol_setting }}}'.*/\"'{{{ pol_setting }}}'\": '{{{ pol_setting_val }}}',/g' {{{ chrome_pol_dir }}}{{{ chrome_pol_file }}}
fi
{{%- endmacro -%}}


{{#
    Macro that lets you define the body of a loop that iterates over the output of the find command
    Use with the call block syntax {{% call iterate_over_find_output("fname", "mydir -name *.conf") %}} ...

#}}
{{% macro iterate_over_find_output(varname, find_args="") -%}}
while IFS= read -r -d '' {{{ varname }}}; do
    {{{ caller() | indent(4) }}}
done <   <(find {{{ find_args }}} -print0)
{{%- endmacro %}}


{{#
    Macro that lets you define the body of a loop that iterates over the output of any command
    Use with the call block syntax {{% call iterate_over_find_output("fname", "awk ... myfile") %}} ...

#}}
{{% macro iterate_over_command_output(varname, command_and_its_args) -%}}
while IFS= read -r {{{ varname }}}; do
    {{{ caller() | indent(4) }}}
done <   <({{{ command_and_its_args }}})
{{%- endmacro %}}


{{#
    Ensure key is set to correct value under a correct section in an .ini style config file

Example macro invocation(s)::

    {{{ bash_ensure_ini_config("/etc/sssd/sssd.conf", "pam", "offline_credentials_expiration", "1") }}}
    {{{ bash_ensure_ini_config("/etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf", "sssd", "user", "sssd") }}}

:param files:   list of space-separated files to add key = value to (may contain wildcards)
                if none contain section, create and append to FIRST file
:type files: str
:param section: section to add key = value under
:type section: str
:param key:     key
:type key: str
:param value:   value
:type value: str

#}}
{{% macro bash_ensure_ini_config(files, section, key, value, no_quotes=true) -%}}
found=false

# set value in all files if they contain section or key
for f in $(echo -n "{{{ files }}}"); do
    if [ ! -e "$f" ]; then
        continue
    fi

    # find key in section and change value
    if grep -qzosP "[[:space:]]*\[{{{ section }}}\]([^\n\[]*\n+)+?[[:space:]]*{{{ key }}}" "$f"; then
{{% if no_quotes %}}
            sed -i "s/{{{ key }}}[^(\n)]*/{{{ key }}}={{{ value | replace("/", "\/") }}}/" "$f"
{{% else %}}
            sed -i 's/{{{ key }}}[^(\n)]*/{{{ key }}}="{{{ value | replace("/", "\/") }}}"/' "$f"
{{% endif %}}
            found=true

    # find section and add key = value to it
    elif grep -qs "[[:space:]]*\[{{{ section }}}\]" "$f"; then
{{% if no_quotes %}}
            sed -i "/[[:space:]]*\[{{{ section }}}\]/a {{{ key }}}={{{ value | replace("/", "\/") }}}" "$f"
{{% else %}}
            sed -i '/[[:space:]]*\[{{{ section }}}\]/a {{{ key }}}="{{{ value | replace ("/", "\/") }}}"' "$f"
{{% endif %}}
            found=true
    fi
done

# if section not in any file, append section with key = value to FIRST file in files parameter
if ! $found ; then
    file=$(echo "{{{ files }}}" | cut -f1 -d ' ')
    mkdir -p "$(dirname "$file")"
{{% if no_quotes %}}
    echo -e "[{{{ section }}}]\n{{{ key }}}={{{ value }}}" >> "$file"
{{% else %}}
    echo -e '[{{{ section }}}]\n{{{ key }}}="{{{ value }}}"' >> "$file"
{{% endif %}}
fi
{{%- endmacro %}}


{{#
    Make sure that a line with a specific PAM module is present with the correct control.
    If the line is not present, it will be included after the regex informed in the "after_match"
    parameter. If the "after_match" parameter is empty, the line will be included at the end of
    the file informed in the "pam_file" parameter.

    If the line was already present, but with a different control, the control will be updated.
    Note: If there are multiple lines matching the "group" + "module", no lines will be updated.
    Instead, a new line will be included after the regex informed in "after_match" or at the
    end of file if "after_match" parameter is empty or there is no match.

    This is a conservative safeguard for improper use of this macro in rare cases of modules
    configured by multiple lines, like pam_sss.so, pam_faillock.so and pam_lastlog.so. In some
    situations, these special modules may have similar lines sharing the same "group" and "module".
    For these specific cases, this macro is not recommened without careful tests to make sure the
    PAM module is working as expected. Otherwise, a custom remediation should be considered.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags.
:type control: str
:param module:          PAM module name.
:type module: str
:param after_match:     Regex used as reference to append a line, if necessary. Optional parameter.
                        Note: For this macro, there is a special value used to include a line at the beginning of the file: "BOF"
:type after_match: str

#}}
{{%- macro bash_ensure_pam_module_line(pam_file, group, control, module, after_match='') -%}}
{{% set control_regex = control | escape_regex %}}
if ! grep -qP "^\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}\s*.*" "{{{ pam_file }}}"; then
    # Line matching group + control + module was not found. Check group + module.
    if [ "$(grep -cP '^\s*{{{ group }}}\s+.*\s+{{{ module }}}\s*' "{{{ pam_file }}}")" -eq 1 ]; then
        # The control is updated only if one single line matches.
        sed -i -E --follow-symlinks "s/^(\s*{{{ group }}}\s+).*(\b{{{ module }}}.*)/\1{{{ control }}} \2/" "{{{ pam_file }}}"
    else
        {{%- if after_match == '' %}}
        echo "{{{ group }}}    {{{ control }}}    {{{ module }}}" >> "{{{ pam_file }}}"
        {{%- elif after_match == 'BOF'  %}}
        sed -i --follow-symlinks "1i {{{ group }}}     {{{ control }}}    {{{ module }}}" "{{{ pam_file }}}"
        {{%- else %}}
        LAST_MATCH_LINE=$(grep -nP "{{{ after_match }}}" "{{{ pam_file }}}" | tail -n 1 | cut -d: -f 1)
        if [ ! -z $LAST_MATCH_LINE ]; then
            sed -i --follow-symlinks $LAST_MATCH_LINE" a {{{ group }}}     {{{ control }}}    {{{ module }}}" "{{{ pam_file }}}"
        else
            echo "{{{ group }}}    {{{ control }}}    {{{ module }}}" >> "{{{ pam_file }}}"
        fi
        {{%- endif %}}
    fi
fi
{{%- endmacro -%}}


{{#
    Make sure that an existing PAM module line is properly configured with an option.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option.
:type option: str
:param value:           PAM module option argument, if is case. Optional parameter.
:type value: str
:param after_match:     Regex used as reference to include the PAM line below, if necessary. Optional parameter.
:type after_match: str

#}}
{{%- macro bash_ensure_pam_module_option(pam_file, group, control, module, option, value='', after_match='') -%}}
{{% set control_regex = control | escape_regex %}}
{{{ bash_ensure_pam_module_line(pam_file, group, control, module, after_match) }}}
# Check the option
if ! grep -qP "^\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}\s*.*\s{{{ option }}}\b" "{{{ pam_file }}}"; then
    {{%- if value == '' %}}
    sed -i -E --follow-symlinks "/\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}.*/ s/$/ {{{ option }}}/" "{{{ pam_file }}}"
    {{%- else %}}
    sed -i -E --follow-symlinks "/\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}.*/ s/$/ {{{ option }}}={{{ value }}}/" "{{{ pam_file }}}"
    {{%- endif %}}
{{%- if value == '' %}}
fi
{{%- else %}}
else
    sed -i -E --follow-symlinks "s/(\s*{{{ group }}}\s+{{{ control_regex }}}\s+{{{ module }}}\s+.*)({{{ option }}}=)[[:alnum:]]+\s*(.*)/\1\2{{{ value }}} \3/" "{{{ pam_file }}}"
fi
{{%- endif %}}
{{%- endmacro -%}}


{{#
    Remove a PAM module option if present in a PAM module line.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags. Optional parameter, but recommended to be informed whenever possible.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option.
:type option: str

#}}
{{%- macro bash_remove_pam_module_option(pam_file, group, control, module, option) -%}}
{{%- if control == '' %}}
if grep -qP "^\s*{{{ group }}}\s.*\b{{{ module }}}\s.*\b{{{ option }}}\b" "{{{ pam_file }}}"; then
    sed -i -E --follow-symlinks "s/(.*{{{ group }}}.*{{{ module }}}.*)\b{{{ option }}}\b=?[[:alnum:]]*(.*)/\1\2/g" "{{{ pam_file }}}"
{{%- else %}}
if grep -qP "^\s*{{{ group }}}\s+{{{ control }}}\s+{{{ module }}}\s.*\b{{{ option }}}\b" "{{{ pam_file }}}"; then
    sed -i -E --follow-symlinks "s/(.*{{{ group }}}.*{{{ control }}}.*{{{ module }}}.*)\s{{{ option }}}=?[[:alnum:]]*(.*)/\1\2/g" "{{{ pam_file }}}"
{{%- endif %}}
fi
{{%- endmacro -%}}


{{#
    Macro used to check if authselect files are intact. When used, it will exit the respective
    script if any authselect file was modified without proper use of authselect tool and
    respective profiles.

#}}
{{% macro bash_check_authselect_integrity() -%}}
if ! authselect check; then
echo "
authselect integrity check failed. Remediation aborted!
This remediation could not be applied because an authselect profile was not selected or the selected profile is not intact.
It is not recommended to manually edit the PAM files when authselect tool is available.
In cases where the default authselect profile does not cover a specific demand, a custom authselect profile is recommended."
exit 1
fi
{{%- endmacro %}}


{{#
    Macro used to ensure a custom authselect profile is in use before changing any PAM file.
    This macro is useful in cases where an authselect profile doesn't provide a feature to enable
    the desired PAM module or option. In these cases, a custom authselect profile is necessary.
    If the system already uses a custom authselect profile, no action is necessary. Otherwise, a
    new custom profile will be created based on the current profile and preserving the already
    enabled features. Custom profiles are only recommeded if an authselect feature for the same
    purpose is not available. In any case, this macro will also set the "CURRENT_PROFILE" variable
    which is also used in the "bash_ensure_pam_variables_and_authselect_profile" macro.

#}}
{{% macro bash_ensure_authselect_custom_profile() -%}}
CURRENT_PROFILE=$(authselect current -r | awk '{ print $1 }')
# If not already in use, a custom profile is created preserving the enabled features.
if [[ ! $CURRENT_PROFILE == custom/* ]]; then
    ENABLED_FEATURES=$(authselect current | tail -n+3 | awk '{ print $2 }')
    # The "local" profile does not contain essential security features required by multiple Benchmarks.
    # If currently used, it is replaced by "sssd", which is the best option in this case.
    if [[ $CURRENT_PROFILE == local ]]; then
        CURRENT_PROFILE="sssd"
    fi
    authselect create-profile hardening -b $CURRENT_PROFILE
    CURRENT_PROFILE="custom/hardening"
    {{{ bash_apply_authselect_changes('before-hardening-custom-profile') | indent(4) }}}
    authselect select $CURRENT_PROFILE
    for feature in $ENABLED_FEATURES; do
        authselect enable-feature $feature;
    done
    {{{ bash_apply_authselect_changes('after-hardening-custom-profile') | indent(4) }}}
fi
{{%- endmacro %}}


{{#
    Make sure that an existing PAM module line is properly configured, in aligment to the current
    system configuration. This macro is compatible with custom authselect profiles if the system
    relies on authselect. Otherwise, the PAM files will be directly edited.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option. Optional parameter.
:type option: str
:param value:           PAM module option argument, if is case. Optional parameter.
:type value: str
:param after_match:     Regex used as reference to include the PAM line below, if necessary. Optional parameter.
:type after_match: str

#}}
{{%- macro bash_ensure_pam_module_configuration(pam_file, group, control, module, option='', value='', after_match='') -%}}
if [ -e "{{{ pam_file }}}" ] ; then
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{%- if option == '' %}}
    {{{ bash_ensure_pam_module_line("$PAM_FILE_PATH", group, control, module, after_match) }}}
    {{%- else %}}
    {{{ bash_ensure_pam_module_option("$PAM_FILE_PATH", group, control, module, option, value, after_match) | indent(8) }}}
    {{%- endif %}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
else
    echo "{{{ pam_file }}} was not found" >&2
fi
{{%- endmacro -%}}


{{#
    Remove a PAM module option from an existing PAM module line. This macro is compatible with
    custom authselect profiles if the system relies on authselect. Otherwise, the PAM files will
    be directly edited.

:param pam_file:        PAM config file.
:type pam_file: str
:param group:           PAM management group: auth, account, password or session. Also known as "type".
:type group: str
:param control:         PAM control flags. Optional parameter, but recommended to be informed whenever possible.
:type control: str
:param module:          PAM module name.
:type module: str
:param option:          PAM module option.
:type option: str

#}}
{{%- macro bash_remove_pam_module_option_configuration(pam_file, group, control, module, option) -%}}
if [ -e "{{{ pam_file }}}" ] ; then
    PAM_FILE_PATH="{{{ pam_file }}}"
    if [ -f /usr/bin/authselect ]; then
        {{# the following macro updates the PAM_FILE_PATH variable in aligment to the authselect profile #}}
        {{{ bash_ensure_pam_variables_and_authselect_profile(pam_file) | indent(8) }}}
    fi
    {{{ bash_remove_pam_module_option("$PAM_FILE_PATH", group, control, module, option) }}}
    if [ -f /usr/bin/authselect ]; then
        {{{ bash_apply_authselect_changes() | indent(8) }}}
    fi
else
    echo "{{{ pam_file }}} was not found" >&2
fi
{{%- endmacro -%}}


{{%- macro bash_mount_conditional(path) -%}}
'findmnt --kernel "{{{ path }}}" > /dev/null || findmnt --fstab "{{{ path }}}" > /dev/null'
{{%- endmacro -%}}


{{#
    Macro to insert script to find a Python interpreter on the target system.

#}}
{{% macro find_python() -%}}

declare __REMEDIATE_PYTHON
if [ -x /usr/bin/python ]; then
    __REMEDIATE_PYTHON=/usr/bin/python
elif [ -x /usr/bin/python3 ]; then
    __REMEDIATE_PYTHON=/usr/bin/python3
elif [ -x /usr/bin/python2 ]; then
    __REMEDIATE_PYTHON=/usr/bin/python2
else
    echo "Python required and no python interpreter found."
    exit 1
fi
{{%- endmacro %}}


{{#
    Macro to insert script to find Mozilla Firefox location on the target system.

#}}
{{% macro find_firefox() -%}}

declare __FIREFOX_DISTRIBUTION
if find /usr -iname firefox\* -type f -print | grep -qe "firefox.sh$\|firefox-bin$"; then
   __FIREFOX_DISTRIBUTION=$(dirname "$(find /usr -iname firefox\* -type f -print | grep -e "firefox.sh$\|firefox-bin$" | head -n1)")/distribution
fi
{{%- endmacro %}}


{{#
This macro creates a Bash conditional which is used to determine if a
remediation is applicable. The condition compares the actual version of the
operating system with the expected version using the given operator. The macro
takes the operating system name ID as an argument. If the operating system
conforms and satisfies the optional version restricion, the Bash remediation
will be applied.

:param os_id: OS name, value of the ID variable in /etc/os-release
:type os_id: str
:param expected_ver: expected OS version, value of the VERSION_ID variable in /etc/os-release
            (optional argument, use together with "op")
:type expected_ver: str
:param op: version comparison operator (optional argument, "<", "<=", "==", "!=", ">", ">=")
:type op: str
:param os_release_path: path to the os-release file, default: "/etc/os-release"
:type os_release_path: str

#}}
{{%- macro bash_os_linux_conditional(os_id, expected_ver=None, op=None, os_release_path="/etc/os-release") -%}}
{{%- if expected_ver -%}}
grep -qP "^ID=[\"']?{{{ os_id }}}[\"']?$" "{{{ os_release_path }}}" && {{{ bash_compare_version_os_linux(expected_ver, op, os_release_path) }}}
{{%- else -%}}
grep -qP "^ID=[\"']?{{{ os_id }}}[\"']?$" "{{{ os_release_path }}}"
{{%- endif -%}}
{{%- endmacro %}}


{{#
This macro generates bash condition that compares the actual version of the
operating system with the expected version using the given operator.

:param expected: expected OS version, value of the VERSION_ID variable in /etc/os-release
:type expected: str
:param op: version comparison operator ("<", "<=", "==", "!=", ">", ">=")
:type op: str
:param os_release_path: path to the os-release file, default: "/etc/os-release"
:type os_release_path: str

#}}
{{%- macro bash_compare_version_os_linux(expected, op, os_release_path="/etc/os-release") -%}}
{ real="$({{{ bash_get_version_os_linux(os_release_path) }}})"; expected="{{{ expected }}}"; {{{ bash_compare_version("$real", op, "$expected") }}}; }
{{%- endmacro -%}}


{{#
This macro generates code that retrieves the operating system version
from /etc/os-release from VERSION_ID variable.

:param os_release_path: path to the os-release file, default: "/etc/os-release"
:type os_release_path: str

#}}
{{%- macro bash_get_version_os_linux(os_release_path="/etc/os-release") -%}}
grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" {{{ os_release_path }}} | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/"
{{%- endmacro -%}}


{{#
Remove all interactive users (UID >= uid_min) from /etc/passwd
#}}
{{%- macro bash_remove_interactive_users_from_passwd_by_uid() -%}}
# remove all interactive users (UID >= {{{ uid_min }}}) from /etc/passwd
del=""
while read -r user; do
    del+="/^${user}:/d;"
done < <(awk -F: '($3 >= {{{ uid_min }}}) { print $1 }' /etc/passwd)
sed -i "${del}" /etc/passwd
{{%- endmacro -%}}

{{#
Macro for enabling dconf user profile in /etc/dconf/profile/<PROFILE>

The macro adds the following lines to the profile:
---
user-db:user
system-db:<DATABASE>
---
If the profile exists but does not contain the above lines, the
lines will be inserted at the beginning of the profile.

:param profile: name of dconf profile (e.g. user, gdm)
:type profile: str
:param database: name of dconf database (e.g. local, gdm)
:type database: str
#}}
{{% macro bash_enable_dconf_user_profile(profile, database) -%}}

mkdir -p /etc/dconf/profile
dconf_profile_path=/etc/dconf/profile/{{{ profile }}}

[[ -s "${dconf_profile_path}" ]] || echo > "${dconf_profile_path}"

if ! grep -Pzq "(?s)^\s*user-db:user.*\n\s*system-db:{{{ database }}}" "${dconf_profile_path}"; then
    sed -i --follow-symlinks "1s/^/user-db:user\nsystem-db:{{{ database }}}\n/" "${dconf_profile_path}"
fi

# Make sure the corresponding directories exist
mkdir -p /etc/dconf/db/{{{ database }}}.d

# Make sure permissions allow regular users to read dconf settings.
# Also define the umask to avoid `dconf update` changing permissions.
chmod -R u=rwX,go=rX /etc/dconf/profile
(umask 0022 && dconf update)
{{%- endmacro -%}}

{{#
This macro defines a conditional expression that is evaluated as true
if the remediation is performed during a build of a bootable container image.
#}}
{{%- macro bash_bootc_build() -%}}
[[ "$OSCAP_BOOTC_BUILD" == "YES" ]]
{{%- endmacro -%}}

{{#
This macro defines a conditional expression that is evaluated as true
if the remediation is not performed during a build of a bootable container image.
#}}
{{%- macro bash_not_bootc_build() -%}}
[[ "$OSCAP_BOOTC_BUILD" != "YES" ]]
{{%- endmacro -%}}


{{#
This macro creates a Bash conditional which checks the system architecture in /proc/sys/kernel/{osrelease,arch}

  :param arch: system architecture (x86_64, aarch64, s90x, ppc64le, ...)
  :type arch: str
#}}
{{%- macro bash_arch_conditional(arch) -%}}
( grep -sqE "^.*\.{{{ arch }}}$" /proc/sys/kernel/osrelease || grep -sqE "^{{{ arch }}}$" /proc/sys/kernel/arch; )
{{%- endmacro -%}}