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
|
{{#
Pass strings that correspond to XCCDF value names as arguments to this macro::
ansible_instantiate_variables("varname1", "varname2")
Then, assume that the task that follows can work with the variable by referencing it, e.g.
value: :code:`Setting={{ varname1 }}`
#}}
{{%- macro ansible_instantiate_variables() -%}}
{{%- for name in varargs -%}}
- (xccdf-var {{{ name }}})
{{% endfor -%}}
{{%- endmacro -%}}
{{#
A wrapper over the Ansible lineinfile module. This handles the most common
options for us. regex is optional and when blank, it won't be included in
the Ansible script; this allows arbitrary additions to files. new_line will
only be passed when state is present. with_items will be specified only if
non-empty, allowing for iterating through a variable of content (with the
appropriate macro-based path). register will be specified only if non-empty,
allowing for saving the output of this lineinfile module. check_mode allows
an idempotent way to gather output, or run a task without changes. Useful when
calling the ansible_only_lineinfile macro to handle deduplication of values.
Note that all string-like parameters are single quoted in the YAML.
#}}
{{%- macro ansible_lineinfile(msg='', path='', mode='', regex='', insensitive='false', new_line='', create='no', state='present', with_items='', register='', when='', validate='', insert_after='', insert_before='', check_mode=False) -%}}
- name: "{{{ msg or rule_title }}}"
lineinfile:
path: '{{{ path }}}'
create: {{{ create }}}
{{%- if regex and insensitive %}}
regexp: '(?i){{{ regex }}}'
{{%- else %}}
regexp: '{{{ regex }}}'
{{%- endif %}}
{{%- if mode %}}
mode: '{{{ mode }}}'
{{%- endif %}}
{{%- if state == 'present' %}}
line: '{{{ new_line }}}'
state: present
{{%- if insert_after %}}
insertafter: '{{{ insert_after }}}'
{{%- elif insert_before %}}
insertbefore: '{{{ insert_before }}}'
{{%- endif %}}
{{%- else %}}
state: '{{{ state }}}'
{{%- endif %}}
{{%- if validate %}}
validate: '{{{ validate }}}'
{{%- endif %}}
{{%- if with_items %}}
with_items: '{{{ with_items }}}'
{{%- endif %}}
{{%- if check_mode %}}
check_mode: yes
changed_when: no
{{%- endif %}}
{{%- if register %}}
register: '{{{ register }}}'
{{%- endif %}}
{{%- if when %}}
when: '{{{ when }}}'
{{%- endif %}}
{{%- endmacro %}}
{{#
Check the file system status of an object. Not a full implementation.
:parameter msg: Optional task title
:type msg: str
:parameter path: Path to file
:type path: str
:parameter register: variable to register
:type register: str
#}}
{{%- macro ansible_stat(msg='', path='', register='') %}}
- name: '{{{ msg or rule_title }}}'
stat:
path: '{{{ path }}}'
{{%- if register %}}
register: '{{{ register }}}'
{{%- endif %}}
{{%- endmacro %}}
{{#
Find files matching a particular value. Not a full implementation.
#}}
{{%- macro ansible_find(msg='', paths='', recurse='yes', follow='no', contains='', register='', when='') %}}
- name: '{{{ msg or rule_title }}}'
find:
paths: '{{{ paths }}}'
recurse: '{{{ recurse }}}'
follow: '{{{ follow }}}'
{{%- if contains %}}
contains: '{{{ contains }}}'
{{%- endif %}}
{{%- if register %}}
register: '{{{ register }}}'
{{%- endif %}}
{{%- if when %}}
when: '{{{ when }}}'
{{%- endif %}}
{{%- endmacro %}}
{{#
A wrapper for adding one, unique line to a file. A regex must be specified
to tell if the line is unique. This is helpful in configuration files where
a single configuration parameter might have multiple values, but only one
value is approved. All lines matching the regex are first removed and then
the new line is appended to the file.
#}}
{{%- macro ansible_only_lineinfile(msg, path, line_regex, new_line, insensitive='false', create='no', block=False, validate='', insert_after='', insert_before='', mode='') -%}}
{{%- if block %}}
- name: "{{{ msg or rule_title }}}"
block:
{{{ ansible_lineinfile("Check for duplicate values", path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', register='dupes', check_mode=True)|indent }}}
{{{ ansible_lineinfile("Deduplicate values from " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', when='dupes.found is defined and dupes.found > 1')|indent }}}
{{{ ansible_lineinfile("Insert correct line to " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, new_line=new_line, create=create, state='present', validate=validate, insert_after=insert_after, insert_before=insert_before)|indent }}}
{{%- else %}}
{{{ ansible_lineinfile("Check for duplicate values", path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', register='dupes', check_mode=True) }}}
{{{ ansible_lineinfile("Deduplicate values from " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, create=create, state='absent', when='dupes.found is defined and dupes.found > 1') }}}
{{{ ansible_lineinfile("Insert correct line into " + path, path, mode=mode, regex=line_regex, insensitive=insensitive, new_line=new_line, create=create, state='present', validate=validate, insert_after=insert_after, insert_before=insert_before) }}}
{{%- endif %}}
{{%- endmacro %}}
{{#
Ensure the configuration is set in a file. Note this handles generic
key-seperator-value files with no sense of structure. In particular,
ini configuration files are best served with the ini Ansible module
instead of lineinfile-based solutions.
#}}
{{%- macro ansible_set_config_file(msg, file, parameter, separator=' ', separator_regex='\s+', value='', prefix_regex='^\s*', insensitive='false', create='no', validate='', insert_after='', insert_before='', mode='') %}}
{{{ ansible_only_lineinfile(msg, file, prefix_regex + parameter + separator_regex, parameter + separator + value, insensitive=insensitive, create=create, block=True, validate=validate, insert_after=insert_after, insert_before=insert_before, mode=mode) }}}
{{%- endmacro %}}
{{#
Ensure the configuration is set in a file and not conflicted by a
configuration in a directory. Note this handles generic key-separator-value
files with no sense of structure. In particular, ini configuration files are
best served with the ini Ansible module instead of lineinfile-based
solutions.
#}}
{{%- macro ansible_set_config_file_dir(msg, config_file, config_dir, set_file, parameter, separator=' ', separator_regex='\s+', value='', prefix_regex='^\s*', insensitive='false', create='no', validate='', insert_after='', insert_before='') %}}
{{%- set var_dir = config_dir | replace("/", "_") | replace("-", "_") | replace(".", "_") -%}}
{{%- set dir_exists = var_dir + "_exists" -%}}
{{%- set dir_parameter = var_dir + "_has_parameter" -%}}
{{%- set line_regex = prefix_regex + "{{ \"" + parameter + "\"| regex_escape }}" + separator_regex -%}}
{{%- set find_when = dir_exists + ".stat.isdir is defined and " + dir_exists + ".stat.isdir" -%}}
{{%- set lineinfile_items = "{{ " + dir_parameter + ".files }}" -%}}
{{%- set lineinfile_when = dir_parameter + ".matched" -%}}
{{%- set new_line = parameter + separator + value -%}}
- name: '{{{ msg or rule_title }}}'
block:
{{{ ansible_lineinfile("Deduplicate values from " + config_file, config_file, regex=line_regex, insensitive=insensitive, create='no', state='absent')|indent }}}
{{{ ansible_stat("Check if " + config_dir + " exists", path=config_dir, register=dir_exists)|indent }}}
{{{ ansible_find("Check if the parameter " + parameter + " is present in " + config_dir, paths=config_dir, contains=line_regex, register=dir_parameter, when=find_when)|indent }}}
{{{ ansible_lineinfile("Remove parameter from files in " + config_dir, path="{{ item.path }}", regex=line_regex, insensitive=insensitive, state="absent", with_items=lineinfile_items, when=lineinfile_when)|indent }}}
{{{ ansible_lineinfile("Insert correct line to " + set_file, set_file, regex=line_regex, insensitive=insensitive, new_line=new_line, create=create, state='present', validate=validate, insert_after=insert_after, insert_before=insert_before)|indent }}}
{{%- endmacro %}}
{{#
High level macro to set a value in the ssh daemon configuration file.
We specify a case insensitive comparison in the prefix since this is
used to deduplicate since sshd_config has case-insensitive parameters
(but case-sensitive values). We also specify the validation program here;
-t specifies test and -f allows Ansible to pass a file at a different path.
Set set a parameter in /etc/sshd_config or /etc/ssh/sshd_config.d/
:parameter msg: Message to be set as Task Title, if not set the rule's title will be used instead
:type msg: str
: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 ansible_sshd_set(msg='', parameter='', value='', config_is_distributed="false", config_basename="00-complianceascode-hardening.conf") %}}
{{%- if config_is_distributed == "true" %}}
{{% set config_dir = "/etc/ssh/sshd_config.d" %}}
{{% set config_file = "/etc/ssh/sshd_config.d" ~ "/" ~ config_basename %}}
{{{ ansible_set_config_file_dir(msg, config_file="/etc/ssh/sshd_config", config_dir=config_dir, set_file=config_file, parameter=parameter, separator_regex="\s+", value=value, prefix_regex="(?i)^\s*", create='yes', validate='/usr/sbin/sshd -t -f %s', insert_after='', insert_before="BOF") }}}
- name: {{{ rule_title }}} - set file mode for {{{ config_file }}}
ansible.builtin.file:
path: {{{ config_file }}}
mode: '0600'
{{%- else %}}
{{% if product in ["ol8", "ol9"] %}}
- name: "Find sshd_config included files"
shell: |-
included_files=$(grep -oP "^\s*(?i)include.*" /etc/ssh/sshd_config | sed -e 's/\s*Include\s*//i' | sed -e 's|^[^/]|/etc/ssh/&|')
[[ -n $included_files ]] && ls $included_files || true
register: sshd_config_included_files
- name: "Comment conf from included files"
replace:
path: '{{ item }}'
regexp: '^(\s*{{{ parameter }}}.*)$'
replace: '# \1'
loop: "{{ sshd_config_included_files.stdout_lines }}"
{{% endif %}}
{{{ ansible_set_config_file(msg, "/etc/ssh/sshd_config", parameter, value=value, create="yes", prefix_regex='(?i)^\s*', validate="/usr/sbin/sshd -t -f %s", insert_before="BOF") }}}
{{%- endif %}}
{{%- endmacro %}}
{{#
High level macro to set a value in a shell-related file that contains var assignments.
We also specify the validation program here; see
bash -c "help set" | grep -e -n
:param msg: The name for the Ansible task
:type msg: str
:param path: to the file
:type path: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: value of the parameter
:type value: str
#}}
{{%- macro ansible_shell_set(msg, path, parameter, value='', no_quotes=false) %}}
{{% if no_quotes -%}}
{{%- else -%}}
{{# Use the double quotes in all cases, as the underlying macro single-quotes the assignment line. #}}
{{% set value = '"%s"' % value %}}
{{%- endif -%}}
{{{ ansible_set_config_file(msg, path, parameter, separator="=", separator_regex="=", value=value, create="yes", prefix_regex='^\s*', validate="/usr/bin/bash -n %s", insert_before="^# " ~ parameter) }}}
{{%- endmacro %}}
{{#
High level macro to set a command in tmux configuration file /etc/tmux.conf.
Automatically adds "set -g " before the parameter.
:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str
#}}
{{%- macro ansible_tmux_set(msg='', parameter='', value='') %}}
{{{ ansible_set_config_file(msg, "/etc/tmux.conf", "set -g " + parameter, value=value, create="yes", mode="0644") }}}
{{%- endmacro %}}
{{#
High level macro to set a command in auditd configuration file /etc/audit/auditd.conf.
:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str
#}}
{{%- macro ansible_auditd_set(msg='', parameter='', value='') %}}
{{{ ansible_set_config_file(msg, "/etc/audit/auditd.conf", parameter=parameter, value=value, create="yes", prefix_regex='(?i)^\s*', separator=" = ", separator_regex="\s*=\s*") }}}
{{%- endmacro %}}
{{#
High level macro to set a parameter in /etc/systemd/coredump.conf.
For SLE platforms put remediation in drop-in configuration file /etc/systemd/coredump.conf.d/oscap-autoremedy.conf.
:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str
#}}
{{%- macro ansible_coredump_config_set(msg='', parameter='', value='') %}}
{{% if 'sle' in product %}}
{{% set file = '/etc/systemd/coredump.conf.d/oscap-autoremedy.conf' %}}
{{% else %}}
{{% set file = '/etc/systemd/coredump.conf' %}}
{{% endif %}}
{{{ ansible_ini_file_set(file, "Coredump", parameter, value) }}}
{{%- endmacro %}}
{{#
High level macro to set a parameter in /etc/selinux/config.
:param msg: The name for the Ansible task
:type msg: str
:param parameter: Parameter to be set in the configuration file
:type parameter: str
:param value: Value of the parameter
:type value: str
#}}
{{%- macro ansible_selinux_config_set(msg='', parameter='', value='') %}}
{{{ ansible_set_config_file(msg, "/etc/selinux/config", parameter=parameter, value=value, create="yes", separator="=", separator_regex="=", prefix_regex='^') }}}
{{%- endmacro %}}
{{#
Generates an Ansible task 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 ansible_file_contents(filepath='', contents='') %}}
- name: "Put contents into {{{ filepath }}} according to policy"
copy:
dest: "{{{ filepath }}}"
content: |+
{{{ contents|indent(8) }}}
force: yes
{{%- endmacro %}}
{{#
Formats a banner regex for use in :code:`/etc/issue`, :code:`/etc/issue.net` or :code:`/etc/motd`
:param banner_var_name: name of ansible variable with the banner regex
:type banner_var_name: str
#}}
{{% macro ansible_deregexify_banner_etc_issue(banner_var_name) -%}}
{{ {{{ banner_var_name }}} |
{{{ ansible_deregexify_banner_anchors() }}} |
{{{ ansible_deregexify_multiple_banners() }}} |
{{{ ansible_deregexify_banner_space() }}} |
{{{ ansible_deregexify_banner_newline("\\n") }}} |
{{{ ansible_deregexify_banner_backslash() }}} |
wordwrap() }}
{{%- endmacro %}}
{{#
Formats a banner regex for use in dconf
:param banner_var_name: name of ansible variable with the banner regex
:type banner_var_name: str
#}}
{{% macro ansible_deregexify_banner_dconf_gnome(banner_var_name) -%}}
''{{ {{{ banner_var_name }}} |
{{{ ansible_deregexify_banner_anchors() }}} |
{{{ ansible_deregexify_multiple_banners() }}} |
{{{ ansible_deregexify_banner_space() }}} |
{{{ ansible_deregexify_banner_newline("(n)*") }}} |
{{{ ansible_deregexify_banner_backslash() }}} |
{{{ ansible_deregexify_banner_newline_token()}}} }}''
{{%- endmacro %}}
{{# Strips anchors around the banner #}}
{{% macro ansible_deregexify_banner_anchors() -%}}
regex_replace("^\^(.*)\$$", "\1")
{{%- endmacro %}}
{{# Strips multibanner regex and keeps only the first banner #}}
{{% macro ansible_deregexify_multiple_banners() -%}}
regex_replace("^\((.*\.)\|.*\)$", "\1")
{{%- endmacro %}}
{{# Strips whitespace or newline regex #}}
{{% macro ansible_deregexify_banner_space() -%}}
regex_replace("\[\\s\\n\]\+"," ")
{{%- endmacro %}}
{{# Strips newline or newline escape sequence regex #}}
{{% macro ansible_deregexify_banner_newline(newline) -%}}
regex_replace("\(\?:\[\\n\]\+\|\(\?:\\\\n\)\+\)", "{{{ newline }}}")
{{%- endmacro %}}
{{# Strips newline token for a newline escape sequence regex #}}
{{% macro ansible_deregexify_banner_newline_token() -%}}
regex_replace("\(n\)\*", "\\n")
{{%- endmacro %}}
{{# Strips backslash regex #}}
{{% macro ansible_deregexify_banner_backslash() -%}}
regex_replace("\\", "")
{{%- endmacro %}}
{{#
The following macro remediates one audit watch rule in :code:`/etc/audit/rules.d` directory.
:param path: path to watch
:type path: str
:param permissions: permissions changes to watch for
:type permissions: str
:param key: key to use as identifier. Note that if there exists any other rule with the same find_mac_key in some file within :code:`/etc/audit/rules.d/`, the new rule will be appended to this file.
:type key: str
#}}
{{% macro ansible_audit_augenrules_add_watch_rule(path='', permissions='', key='') -%}}
- name: Check if watch rule for {{{ path }}} already exists in /etc/audit/rules.d/
find:
paths: "/etc/audit/rules.d"
contains: '^\s*-w\s+{{{ path }}}\s+-p\s+{{{ permissions }}}(\s|$)+'
patterns: "*.rules"
register: find_existing_watch_rules_d
- name: Search /etc/audit/rules.d for other rules with specified key {{{ key }}}
find:
paths: "/etc/audit/rules.d"
contains: '^.*(?:-F key=|-k\s+){{{ key }}}$'
patterns: "*.rules"
register: find_watch_key
when: find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0
- name: Use /etc/audit/rules.d/{{{ key }}}.rules as the recipient for the rule
set_fact:
all_files:
- /etc/audit/rules.d/{{{ key }}}.rules
when: find_watch_key.matched is defined and find_watch_key.matched == 0 and find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0
- name: Use matched file as the recipient for the rule
set_fact:
all_files:
- "{{ find_watch_key.files | map(attribute='path') | list | first }}"
when: find_watch_key.matched is defined and find_watch_key.matched > 0 and find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0
- name: Add watch rule for {{{ path }}} in /etc/audit/rules.d/
lineinfile:
path: "{{ all_files[0] }}"
line: "-w {{{ path }}} -p {{{ permissions }}} -k {{{ key }}}"
create: yes
mode: '0600'
when: find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched == 0
{{%- endmacro %}}
{{#
The following macro remediates one audit watch rule in :code:`/etc/audit/audit.rules`.
:param path: Path to watch
:type path: str
:param permissions: Permissions changes to watch for
:type permissions: str
:param key: Key to use as identifier
:type key: str
#}}
{{% macro ansible_audit_auditctl_add_watch_rule(path='', permissions='', key='') -%}}
- name: Check if watch rule for {{{ path }}} already exists in /etc/audit/audit.rules
find:
paths: "/etc/audit/"
contains: '^\s*-w\s+{{{ path }}}\s+-p\s+{{{ permissions }}}(\s|$)+'
patterns: "audit.rules"
register: find_existing_watch_audit_rules
- name: Add watch rule for {{{ path }}} in /etc/audit/audit.rules
lineinfile:
line: "-w {{{ path }}} -p {{{ permissions }}} -k {{{ key }}}"
state: present
dest: /etc/audit/audit.rules
create: yes
mode: '0600'
when: find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched == 0
{{%- endmacro %}}
{{#
The following macro remediates Audit syscall rule in :code:`/etc/audit/rules.d` directory.
The macro requires following parameters:
: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 syscalls: List of syscalls to ensure presense among audit rules. For example, "['fchown', 'lchown', 'fchownat']"
:type syscalls: list[str]
:param syscall_grouping: List of other syscalls that can be grouped with 'syscalls'. For example, "['fchown', 'lchown', 'fchownat']"
:type syscall_grouping: list[str]
:param key: The key to use when appending a new rule
:type key: str
#}}
{{% macro ansible_audit_augenrules_add_syscall_rule(action_arch_filters="", other_filters="", auid_filters="", syscalls=[], key="", syscall_grouping=[]) -%}}
{{% if other_filters != "" %}}
{{% set other_filters = " " ~ other_filters %}}
{{% endif %}}
{{% if auid_filters != "" %}}
{{% set auid_filters = " " ~ auid_filters %}}
{{% endif %}}
{{% if syscalls == [] %}}
{{% set syscall_flag = "" %}}
{{% else %}}
{{% set syscall_flag = " -S " %}}
{{% endif %}}
- name: Declare list of syscalls
set_fact:
syscalls: {{{ syscalls }}}
syscall_grouping: {{{ syscall_grouping }}}
- name: Check existence of {{{ syscalls | join(", ") }}} in /etc/audit/rules.d/
find:
paths: /etc/audit/rules.d
contains: '{{{ action_arch_filters }}}(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)*{{{ other_filters }}}{{{ auid_filters }}} (-k\s+|-F\s+key=)\S+\s*$'
patterns: '*.rules'
register: find_command
loop: '{{ (syscall_grouping + syscalls) | unique }}'
- name: Reset syscalls found per file
set_fact:
syscalls_per_file: {}
found_paths_dict: {}
- name: Declare syscalls found per file
set_fact: syscalls_per_file="{{ syscalls_per_file | combine( {item.files[0].path :[item.item] + syscalls_per_file.get(item.files[0].path, []) } ) }}"
loop: "{{ find_command.results | selectattr('matched') | list }}"
- name: Declare files where syscalls were found
set_fact: found_paths="{{ find_command.results | map(attribute='files') | flatten | map(attribute='path') | list }}"
- name: Count occurrences of syscalls in paths
set_fact: found_paths_dict="{{ found_paths_dict | combine({ item:1+found_paths_dict.get(item, 0) }) }}"
loop: "{{ find_command.results | map(attribute='files') | flatten | map(attribute='path') | list }}"
- name: Get path with most syscalls
set_fact: audit_file="{{ (found_paths_dict | dict2items() | sort(attribute='value') | last).key }}"
when: found_paths | length >= 1
- name: No file with syscall found, set path to /etc/audit/rules.d/{{{ key }}}.rules
set_fact: audit_file="/etc/audit/rules.d/{{{ key }}}.rules"
when: found_paths | length == 0
- name: Declare found syscalls
set_fact: syscalls_found="{{ find_command.results | selectattr('matched') | map(attribute='item') | list }}"
- name: Declare missing syscalls
set_fact:
missing_syscalls="{{ syscalls | difference(syscalls_found) }}"
- name: Replace the audit rule in {{ audit_file }}
lineinfile:
path: '{{ audit_file }}'
regexp: '({{{ action_arch_filters }}})(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file] | join("|") }}))\b)((?:( -S |,)\w+)+)({{{ other_filters }}}{{{ auid_filters }}} (?:-k |-F key=)\w+)'
line: '\1\2\3{{ missing_syscalls | join("\3") }}\4'
backrefs: yes
state: present
mode: g-rwx,o-rwx
when: syscalls_found | length > 0 and missing_syscalls | length > 0
- name: Add the audit rule to {{ audit_file }}
lineinfile:
path: '{{ audit_file }}'
line: "{{{ action_arch_filters }}}{{{ syscall_flag }}}{{ syscalls | join(',') }}{{{ other_filters }}}{{{ auid_filters}}} -F key={{{ key }}}"
create: true
mode: g-rwx,o-rwx
state: present
when: syscalls_found | length == 0
{{%- endmacro %}}
{{#
The following macro remediates Audit syscall rule in :code:`/etc/audit/audit.rules` file.
: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 syscalls: List of syscalls to ensure presense among audit rules.
For example, "['fchown', 'lchown', 'fchownat']"
:type syscalls: list[str]
:param key: The key to use when appending a new rule
:type key: str
:param syscall_grouping: List of other syscalls that can be grouped with
'syscalls'. For example, "['fchown', 'lchown', 'fchownat']"
:type syscall_grouping: list[str]
#}}
{{% macro ansible_audit_auditctl_add_syscall_rule(action_arch_filters="", other_filters="", auid_filters="", syscalls=[], key="", syscall_grouping=[]) -%}}
{{% if other_filters!= "" %}}
{{% set other_filters = " " ~ other_filters %}}
{{% endif %}}
{{% if auid_filters!= "" %}}
{{% set auid_filters = " " ~ auid_filters %}}
{{% endif %}}
{{% if syscalls == [] %}}
{{% set syscall_flag = "" %}}
{{% else %}}
{{% set syscall_flag = " -S " %}}
{{% endif %}}
- name: Declare list of syscalls
set_fact:
syscalls: {{{ syscalls }}}
syscall_grouping: {{{ syscall_grouping }}}
- name: Check existence of {{{ syscalls | join(", ") }}} in /etc/audit/audit.rules
find:
paths: /etc/audit
contains: '{{{ action_arch_filters }}}(( -S |,)\w+)*(( -S |,){{ item }})+(( -S |,)\w+)*{{{ other_filters }}}{{{ auid_filters }}} (-k\s+|-F\s+key=)\S+\s*$'
patterns: 'audit.rules'
register: find_command
loop: '{{ (syscall_grouping + syscalls) | unique }}'
- name: Set path to /etc/audit/audit.rules
set_fact: audit_file="/etc/audit/audit.rules"
- name: Declare found syscalls
set_fact: syscalls_found="{{ find_command.results | selectattr('matched') | map(attribute='item') | list }}"
- name: Declare missing syscalls
set_fact:
missing_syscalls="{{ syscalls | difference(syscalls_found) }}"
- name: Replace the audit rule in {{ audit_file }}
lineinfile:
path: '{{ audit_file }}'
regexp: '({{{ action_arch_filters }}})(?=.*(?:(?:-S |,)(?:{{ syscalls_found | join("|") }}))\b)((?:( -S |,)\w+)+)({{{ other_filters }}}{{{ auid_filters }}} (?:-k |-F key=)\w+)'
line: '\1\2\3{{ missing_syscalls | join("\3") }}\4'
backrefs: yes
state: present
mode: g-rwx,o-rwx
when: syscalls_found | length > 0 and missing_syscalls | length > 0
- name: Add the audit rule to {{ audit_file }}
lineinfile:
path: '{{ audit_file }}'
line: "{{{ action_arch_filters }}}{{{ syscall_flag }}}{{ syscalls | join(',') }}{{{ other_filters }}}{{{ auid_filters}}} -F key={{{ key }}}"
create: true
mode: g-rwx,o-rwx
state: present
when: syscalls_found | length == 0
{{%- endmacro %}}
{{% macro ansible_sssd_ldap_config(parameter, value) -%}}
- name: "Test for id_provider different than Active Directory (ad)"
command: grep -qzosP '[[:space:]]*\[domain\/[^]]*]([^(\n)]*(\n)+)+?[[:space:]]*id_provider[[:space:]]*=[[:space:]]*((?i)ad)[[:space:]]*$' /etc/sssd/sssd.conf
register: test_id_provider
failed_when: false
changed_when: false
check_mode: no
- name: "Test for domain group"
command: grep '\s*\[domain\/[^]]*]' /etc/sssd/sssd.conf
register: test_grep_domain
failed_when: false
changed_when: false
check_mode: no
- name: "Add default domain group and set {{{ parameter }}} in sssd configuration (if no domain there)"
ini_file:
path: /etc/sssd/sssd.conf
section: "{{ item.section }}"
option: "{{ item.option }}"
value: "{{ item.value }}"
mode: 0600
with_items:
- { section: sssd, option: domains, value: default}
- { section: domain/default, option: {{{ parameter }}}, value: "{{{ value }}}"}
when:
- test_grep_domain.stdout is defined
- test_grep_domain.stdout | length < 1
- test_id_provider.stdout is defined
- test_id_provider.stdout | length < 1
- name: "Set {{{ parameter }}} in sssd configuration"
ini_file:
path: /etc/sssd/sssd.conf
section: "{{ test_grep_domain.stdout | regex_replace('\\[(.*)\\]','\\1') }}"
option: {{{ parameter }}}
value: "{{{ value }}}"
mode: 0600
when:
- test_grep_domain.stdout is defined
- test_grep_domain.stdout | length > 0
- test_id_provider.stdout is defined
- test_id_provider.stdout | length < 1
- name: Find all the conf files inside /etc/sssd/conf.d/
find:
paths: "/etc/sssd/conf.d/"
patterns: "*.conf"
register: sssd_conf_d_files
- name: Set {{{ parameter }}} to {{{ value }}} in /etc/sssd/conf.d/ if exists
ansible.builtin.replace:
path: "{{ item.path }}"
regexp: '[^#]*{{{ parameter }}}.*'
replace: '{{{ parameter }}} = {{{ value }}}'
with_items: "{{ sssd_conf_d_files.files }}"
{{%- endmacro %}}
{{% macro ansible_ini_file_set(filename, section, key, value, description="", no_extra_spaces=False) -%}}
- name: "{{{ description if description else ("Set '" + key + "' to '" + value + "' in the [" + section + "] section of '" + filename + "'") }}}"
ini_file:
path: "{{{ filename }}}"
section: "{{{ section }}}"
option: "{{{ key }}}"
value: "{{{ value }}}"
create: yes
mode: 0644
{{% if no_extra_spaces %}}
no_extra_spaces: true
{{% endif %}}
{{%- endmacro %}}
{{#
This macro comments out a given line of the sudoers and then validates it before saving.
:param parameter: The parameter to remove
:type parameter: str
:param pattern: The pattern to remove
:type pattern: str
#}}
{{%- macro ansible_sudo_remove_config(parameter, pattern) -%}}
- name: Find /etc/sudoers.d/ files
ansible.builtin.find:
paths:
- /etc/sudoers.d/
register: sudoers
- name: "Remove lines containing {{{ parameter }}} from sudoers files"
ansible.builtin.replace:
regexp: '(^(?!#).*[\s]+{{{ pattern }}}.*$)'
replace: '# \g<1>'
path: "{{ item.path }}"
validate: /usr/sbin/visudo -cf %s
with_items:
- { path: /etc/sudoers }
- "{{ sudoers.files }}"
{{%- endmacro -%}}
{{#
This macro creates an Ansible snipped which is used in `when` clause to
determine applicability of a task. If the package passed as a parameter is
installed, the task is applicable. The macro respects
`platform_package_overrides` variable.
: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 ansible_pkg_conditional(package, op=None, ver=None) -%}}
{{%- if package in platform_package_overrides -%}}
{{%- set package = platform_package_overrides[package] -%}}
{{%- endif -%}}
{{%- if ver -%}}
{{# For RPM packages, Ansible splits the package version into "epoch", "version" and "release" keys. For DEB packages, Ansible provides only "version" key. We don't take the "release" part into account. #}}
{{%- if pkg_system == "rpm" -%}}
"{{{ package }}}" in ansible_facts.packages and (((((ansible_facts.packages["{{{ package }}}"] | last)["epoch"]) != None) | ternary((ansible_facts.packages["{{{ package }}}"] | last)["epoch"] ~ ":", "0:")) + ((ansible_facts.packages["{{{ package }}}"] | last)["version"] | split("-") | first)) is version("{{{ ver }}}", "{{{ op }}}")
{{%- else -%}}
"{{{ package }}}" in ansible_facts.packages and ((ansible_facts.packages["{{{ package }}}"] | last)["version"] | split("-") | first) is version("{{{ ver }}}", "{{{ op }}}")
{{%- endif -%}}
{{%- else -%}}
"{{{ package }}}" in ansible_facts.packages
{{%- endif -%}}
{{%- 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 ansible_check_authselect_integrity() -%}}
- name: '{{{ rule_title }}} - Check integrity of authselect current profile'
ansible.builtin.command:
cmd: authselect check
register: result_authselect_check_cmd
changed_when: false
failed_when: false
- name: '{{{ rule_title }}} - Informative message based on the authselect integrity check result'
ansible.builtin.assert:
that:
- result_authselect_check_cmd.rc == 0
fail_msg:
- 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.
success_msg:
- authselect integrity check passed
{{%- 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 ansible_apply_authselect_changes(backup_name='') -%}}
- name: '{{{ rule_title }}} - Ensure authselect changes are applied'
ansible.builtin.command:
{{%- if backup_name == '' %}}
cmd: authselect apply-changes -b
{{%- else %}}
cmd: authselect apply-changes -b --backup={{{ backup_name }}}
{{%- endif %}}
{{%- endmacro %}}
{{#
Macro used to apply changes on pam-auth-update profiles. If the "profile_name" parameter is not defined, the
pam-auth-update will apply all profile changes by default.
:param profile_name: Changes the default profile used by pam-auth-update.
:type profile_name: str
#}}
{{% macro ansible_apply_pam_auth_update_changes(profile_name='') -%}}
- name: '{{{ rule_title }}} - Ensure pam-auth-update profile changes are applied'
ansible.builtin.command:
{{%- if profile_name == '' %}}
cmd: pam-auth-update
{{%- else %}}
cmd: pam-auth-update --enable {{{ profile_name }}}
{{%- endif %}}
{{%- endmacro %}}
{{#
Disable authselect feature if the authselect current profile is intact or inform that its
integrity check failed.
#}}
{{%- macro ansible_disable_authselect_feature(feature) -%}}
{{{ ansible_check_authselect_integrity() }}}
- name: '{{{ rule_title }}} - Get authselect Features Currently Enabled'
ansible.builtin.shell:
cmd: authselect current | tail -n+3 | awk '{ print $2 }'
register: result_authselect_features
changed_when: false
when:
- result_authselect_check_cmd is success
- name: '{{{ rule_title }}} - Ensure "{{{ feature }}}" Feature is Disabled Using authselect Tool'
ansible.builtin.command:
cmd: authselect disable-feature {{{ feature }}}
register: result_authselect_disable_feature_cmd
when:
- result_authselect_check_cmd is success
- result_authselect_features.stdout is search("{{{ feature }}}")
{{{ ansible_apply_authselect_changes() }}}
when:
- result_authselect_disable_feature_cmd is not skipped
- result_authselect_disable_feature_cmd is success
{{%- endmacro -%}}
{{#
Enable authselect feature if the authselect current profile is intact or inform that its
integrity check failed.
#}}
{{%- macro ansible_enable_authselect_feature(feature) -%}}
{{{ ansible_check_authselect_integrity() }}}
- name: '{{{ rule_title }}} - Get authselect current features'
ansible.builtin.shell:
cmd: authselect current | tail -n+3 | awk '{ print $2 }'
register: result_authselect_features
changed_when: false
when:
- result_authselect_check_cmd is success
- name: '{{{ rule_title }}} - Ensure "{{{ feature }}}" feature is enabled using authselect tool'
ansible.builtin.command:
cmd: authselect enable-feature {{{ feature }}}
register: result_authselect_enable_feature_cmd
when:
- result_authselect_check_cmd is success
- result_authselect_features.stdout is not search("{{{ feature }}}")
{{{ ansible_apply_authselect_changes() }}}
when:
- result_authselect_enable_feature_cmd is not skipped
- result_authselect_enable_feature_cmd is success
{{%- endmacro -%}}
{{#
Used to identify if authselect is present or not in the system.
Some macros can change the remediation behavior based on the presence of authselect.
#}}
{{%- macro ansible_check_authselect_presence() -%}}
- name: '{{{ rule_title }}} - Check if system relies on authselect tool'
ansible.builtin.stat:
path: /usr/bin/authselect
register: result_authselect_present
{{%- endmacro -%}}
{{#
Used to identify if pam-auth-update is present or not in the system.
Some macros can change the remediation behavior based on the presence of authselect.
#}}
{{%- macro ansible_check_pam_auth_update_presence() -%}}
- name: '{{{ rule_title }}} - Check if system relies on pam-auth-update tool'
ansible.builtin.stat:
path: /usr/sbin/pam-auth-update
register: result_pam_auth_update_present
{{%- 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 ansible_pam_lastlog_enable_showfailed(pam_file, control, after_match='') -%}}
{{{ ansible_check_authselect_presence() }}}
- name: '{{{ rule_title }}} - Collect the Available authselect Features'
ansible.builtin.command:
cmd: authselect list-features sssd
register: result_authselect_available_features
changed_when: false
when:
- result_authselect_present.stat.exists
- name: '{{{ rule_title }}} - Configure pam_lastlog.so Using authselect Feature'
block:
{{{ ansible_disable_authselect_feature('with-silent-lastlog') | indent(4) }}}
when:
- result_authselect_present.stat.exists
- result_authselect_available_features.stdout is search("with-silent-lastlog")
- name: '{{{ rule_title }}} - Configure pam_lastlog.so in appropriate PAM files'
block:
{{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
{{{ ansible_ensure_pam_module_option('{{ pam_file_path }}', 'session', control, 'pam_lastlog.so', 'showfailed', '', after_match) | indent(4) }}}
{{{ ansible_remove_pam_module_option('{{ pam_file_path }}', 'session', control, 'pam_lastlog.so', 'silent') | indent(4) }}}
{{%- 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 ansible_pam_pwhistory_enable(pam_file, control, after_match='') -%}}
{{{ ansible_check_authselect_presence() }}}
- name: '{{{ rule_title }}} - Collect the available authselect features'
ansible.builtin.command:
cmd: authselect list-features sssd
register: result_authselect_available_features
changed_when: false
when:
- result_authselect_present.stat.exists
- name: '{{{ rule_title }}} - Enable pam_pwhistory.so using authselect feature'
block:
{{{ ansible_enable_authselect_feature('with-pwhistory') | indent(4) }}}
when:
- result_authselect_present.stat.exists
- result_authselect_available_features.stdout is search("with-pwhistory")
- name: '{{{ rule_title }}} - Enable pam_pwhistory.so in appropriate PAM files'
block:
{{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
{{{ ansible_ensure_pam_module_line('{{ pam_file_path }}', 'password', control, 'pam_pwhistory.so', after_match) | indent(4) }}}
when: >
(result_authselect_available_features.stdout is defined and result_authselect_available_features.stdout is not search("with-pwhistory"))
or result_authselect_available_features is not defined
{{%- 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 parameter: pwhistory parameter/option e.g.: remember, retry, debug
:type parameter: str
:param pwhistory_var_name: Literal variable name.
:type pwhistory_var_name: str
#}}
{{%- macro ansible_pam_pwhistory_parameter_value(pam_file, parameter, pwhistory_var_name='') -%}}
- name: '{{{ rule_title }}} - Check the presence of /etc/security/pwhistory.conf file'
ansible.builtin.stat:
path: /etc/security/pwhistory.conf
register: result_pwhistory_conf_check
- name: '{{{ rule_title }}} - pam_pwhistory.so parameters are configured in /etc/security/pwhistory.conf file'
block:
- name: '{{{ rule_title }}} - Ensure the pam_pwhistory.so {{{ parameter }}} parameter in /etc/security/pwhistory.conf'
ansible.builtin.lineinfile:
path: /etc/security/pwhistory.conf
{{%- if pwhistory_var_name == '' %}}
regexp: ^\s*{{{ parameter }}}
line: {{{ parameter }}}
{{%- else %}}
regexp: ^\s*{{{ parameter }}}\s*=
line: {{{ parameter }}} = {{{ pwhistory_var_name }}}
{{%- endif %}}
state: present
- name: '{{{ rule_title }}} - Ensure the pam_pwhistory.so {{{ parameter }}} parameter is removed from PAM files'
block:
{{{ ansible_remove_pam_module_option_configuration(pam_file, 'password', '', 'pam_pwhistory.so', parameter) | indent(8) }}}
when:
- result_pwhistory_conf_check.stat.exists
- name: '{{{ rule_title }}} - pam_pwhistory.so parameters are configured in PAM files'
block:
{{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
{{{ ansible_ensure_pam_module_option('{{ pam_file_path }}', 'password', 'requisite', 'pam_pwhistory.so', parameter, pwhistory_var_name, '') | indent(4) }}}
{{{ ansible_apply_authselect_changes() | indent(4) }}}
when:
- result_authselect_present.stat.exists
- (result_pam_{{{ parameter }}}_add is defined and result_pam_{{{ parameter }}}_add.changed) or (result_pam_{{{ parameter }}}_edit is defined and result_pam_{{{ parameter }}}_edit.changed)
when:
- not result_pwhistory_conf_check.stat.exists
{{%- endmacro -%}}
{{#
This macro ensures the pam_faillock.so PAM module is enabled.
It is enabled using the authselect tool or editing the PAM files, only if authselect tool is not available.
#}}
{{%- macro ansible_pam_faillock_enable() -%}}
{{{ ansible_check_authselect_presence() }}}
- name: {{{ rule_title }}} - Remediation where authselect tool is present
block:
{{{ ansible_enable_authselect_feature('with-faillock') | indent(4) }}}
when:
- result_authselect_present.stat.exists
- name: {{{ rule_title }}} - Remediation where authselect tool is not present
block:
- name: {{{ rule_title }}} - Check if pam_faillock.so is already enabled
ansible.builtin.lineinfile:
path: /etc/pam.d/system-auth
regexp: .*auth.*pam_faillock\.so (preauth|authfail)
state: absent
check_mode: yes
changed_when: false
register: result_pam_faillock_is_enabled
- name: {{{ rule_title }}} - Enable pam_faillock.so preauth editing PAM files
ansible.builtin.lineinfile:
path: '{{ item }}'
line: auth required pam_faillock.so preauth
insertbefore: ^auth.*sufficient.*pam_unix\.so.*
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_is_enabled.found == 0
- name: {{{ rule_title }}} - Enable pam_faillock.so authfail editing PAM files
ansible.builtin.lineinfile:
path: '{{ item }}'
line: auth required pam_faillock.so authfail
insertbefore: ^auth.*required.*pam_deny\.so.*
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_is_enabled.found == 0
- name: {{{ rule_title }}} - Enable pam_faillock.so account section editing PAM files
ansible.builtin.lineinfile:
path: '{{ item }}'
line: account required pam_faillock.so
insertbefore: ^account.*required.*pam_unix\.so.*
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_is_enabled.found == 0
when:
- not result_authselect_present.stat.exists
{{%- endmacro -%}}
{{#
This macro make sure the informed parameter from pam_faillock.so PAM module is properly set. 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.
:param parameter: The pam_faillock.so parameter name.
:type parameter: str
:param faillock_var_name: If the parameter expects a value from a variable, the variable name is informed here.
:type faillock_var_name: str
:param authfail: check the pam_faillock.so conf line with authfail
:type authfail: bool
#}}
{{%- macro ansible_pam_faillock_parameter_value(parameter, faillock_var_name='', authfail=True) -%}}
{{%- if faillock_var_name != '' %}}
{{{ ansible_instantiate_variables( faillock_var_name ) }}}
{{%- endif %}}
- name: {{{ rule_title }}} - Check the presence of /etc/security/faillock.conf file
ansible.builtin.stat:
path: /etc/security/faillock.conf
register: result_faillock_conf_check
- name: {{{ rule_title }}} - Ensure the pam_faillock.so {{{ parameter }}} parameter in /etc/security/faillock.conf
ansible.builtin.lineinfile:
path: /etc/security/faillock.conf
{{%- if faillock_var_name == '' %}}
regexp: ^\s*{{{ parameter }}}
line: {{{ parameter }}}
{{%- else %}}
regexp: ^\s*{{{ parameter }}}\s*=
line: {{{ parameter }}} = {{ {{{ faillock_var_name }}} }}
{{%- endif %}}
state: present
when:
- result_faillock_conf_check.stat.exists
- name: {{{ rule_title }}} - Ensure the pam_faillock.so {{{ parameter }}} parameter not in PAM files
block:
{{{ ansible_remove_pam_module_option_configuration('/etc/pam.d/system-auth','auth','','pam_faillock.so',parameter) | indent(4) }}}
{{{ ansible_remove_pam_module_option_configuration('/etc/pam.d/password-auth','auth','','pam_faillock.so',parameter) | indent(4) }}}
when:
- result_faillock_conf_check.stat.exists
- name: {{{ rule_title }}} - Ensure the pam_faillock.so {{{ parameter }}} parameter in PAM files
block:
- name: {{{ rule_title }}} - Check if pam_faillock.so {{{ parameter }}} parameter is already enabled in pam files
ansible.builtin.lineinfile:
path: /etc/pam.d/system-auth
regexp: .*auth.*pam_faillock\.so (preauth|authfail).*{{{ parameter }}}
state: absent
check_mode: yes
changed_when: false
register: result_pam_faillock_{{{ parameter }}}_parameter_is_present
- name: {{{ rule_title }}} - Ensure the inclusion of pam_faillock.so preauth {{{ parameter }}} parameter in auth section
ansible.builtin.lineinfile:
path: "{{ item }}"
backrefs: true
regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)
{{%- if faillock_var_name == '' %}}
line: \1required\3 {{{ parameter }}}
{{%- else %}}
line: \1required\3 {{{ parameter }}}={{ {{{ faillock_var_name }}} }}
{{%- endif %}}
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_{{{ parameter }}}_parameter_is_present.found == 0
{{%- if authfail %}}
- name: {{{ rule_title }}} - Ensure the inclusion of pam_faillock.so authfail {{{ parameter }}} parameter in auth section
ansible.builtin.lineinfile:
path: "{{ item }}"
backrefs: true
regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)
{{%- if faillock_var_name == '' %}}
line: \1required\3 {{{ parameter }}}
{{%- else %}}
line: \1required\3 {{{ parameter }}}={{ {{{ faillock_var_name }}} }}
{{%- endif %}}
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_{{{ parameter }}}_parameter_is_present.found == 0
{{%- endif %}}
{{%- if faillock_var_name != '' %}}
- name: {{{ rule_title }}} - Ensure the desired value for pam_faillock.so preauth {{{ parameter }}} parameter in auth section
ansible.builtin.lineinfile:
path: "{{ item }}"
backrefs: true
regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so preauth.*)({{{ parameter }}})=[0-9]+(.*)
line: \1required\3\4={{ {{{ faillock_var_name }}} }}\5
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_{{{ parameter }}}_parameter_is_present.found > 0
{{%- if authfail %}}
- name: {{{ rule_title }}} - Ensure the desired value for pam_faillock.so authfail {{{ parameter }}} parameter in auth section
ansible.builtin.lineinfile:
path: "{{ item }}"
backrefs: true
regexp: (^\s*auth\s+)([\w\[].*\b)(\s+pam_faillock.so authfail.*)({{{ parameter }}})=[0-9]+(.*)
line: \1required\3\4={{ {{{ faillock_var_name }}} }}\5
state: present
loop:
- /etc/pam.d/system-auth
- /etc/pam.d/password-auth
when:
- result_pam_faillock_{{{ parameter }}}_parameter_is_present.found > 0
{{%- endif %}}
{{%- endif %}}
when:
- not result_faillock_conf_check.stat.exists
{{%- endmacro -%}}
{{#
This macro ensures the pam_pwquality.so PAM module is enabled.
It is enabled using the pam-auth-update tool.
:param path: The path of pam-auth-update configuration for pam_pwquality.so.
:type parameter: str
#}}
{{%- macro ansible_pam_pwquality_enable(path) -%}}
{{{ ansible_check_pam_auth_update_presence() }}}
- name: {{{ rule_title }}} - Remediation where pam-auth-update tool is present
block:
- name: Check if {{{ path }}} exists
stat:
path: {{{ path }}}
register: pwquality_file_stat
- name: Put the content into {{{ path }}} if it does not exist
copy:
dest: {{{ path }}}
content: |+
Name: Pwquality password strength checking
Default: yes
Priority: 1024
Conflicts: cracklib
Password-Type: Primary
Password:
requisite pam_pwquality.so retry=3
force: yes
when: not pwquality_file_stat.stat.exists
{{{ ansible_apply_pam_auth_update_changes('cac_pwquality') | indent(4) }}}
when:
- result_pam_auth_update_present.stat.exists
{{%- endmacro -%}}
{{#
Macro for Ansible 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 ansible_grub2_bootloader_argument(arg_name, arg_name_value) -%}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['ol7', 'sle12', 'sle15', 'slmicro5'] %}}
- name: Check {{{ arg_name }}} argument exists
command: grep '^\s*GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=' /etc/default/grub
failed_when: False
register: argcheck
- name: Check {{{ arg_name }}} argument exists
command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
failed_when: False
register: linecheck
- name: Add {{{ arg_name }}} argument
ansible.builtin.lineinfile:
line: 'GRUB_CMDLINE_LINUX="{{{ arg_name_value }}} "'
state: present
dest: /etc/default/grub
create: yes
mode: '0644'
when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc != 0
- name: Replace existing {{{ arg_name }}} argument
replace:
path: /etc/default/grub
regexp: '{{{ arg_name }}}=[a-zA-Z0-9,]+'
replace: '{{{ arg_name_value }}}'
when: argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and linecheck.rc == 0
- name: Add {{{ arg_name }}} argument
replace:
path: /etc/default/grub
regexp: '(^\s*GRUB_CMDLINE_LINUX=.*)"'
replace: '\1 {{{ arg_name_value }}}"'
when: argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and linecheck.rc == 0
{{% endif -%}}
{{% if product in ['sle12', 'sle15'] %}}
- name: Update grub defaults and the bootloader menu
command: /usr/sbin/grub2-mkconfig -o {{{ grub2_boot_path }}}/grub.cfg
{{% elif 'debian' in product %}}
- name: Update grub defaults and the bootloader menu
command: /usr/sbin/update-grub
{{% else %}}
- name: Update grub defaults and the bootloader menu
command: /sbin/grubby --update-kernel=ALL --args="{{{ arg_name_value }}}"
{{% endif -%}}
{{%- endmacro -%}}
{{#
Macro for Ansible 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 ansible_grub2_bootloader_argument_absent(arg_name) -%}}
{{% if 'ubuntu' in product or 'debian' in product or product in ['ol7', 'sle12', 'sle15'] %}}
- name: Check {{{ arg_name }}} argument exists
command: grep '^GRUB_CMDLINE_LINUX=.*{{{ arg_name }}}=.*"' /etc/default/grub
failed_when: False
register: argcheck
- name: Replace existing {{{ arg_name }}} argument
replace:
path: /etc/default/grub
regexp: '\(^GRUB_CMDLINE_LINUX=".*\){{{ arg_name }}}=?[^[:space:]]*\(.*"\)'
replace: '\1 \2'
when: argcheck is not skipped and argcheck.rc == 0
{{% endif -%}}
{{% if product in ['sle12', 'sle15'] %}}
- name: Update grub defaults and the bootloader menu
command: /usr/sbin/grub2-mkconfig -o {{{ grub2_boot_path }}}/grub.cfg
{{% elif 'debian' in product %}}
- name: Update grub defaults and the bootloader menu
command: /usr/sbin/update-grub
{{% else %}}
- name: Update grub defaults and the bootloader menu
command: /sbin/grubby --update-kernel=ALL --remove-args="{{{ arg_name }}}"
{{% endif -%}}
{{%- endmacro -%}}
{{#
Macro to restrict permissions in home directories of interactive users
#}}
{{%- macro ansible_restrict_permissions_home_directories(recursive=false) -%}}
- name: Get all local users from /etc/passwd
ansible.builtin.getent:
database: passwd
split: ':'
- name: Create local_users variable from the getent output
ansible.builtin.set_fact:
local_users: '{{ ansible_facts.getent_passwd|dict2items }}'
- name: Test for existence home directories to avoid creating them.
ansible.builtin.stat:
path: '{{ item.value[4] }}'
register: path_exists
loop: '{{ local_users }}'
when:
- item.value[1]|int >= {{{ uid_min }}}
- item.value[1]|int != {{{ nobody_uid }}}
- item.value[4] != "/"
- name: Ensure interactive local users have proper permissions on their respective home directories
ansible.builtin.file:
path: '{{ item.0.value[4] }}'
mode: 'u-s,g-w-s,o=-'
follow: no
{{%- if recursive %}}
recurse: yes
{{%- else %}}
recurse: no
{{%- endif %}}
loop: '{{ local_users|zip(path_exists.results)|list }}'
when:
- item.1.stat is defined and item.1.stat.exists
{{%- 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 include the line below, if necessary. Optional parameter.
:type after_match: str
#}}
{{%- macro ansible_ensure_pam_module_line(pam_file, group, control, module, after_match='') -%}}
- name: '{{{ rule_title }}} - Define a fact for control already filtered in case filters are used'
ansible.builtin.set_fact:
pam_module_control: '{{{ control }}}'
- name: '{{{ rule_title }}} - Check if expected PAM module line is present in {{{ pam_file }}}'
ansible.builtin.lineinfile:
path: "{{{ pam_file }}}"
regexp: ^\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}\s*.*
state: absent
check_mode: yes
changed_when: false
register: result_pam_line_present
- name: '{{{ rule_title }}} - Include or update the PAM module line in {{{ pam_file }}}'
block:
- name: '{{{ rule_title }}} - Check if required PAM module line is present in {{{ pam_file }}} with different control'
ansible.builtin.lineinfile:
path: "{{{ pam_file }}}"
regexp: ^\s*{{{ group }}}\s+.*\s+{{{ module }}}\s*
state: absent
check_mode: yes
changed_when: false
register: result_pam_line_other_control_present
- name: '{{{ rule_title }}} - Ensure the correct control for the required PAM module line in {{{ pam_file }}}'
ansible.builtin.replace:
dest: "{{{ pam_file }}}"
regexp: '^(\s*{{{ group }}}\s+).*(\b{{{ module }}}.*)'
replace: '\1{{ pam_module_control }} \2'
register: result_pam_module_edit
when:
- result_pam_line_other_control_present.found == 1
- name: '{{{ rule_title }}} - Ensure the required PAM module line is included in {{{ pam_file }}}'
ansible.builtin.lineinfile:
dest: "{{{ pam_file }}}"
{{%- if after_match != '' %}}
insertafter: {{{ after_match }}}
{{%- endif %}}
line: "{{{ group }}} {{ pam_module_control }} {{{ module }}}"
register: result_pam_module_add
when:
- result_pam_line_other_control_present.found == 0 or result_pam_line_other_control_present.found > 1
{{{ ansible_apply_authselect_changes() | indent(4) }}}
when:
- result_authselect_present is defined
- result_authselect_present.stat.exists
- >-
(result_pam_module_add is defined and result_pam_module_add.changed)
or (result_pam_module_edit is defined and result_pam_module_edit.changed)
when:
- result_pam_line_present.found is defined
- result_pam_line_present.found == 0
{{%- 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 ansible_ensure_pam_module_option(pam_file, group, control, module, option, value='', after_match='') -%}}
{{{ ansible_ensure_pam_module_line(pam_file, group, control, module, after_match) }}}
- name: '{{{ rule_title }}} - Define a fact for control already filtered in case filters are used'
ansible.builtin.set_fact:
pam_module_control: '{{{ control }}}'
- name: '{{{ rule_title }}} - Check if the required PAM module option is present in {{{ pam_file }}}'
ansible.builtin.lineinfile:
path: "{{{ pam_file }}}"
regexp: ^\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}\s*.*\s{{{ option }}}\b
state: absent
check_mode: true
changed_when: false
register: result_pam_module_{{{ rule_id }}}_option_present
- name: '{{{ rule_title }}} - Ensure the "{{{ option }}}" PAM option for "{{{ module }}}" is included in {{{ pam_file }}}'
ansible.builtin.lineinfile:
path: "{{{ pam_file }}}"
backrefs: true
regexp: ^(\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}.*)
{{%- if value == '' %}}
line: \1 {{{ option }}}
{{%- else %}}
line: \1 {{{ option }}}={{{ value }}}
{{%- endif %}}
state: present
register: result_pam_{{{ rule_id }}}_add
when:
- result_pam_module_{{{ rule_id }}}_option_present.found == 0
{{%- if value != '' %}}
- name: '{{{ rule_title }}} - Ensure the required value for "{{{ option }}}" PAM option from "{{{ module }}}" in {{{ pam_file }}}'
ansible.builtin.lineinfile:
path: "{{{ pam_file }}}"
backrefs: true
regexp: ^(\s*{{{ group }}}\s+{{ pam_module_control | regex_escape() }}\s+{{{ module }}}\s+.*)({{{ option }}})=[0-9a-zA-Z]+\s*(.*)
line: \1\2={{{ value }}} \3
register: result_pam_{{{ rule_id }}}_edit
when:
- result_pam_module_{{{ rule_id }}}_option_present.found > 0
{{%- 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 ansible_remove_pam_module_option(pam_file, group, control, module, option) -%}}
- name: '{{{ rule_title }}} - Define a fact for control already filtered in case filters are used'
ansible.builtin.set_fact:
pam_module_control: '{{{ control }}}'
- name: '{{{ rule_title }}} - Ensure the "{{{ option }}}" option from "{{{ module }}}" is not present in {{{ pam_file }}}'
ansible.builtin.replace:
dest: "{{{ pam_file }}}"
{{%- if control == '' %}}
regexp: (.*{{{ group }}}.*{{{ module }}}.*)\b{{{ option }}}\b=?[0-9a-zA-Z]*(.*)
{{%- else %}}
regexp: (.*{{{ group }}}.*{{ pam_module_control | regex_escape() }}.*{{{ module }}}.*)\b{{{ option }}}\b=?[0-9a-zA-Z]*(.*)
{{%- endif %}}
replace: '\1\2'
register: result_pam_option_removal
{{%- 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 taken. 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.
#}}
{{% macro ansible_ensure_authselect_custom_profile() -%}}
- name: '{{{ rule_title }}} - Get authselect current profile'
ansible.builtin.shell:
cmd: authselect current -r | awk '{ print $1 }'
register: result_authselect_profile
changed_when: false
when:
- result_authselect_check_cmd is success
- name: '{{{ rule_title }}} - Define the current authselect profile as a local fact'
ansible.builtin.set_fact:
authselect_current_profile: "{{ result_authselect_profile.stdout }}"
authselect_custom_profile: "{{ result_authselect_profile.stdout }}"
when:
- result_authselect_profile is not skipped
- result_authselect_profile.stdout is match("custom/")
- name: '{{{ rule_title }}} - Define the new authselect custom profile as a local fact'
ansible.builtin.set_fact:
authselect_current_profile: "{{ result_authselect_profile.stdout }}"
authselect_custom_profile: "custom/hardening"
when:
- result_authselect_profile is not skipped
- result_authselect_profile.stdout is not match("custom/")
- name: '{{{ rule_title }}} - Get authselect current features to also enable them in the custom profile'
ansible.builtin.shell:
cmd: authselect current | tail -n+3 | awk '{ print $2 }'
register: result_authselect_features
changed_when: false
when:
- result_authselect_profile is not skipped
- authselect_current_profile is not match("custom/")
- name: '{{{ rule_title }}} - Check if any custom profile with the same name was already created'
ansible.builtin.stat:
path: /etc/authselect/{{ authselect_custom_profile }}
register: result_authselect_custom_profile_present
changed_when: false
when:
- authselect_current_profile is not match("custom/")
- name: '{{{ rule_title }}} - Create an authselect custom profile based on the current profile'
ansible.builtin.command:
cmd: authselect create-profile hardening -b {{ authselect_current_profile }}
when:
- result_authselect_check_cmd is success
- authselect_current_profile is not match("^(custom/|local)")
- not result_authselect_custom_profile_present.stat.exists
- name: '{{{ rule_title }}} - Create an authselect custom profile based on sssd profile'
ansible.builtin.command:
cmd: authselect create-profile hardening -b sssd
when:
- result_authselect_check_cmd is success
- authselect_current_profile is match("local")
- not result_authselect_custom_profile_present.stat.exists
{{{ ansible_apply_authselect_changes('before-hardening-custom-profile') }}}
when:
- result_authselect_check_cmd is success
- result_authselect_profile is not skipped
- authselect_current_profile is not match("custom/")
- authselect_custom_profile is not match(authselect_current_profile)
- name: '{{{ rule_title }}} - Ensure the authselect custom profile is selected'
ansible.builtin.command:
cmd: authselect select {{ authselect_custom_profile }}
register: result_pam_authselect_select_profile
when:
- result_authselect_check_cmd is success
- result_authselect_profile is not skipped
- authselect_current_profile is not match("custom/")
- authselect_custom_profile is not match(authselect_current_profile)
- name: '{{{ rule_title }}} - Restore the authselect features in the custom profile'
ansible.builtin.command:
cmd: authselect enable-feature {{ item }}
loop: "{{ result_authselect_features.stdout_lines }}"
register: result_pam_authselect_restore_features
when:
- result_authselect_profile is not skipped
- result_authselect_features is not skipped
- result_pam_authselect_select_profile is not skipped
{{{ ansible_apply_authselect_changes('after-hardening-custom-profile') }}}
when:
- result_authselect_check_cmd is success
- result_authselect_profile is not skipped
- result_pam_authselect_restore_features is not skipped
{{%- endmacro %}}
{{#
Check if the system is using authselect. If so, check the profile integrity and make sure
a custom profile is ready to be updated. Otherwise, ensures the ansible fact referring
to the PAM file to be edited is correctly set.
:param pam_file: PAM config file.
:type pam_file: str
#}}
{{%- macro ansible_ensure_pam_facts_and_authselect_profile(pam_file) -%}}
- name: '{{{ rule_title }}} - Define the PAM file to be edited as a local fact'
ansible.builtin.set_fact:
pam_file_path: {{{ pam_file }}}
{{{ ansible_check_authselect_presence() }}}
- name: '{{{ rule_title }}} - Ensure authselect custom profile is used if authselect is present'
block:
{{{ ansible_check_authselect_integrity() | indent(4) }}}
{{{ ansible_ensure_authselect_custom_profile() | indent(4) }}}
- name: '{{{ rule_title }}} - Change the PAM file to be edited according to the custom authselect profile'
ansible.builtin.set_fact:
pam_file_path: "/etc/authselect/{{ authselect_custom_profile }}/{{ pam_file_path | basename }}"
when:
- result_authselect_present.stat.exists
{{%- 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 ansible_ensure_pam_module_configuration(pam_file, group, control, module, option, value='', after_match='') -%}}
- name: '{{{ rule_title }}} - Check if {{{ pam_file }}} file is present'
ansible.builtin.stat:
path: {{{ pam_file }}}
register: result_pam_file_present
- name: '{{{ rule_title }}} - Check the proper remediation for the system'
block:
{{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
{{%- if option == '' %}}
{{{ ansible_ensure_pam_module_line('{{ pam_file_path }}', group, control, module, after_match) | indent(4) }}}
{{%- else %}}
{{{ ansible_ensure_pam_module_option('{{ pam_file_path }}', group, control, module, option, value, after_match) | indent(4) }}}
{{%- endif %}}
{{{ ansible_apply_authselect_changes() | indent(4) }}}
when:
- result_authselect_present.stat.exists
- >-
(result_pam_{{{ rule_id }}}_add is defined and result_pam_{{{ rule_id }}}_add.changed)
or (result_pam_{{{ rule_id }}}_edit is defined and result_pam_{{{ rule_id }}}_edit.changed)
when:
- result_pam_file_present.stat.exists
{{%- 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 ansible_remove_pam_module_option_configuration(pam_file, group, control, module, option) -%}}
- name: '{{{ rule_title }}} - Check if {{{ pam_file }}} file is present'
ansible.builtin.stat:
path: {{{ pam_file }}}
register: result_pam_file_present
- name: '{{{ rule_title }}} - Check the proper remediation for the system'
block:
{{{ ansible_ensure_pam_facts_and_authselect_profile(pam_file) | indent(4) }}}
{{{ ansible_remove_pam_module_option('{{ pam_file_path }}', group, control, module, option) | indent(4) }}}
{{{ ansible_apply_authselect_changes() | indent(4) }}}
when:
- result_authselect_present.stat.exists
- result_pam_option_removal is changed
when:
- result_pam_file_present.stat.exists
{{%- endmacro -%}}
{{%- macro ansible_mount_conditional(path) -%}}
'"{{{ path }}}" in ansible_mounts | map(attribute="mount") | list'
{{%- endmacro -%}}
{{#
Create a list of paths composed by root directories and mount points representing local file systems.
This list excludes all local directories and mount points using known remote file systems.
It also excludes local directories and mount points with pseudo file systems. The list of paths
created by this macro can be used to efficiently locate local files or directories in a system.
:param list_name: Prefered list name to be used in subsequent tasks.
:type pam_file: str
#}}
{{%- macro ansible_create_list_of_local_paths(list_name="search_paths") -%}}
- name: "{{{ rule_title }}} - Define Excluded (Non-Local) File Systems and Paths"
ansible.builtin.set_fact:
excluded_fstypes:
- afs
- ceph
- cifs
- smb3
- smbfs
- sshfs
- ncpfs
- ncp
- nfs
- nfs4
- gfs
- gfs2
- glusterfs
- gpfs
- pvfs2
- ocfs2
- lustre
- davfs
- fuse.sshfs
excluded_paths:
- dev
- proc
- run
- sys
{{{ list_name }}}: []
- name: "{{{ rule_title }}} - Find Relevant Root Directories Ignoring Pre-Defined Excluded Paths"
ansible.builtin.find:
paths: /
file_type: directory
excludes: "{{ excluded_paths }}"
hidden: true
recurse: false
register: result_relevant_root_dirs
- name: "{{{ rule_title }}} - Include Relevant Root Directories in a List of Paths to be Searched"
ansible.builtin.set_fact:
{{{ list_name }}}: "{{ {{{ list_name }}} | union([item.path]) }}"
loop: "{{ result_relevant_root_dirs.files }}"
- name: "{{{ rule_title }}} - Increment Search Paths List with Local Partitions Mount Points"
ansible.builtin.set_fact:
{{{ list_name }}}: "{{ {{{ list_name }}} | union([item.mount]) }}"
loop: '{{ ansible_mounts }}'
when:
- item.fstype not in excluded_fstypes
- item.mount != '/'
- name: "{{{ rule_title }}} - Increment Search Paths List with Local NFS File System Targets"
ansible.builtin.set_fact:
{{{ list_name }}}: "{{ {{{ list_name }}} | union([item.device.split(':')[1]]) }}"
loop: '{{ ansible_mounts }}'
when:
- item.device is search("localhost:")
{{%- endmacro -%}}
|