## Guide to the Secure Configuration of Debian 13

> with profile ANSSI-BP-028 (high)
> This profile contains configurations that align to ANSSI-BP-028 v2.0 at the high hardening level. ANSSI is the French National Information Security Agency, and stands for Agence nationale de la sécurité des systèmes d'information. ANSSI-BP-028 is a configuration recommendation for GNU/Linux systems. A copy of the ANSSI-BP-028 can be found at the ANSSI website: https://www.ssi.gouv.fr/administration/guide/recommandations-de-securite-relatives-a-un-systeme-gnulinux/

The SCAP Security Guide Project
https://www.open-scap.org/security-policies/scap-security-guide
This guide presents a catalog of security-relevant configuration settings for Debian 13. It is a rendering of content structured in the eXtensible Configuration Checklist Description Format (XCCDF) in order to support security automation. The SCAP content is is available in the `scap-security-guide` package which is developed at https://www.open-scap.org/security-policies/scap-security-guide.
Providing system administrators with such guidance informs them how to securely configure systems under their control in a variety of network roles. Policy makers and baseline creators can use this catalog of settings, with its associated references to higher-level security control catalogs, in order to assist them in security baseline creation. This guide is a catalog, not a checklist, and satisfaction of every item is not likely to be possible or sensible in many operational scenarios. However, the XCCDF format enables granular selection and adjustment of settings, and their association with OVAL and OCIL content provides an automated checking capability. Transformations of this document, and its associated automated checking content, are capable of providing baselines that meet a diverse set of policy objectives. Some example XCCDF Profiles, which are selections of items that form checklists and can be used as baselines, are available with this guide. They can be processed, in an automated fashion, with tools that support the Security Content Automation Protocol (SCAP). The DISA STIG, which provides required settings for US Department of Defense systems, is one example of a baseline created from this guidance.
Do not attempt to implement any of the settings in this guide without first testing them in a non-operational environment. The creators of this guidance assume no responsibility whatsoever for its use by other parties, and makes no guarantees, expressed or implied, about its quality, reliability, or any other characteristic.

## Profile Information

Profile Title | ANSSI-BP-028 (high)
Profile ID | xccdf_org.ssgproject.content_profile_anssi_bp28_high

#### CPE Platforms

- cpe:/o:debian:debian_linux:13

## Revision History

Current version: 0.1.79

- draft (as of 2025-12-05)

## Table of Contents

1. System Settings
   1. Installing and Maintaining Software
   2. Account and Access Control
   3. AppArmor
   4. GRUB2 bootloader configuration
   5. Kernel Configuration
   6. Configure Syslog
   7. Network Configuration and Firewalls
   8. File Permissions and Masks
   9. SELinux
2. Services
   1. DHCP
   2. Mail Server Software
   3. Network Time Protocol
   4. Obsolete Services
   5. SSH Server
   6. System Security Services Daemon
3. System Accounting with auditd
   1. Configure auditd Rules for Comprehensive Auditing

## Checklist

Group Guide to the Secure Configuration of Debian 13 Group contains 78 groups and 399 rules
Group System Settings Group contains 51 groups and 308 rules
[ref] Contains rules that check correct system settings.
Group Installing and Maintaining Software Group contains 6 groups and 36 rules
[ref] The following sections contain information on security-relevant choices during the initial operating system installation process and the setup of software updates.
Group System and Software Integrity Group contains 2 groups and 7 rules

[ref] System and software integrity can be gained by installing antivirus, increasing system encryption strength with FIPS, verifying installed software, enabling SELinux, installing an Intrusion Prevention System, etc. However, installing or enabling integrity checking tools cannot prevent intrusions, but they can detect that an intrusion may have occurred. Requirements for integrity checking may be highly dependent on the environment in which the system will be used. Snapshot-based approaches such as AIDE may induce considerable overhead in the presence of frequent software updates.

Group Software Integrity Checking Group contains 1 group and 7 rules

[ref] Both the AIDE (Advanced Intrusion Detection Environment) software and the RPM package management system provide mechanisms for verifying the integrity of installed software. AIDE uses snapshots of file metadata (such as hashes) and compares these to current system files in order to detect changes.
The RPM package management system can conduct integrity checks by comparing information in its metadata database with files installed on the system.

Group Verify Integrity with AIDE Group contains 7 rules
[ref] AIDE conducts integrity checks by comparing information about files with previously-gathered information. Ideally, the AIDE database is created immediately after initial system configuration, and then again after any software update. AIDE is highly configurable, with further configuration information located in `/usr/share/doc/aide-VERSION` .

#### Rule Install AIDE [ref]

The `aide` package can be installed with the following command:

    $ apt-get install aide

Rationale: | The AIDE package must be installed if it is to be available for integrity checking.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_aide_installed

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 5, 7, 8, 9
cjis | 5.10.1.3
cobit5 | APO01.06, BAI01.06, BAI02.01, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS04.07, DSS05.02, DSS05.03, DSS05.05, DSS05.07, DSS06.02, DSS06.06
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3, 4.3.4.4.4
isa-62443-2013 | SR 3.1, SR 3.3, SR 3.4, SR 3.8, SR 4.1, SR 6.2, SR 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.1, A.12.4.1, A.12.5.1, A.12.6.2, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.14.2.7, A.15.2.1, A.8.2.3
nist | CM-6(a)
nist-csf | DE.CM-1, DE.CM-7, PR.DS-1, PR.DS-6, PR.DS-8, PR.IP-1, PR.IP-3
pcidss | Req-11.5
os-srg | SRG-OS-000445-GPOS-00199
anssi | R76, R79
ism | 1034, 1288, 1341, 1417
pcidss4 | 11.5.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "aide"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_aide

    class install_aide {
      package { 'aide':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_aide_installed

    - name: Ensure aide is installed
      ansible.builtin.package:
        name: aide
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_aide_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "aide"
    version = "*"

#### Rule Build and Test AIDE Database [ref]

Run the following command to generate a new database:

    $ sudo aideinit

By default, the database will be written to the file `/var/lib/aide/aide.db.new`. Storing the database, the configuration file `/etc/aide.conf`, and the binary `/usr/sbin/aide` (or hashes of these files), in a secure location (such as on read-only media) provides additional assurance about their integrity. The newly-generated database can be installed as follows:

    $ sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

To initiate a manual check, run the following command:

    $ sudo /usr/sbin/aide --check

If this check produces any unexpected output, investigate.
Warning: In RHEL Image Mode (bootc) systems, the AIDE database must be regenerated after each system update. Image Mode systems receive updates through new container images that may include modified files. After applying system updates, run the following commands to regenerate the AIDE database:

    $ sudo /usr/sbin/aide --init

Then replace the existing database:

    $ sudo cp /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

Failure to regenerate the AIDE database after updates will result in false positive alerts for legitimate system changes introduced by the update process.

Rationale: | For AIDE to be effective, an initial database of "known-good" information about files must be captured and it should be able to be verified against the installed files.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_aide_build_database

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 5, 7, 8, 9
cjis | 5.10.1.3
cobit5 | APO01.06, BAI01.06, BAI02.01, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS04.07, DSS05.02, DSS05.03, DSS05.05, DSS05.07, DSS06.02, DSS06.06
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3, 4.3.4.4.4
isa-62443-2013 | SR 3.1, SR 3.3, SR 3.4, SR 3.8, SR 4.1, SR 6.2, SR 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.1, A.12.4.1, A.12.5.1, A.12.6.2, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.14.2.7, A.15.2.1, A.8.2.3
nist | CM-6(a)
nist-csf | DE.CM-1, DE.CM-7, PR.DS-1, PR.DS-6, PR.DS-8, PR.IP-1, PR.IP-3
pcidss | Req-11.5
os-srg | SRG-OS-000445-GPOS-00199
anssi | R76, R79
pcidss4 | 11.5.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "aide"

    AIDE_CONFIG=/etc/aide/aide.conf
    DEFAULT_DB_PATH=/var/lib/aide/aide.db

    # Fix db path in the config file, if necessary

    if ! grep -q '^database_in=file:' ${AIDE_CONFIG}; then
        echo "database_in=file:${DEFAULT_DB_PATH}" >> ${AIDE_CONFIG}
    fi

    # Fix db out path in the config file, if necessary
    if ! grep -q '^database_out=file:' ${AIDE_CONFIG}; then
        echo "database_out=file:${DEFAULT_DB_PATH}.new" >> ${AIDE_CONFIG}
    fi

    /usr/sbin/aideinit -y -f

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Ensure AIDE Is Installed
      ansible.builtin.apt:
        name: aide
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Check if DB Path in /etc/aide/aide.conf Is
        Already Set
      ansible.builtin.lineinfile:
        path: /etc/aide/aide.conf
        regexp: ^#?(\s*)(database=)(.*)$
        state: absent
      check_mode: true
      changed_when: false
      register: database_replace
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Check if DB Out Path in /etc/aide/aide.conf
        Is Already Set
      ansible.builtin.lineinfile:
        path: /etc/aide/aide.conf
        regexp: ^#?(\s*)(database_out=)(.*)$
        state: absent
      check_mode: true
      changed_when: false
      register: database_out_replace
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Fix DB Path in Config File if Necessary
      ansible.builtin.lineinfile:
        path: /etc/aide/aide.conf
        regexp: ^#?(\s*)(database)(\s*)=(\s*)(.*)$
        line: \2\3=\4file:/var/lib/aide/aide.db
        backrefs: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - database_replace.found > 0
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Fix DB Out Path in Config File if Necessary
      ansible.builtin.lineinfile:
        path: /etc/aide/aide.conf
        regexp: ^#?(\s*)(database_out)(\s*)=(\s*)(.*)$
        line: \2\3=\4file:/var/lib/aide/aide.db.new
        backrefs: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - database_out_replace.found > 0
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Ensure the Default DB Path is Added
      ansible.builtin.lineinfile:
        path: /etc/aide/aide.conf
        line: database=file:/var/lib/aide/aide.db
        create: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - database_replace.found == 0
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Ensure the Default Out Path is Added
      ansible.builtin.lineinfile:
        path: /etc/aide/aide.conf
        line: database_out=file:/var/lib/aide/aide.db.new
        create: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - database_out_replace.found == 0
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Build and Test AIDE Database - Build and Test AIDE Database
      ansible.builtin.command: /usr/sbin/aideinit -y -f
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_build_database
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Configure Systemd Timer Execution of AIDE [ref]

At a minimum, AIDE should be configured to run a weekly scan. To implement a systemd service and a timer unit to run the service periodically: For example, if a systemd timer is expected to be started every day at 5AM

    OnCalendar=*-*-* 05:00:0

    [Timer]

section in the timer unit and a Unit section starting the AIDE check service unit should be referred.

Rationale: | AIDE provides a means to check if unauthorized changes are made to the system. AIDE itself does not setup a periodic execution, so in order to detect unauthorized changes a systemd service to run the check and a systemd timer to take care of periodical execution of that systemd service should be defined.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_aide_periodic_checking_systemd_timer

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 5, 7, 8, 9
cjis | 5.10.1.3
cobit5 | APO01.06, BAI01.06, BAI02.01, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS04.07, DSS05.02, DSS05.03, DSS05.05, DSS05.07, DSS06.02, DSS06.06
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3, 4.3.4.4.4
isa-62443-2013 | SR 3.1, SR 3.3, SR 3.4, SR 3.8, SR 4.1, SR 6.2, SR 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.1, A.12.4.1, A.12.5.1, A.12.6.2, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.14.2.7, A.15.2.1, A.8.2.3
nist | SI-7, SI-7(1), CM-6(a)
nist-csf | DE.CM-1, DE.CM-7, PR.DS-1, PR.DS-6, PR.DS-8, PR.IP-1, PR.IP-3
pcidss | Req-11.5
os-srg | SRG-OS-000363-GPOS-00150, SRG-OS-000446-GPOS-00200, SRG-OS-000447-GPOS-00201
anssi | R76
pcidss4 | 11.5.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ( dpkg-query --show --showformat='${db:Status-Status}' 'aide' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'systemd' 2>/dev/null | grep -q '^installed$' ); }; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "aide"

    # create unit file for periodic aide database check
    cat > /etc/systemd/system/aidecheck.service <<EOF
    [Unit]
    Description=Aide Check
    [Service]
    Type=simple
    ExecStart=/usr/sbin/aide --check
    [Install]
    WantedBy=multi-user.target
    EOF

    # create unit file for the aide check timer
    cat > /etc/systemd/system/aidecheck.timer <<EOF
    [Unit]
    Description=Aide check every day at 5AM
    [Timer]
    OnCalendar=*-*-* 05:00:00
    Unit=aidecheck.service
    [Install]
    WantedBy=multi-user.target
    EOF

    #  setup service unit files attributes
    chown root:root /etc/systemd/system/aidecheck.*
    chmod 0644 /etc/systemd/system/aidecheck.*

    # enable the aide related services
    systemctl daemon-reload
    systemctl enable aidecheck.service
    systemctl enable aidecheck.timer

    if [[ $(systemctl is-system-running) != "offline" ]]; then
      systemctl start aidecheck.timer
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_checking_systemd_timer
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure Systemd Timer Execution of AIDE - Define AIDE Periodic Check Service
      ansible.builtin.blockinfile:
        create: true
        dest: /etc/systemd/system/aidecheck.service
        owner: root
        group: root
        mode: '0644'
        block: |
          [Unit]
          Description=Aide Check
          [Service]
          Type=simple
          ExecStart=/usr/sbin/aide --check
          [Install]
          WantedBy=multi-user.target
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( "aide" in ansible_facts.packages and "systemd" in ansible_facts.packages )
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_checking_systemd_timer
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure Systemd Timer Execution of AIDE - Define AIDE Periodic Check Service
        Timer
      ansible.builtin.blockinfile:
        create: true
        dest: /etc/systemd/system/aidecheck.timer
        owner: root
        group: root
        mode: '0644'
        block: |
          [Unit]
          Description=Aide check every day at 5AM
          [Timer]
          OnCalendar=*-*-* 05:00:00
          Unit=aidecheck.service
          [Install]
          WantedBy=multi-user.target
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( "aide" in ansible_facts.packages and "systemd" in ansible_facts.packages )
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_checking_systemd_timer
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure Systemd Timer Execution of AIDE - Ensure AIDE Service is Enabled
      ansible.builtin.systemd:
        name: aidecheck.service
        enabled: true
        daemon_reload: true
        masked: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( "aide" in ansible_facts.packages and "systemd" in ansible_facts.packages )
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_checking_systemd_timer
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure Systemd Timer Execution of AIDE - Ensure AIDE Service Timer is Enabled
      ansible.builtin.systemd:
        name: aidecheck.timer
        state: started
        enabled: true
        daemon_reload: true
        masked: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( "aide" in ansible_facts.packages and "systemd" in ansible_facts.packages )
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_checking_systemd_timer
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Configure Periodic Execution of AIDE [ref]

At a minimum, AIDE should be configured to run a weekly scan. To implement a daily execution of AIDE at 4:05am using cron, add the following line to `/etc/crontab`:

    05 4 * * * root /usr/sbin/aide --check

To implement a weekly execution of AIDE at 4:05am using cron, add the following line to `/etc/crontab`:

    05 4 * * 0 root /usr/sbin/aide --check

AIDE can be executed periodically through other means; this is merely one example. The usage of cron's special time codes, such as `@daily` and `@weekly` is acceptable.

Rationale:

By default, AIDE does not install itself for periodic execution. Periodically running AIDE is necessary to reveal unexpected changes in installed files.
Unauthorized changes to the baseline configuration could make the system vulnerable to various attacks or allow unauthorized access to the operating system. Changes to operating system configurations can have unintended side effects, some of which may be relevant to security.
Detecting such changes and providing an automated response can help avoid unintended, negative consequences that could ultimately affect the security state of the operating system. The operating system's Information Management Officer (IMO)/Information System Security Officer (ISSO) and System Administrators (SAs) must be notified via email and/or monitoring system trap when there is an unauthorized modification of a configuration item.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_aide_periodic_cron_checking

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 5, 7, 8, 9
cjis | 5.10.1.3
cobit5 | APO01.06, BAI01.06, BAI02.01, BAI03.05, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS04.07, DSS05.02, DSS05.03, DSS05.05, DSS05.07, DSS06.02, DSS06.06
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3, 4.3.4.4.4
isa-62443-2013 | SR 3.1, SR 3.3, SR 3.4, SR 3.8, SR 4.1, SR 6.2, SR 7.6
iso27001-2013 | A.11.2.4, A.12.1.2, A.12.2.1, A.12.4.1, A.12.5.1, A.12.6.2, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.14.2.7, A.15.2.1, A.8.2.3
nist | SI-7, SI-7(1), CM-6(a)
nist-csf | DE.CM-1, DE.CM-7, PR.DS-1, PR.DS-6, PR.DS-8, PR.IP-1, PR.IP-3
pcidss | Req-11.5
os-srg | SRG-OS-000363-GPOS-00150, SRG-OS-000446-GPOS-00200, SRG-OS-000447-GPOS-00201
anssi | R76
pcidss4 | 11.5.2

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_cron_checking
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure AIDE is installed
      ansible.builtin.package:
        name: aide
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_cron_checking
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Install cron
      ansible.builtin.package:
        name: cron
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_cron_checking
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Gather list of installed packages
      ansible.builtin.package_facts:
        manager: auto
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_cron_checking
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Periodic Execution of AIDE
      ansible.builtin.cron:
        name: run AIDE check
        minute: 5
        hour: 4
        user: root
        job: /usr/sbin/aide --check
      register: crontab_check
      when:
      - '"linux-base" in ansible_facts.packages'
      - '''cron'' in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - PCI-DSS-Req-11.5
      - PCI-DSSv4-11.5.2
      - aide_periodic_cron_checking
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Configure Notification of Post-AIDE Scan Details [ref]

AIDE should notify appropriate personnel of the details of a scan after the scan has been run. If AIDE has already been configured for periodic execution in `/etc/crontab`, append the following line to the existing AIDE line:

     | /bin/mail -s "$(hostname) - AIDE Integrity Check" root@localhost

Otherwise, add the following line to `/etc/crontab`:

    05 4 * * * root /usr/sbin/aide --check | /bin/mail -s "$(hostname) - AIDE Integrity Check" root@localhost

AIDE can be executed periodically through other means; this is merely one example.

Rationale:

Unauthorized changes to the baseline configuration could make the system vulnerable to various attacks or allow unauthorized access to the operating system. Changes to operating system configurations can have unintended side effects, some of which may be relevant to security.
Detecting such changes and providing an automated response can help avoid unintended, negative consequences that could ultimately affect the security state of the operating system. The operating system's Information Management Officer (IMO)/Information System Security Officer (ISSO) and System Administrators (SAs) must be notified via email and/or monitoring system trap when there is an unauthorized modification of a configuration item.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_aide_scan_notification

References:

cis-csc | 1, 11, 12, 13, 15, 16, 2, 3, 5, 7, 8, 9
cobit5 | BAI01.06, BAI06.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS05.02, DSS05.05, DSS05.07
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 6.2, SR 7.6
iso27001-2013 | A.12.1.2, A.12.4.1, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.14.2.7, A.15.2.1
nist | CM-6(a), CM-3(5)
nist-csf | DE.CM-1, DE.CM-7, PR.IP-1, PR.IP-3
os-srg | SRG-OS-000363-GPOS-00150, SRG-OS-000446-GPOS-00200, SRG-OS-000447-GPOS-00201
anssi | R76

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "aide"
    var_aide_scan_notification_email='root@localhost'

    CRONTAB=/etc/crontab
    CRONDIRS='/etc/cron.d /etc/cron.daily /etc/cron.weekly /etc/cron.monthly'

    # NOTE: on some platforms, /etc/crontab may not exist
    if [ -f /etc/crontab ]; then
    	CRONTAB_EXIST=/etc/crontab
    fi

    if [ -f /var/spool/cron/root ]; then
    	VARSPOOL=/var/spool/cron/root
    fi

    if ! grep -qR '^.*/usr/sbin/aide\s*\-\-check.*|.*\/bin\/mail\s*-s\s*".*"\s*.*@.*$' $CRONTAB_EXIST $VARSPOOL $CRONDIRS; then
    	echo "0 5 * * * root /usr/sbin/aide  --check | /bin/mail -s \"\$(hostname) - AIDE Integrity Check\" $var_aide_scan_notification_email" >> $CRONTAB
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-3(5)
      - NIST-800-53-CM-6(a)
      - aide_scan_notification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_aide_scan_notification_email # promote to variable
      set_fact:
        var_aide_scan_notification_email: !!str root@localhost
      tags:
        - always

    - name: Ensure AIDE is installed
      ansible.builtin.package:
        name: '{{ item }}'
        state: present
      with_items:
      - aide
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-3(5)
      - NIST-800-53-CM-6(a)
      - aide_scan_notification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Configure Notification of Post-AIDE Scan Details
      ansible.builtin.cron:
        name: run AIDE check
        minute: 5
        hour: 4
        weekday: 0
        user: root
        job: /usr/sbin/aide  --check | /bin/mail -s "$(hostname) - AIDE Integrity Check"
          {{ var_aide_scan_notification_email }}
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-3(5)
      - NIST-800-53-CM-6(a)
      - aide_scan_notification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Configure AIDE to Verify Access Control Lists (ACLs) [ref]

By default, the `acl` option is added to the `FIPSR` ruleset in AIDE. If using a custom ruleset or the `acl` option is missing, add `acl` to the appropriate ruleset. For example, add `acl` to the following line in `/etc/aide/aide.conf`:

    FIPSR = p+i+n+u+g+s+m+c+acl+selinux+xattrs+sha256

AIDE rules can be configured in multiple ways; this is merely one example that is already configured by default. The remediation provided with this rule adds `acl` to the OwnerMode rule in `/etc/aide/aide.conf`

Rationale: | ACLs can provide permissions beyond those permitted through the file mode and must be verified by the file integrity tools.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_aide_verify_acls

References:

cis-csc | 2, 3
cobit5 | APO01.06, BAI03.05, BAI06.01, DSS06.02
isa-62443-2009 | 4.3.4.4.4
isa-62443-2013 | SR 3.1, SR 3.3, SR 3.4, SR 3.8
iso27001-2013 | A.11.2.4, A.12.2.1, A.12.5.1, A.14.1.2, A.14.1.3, A.14.2.4
nist | SI-7, SI-7(1), CM-6(a)
nist-csf | PR.DS-6, PR.DS-8
os-srg | SRG-OS-000480-GPOS-00227
anssi | R76

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "aide"

    aide_conf="/etc/aide/aide.conf"

    groups=$(LC_ALL=C grep "^OwnerMode" $aide_conf | grep -v "^ALLXTRAHASHES" | cut -f1 -d '=' | tr -d ' ' | sort -u)

    for group in $groups
    do
    	config=$(grep "^$group\s*=" $aide_conf | cut -f2 -d '=' | tr -d ' ')

    	if ! [[ $config = *acl* ]]
    	then
    		if [[ -z $config ]]
    		then
    			config="acl"
    		else
    			config=$config"+acl"
    		fi
    	fi
    	sed -i "s/^$group\s*=.*/$group = $config/g" $aide_conf
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_acls
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Gather list of packages
      ansible.builtin.package_facts:
        manager: auto
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_acls
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Get rules groups
      ansible.builtin.shell: |
        set -o pipefail
        LC_ALL=C grep "^[A-Z][A-Za-z_]*" /etc/aide.conf | grep -v "^ALLXTRAHASHES" | cut -f1 -d '=' | tr -d ' ' | sort -u || true
      when:
      - '"linux-base" in ansible_facts.packages'
      - '''aide'' in ansible_facts.packages'
      register: find_rules_groups_results
      changed_when: false
      check_mode: false
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_acls
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the acl rule is present when aide is installed.
      ansible.builtin.replace:
        path: /etc/aide.conf
        regexp: (^\s*{{ item }}\s*=\s*)(?!.*acl)([^\s]*)
        replace: \g<1>\g<2>+acl
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_rules_groups_results is not skipped and "'aide' in ansible_facts.packages"
      with_items: '{{ find_rules_groups_results.stdout_lines | map(''trim'') | list }}'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_acls
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Configure AIDE to Verify Extended Attributes [ref]

By default, the `xattrs` option is added to the `FIPSR` ruleset in AIDE. If using a custom ruleset or the `xattrs` option is missing, add `xattrs` to the appropriate ruleset. For example, add `xattrs` to the following line in `/etc/aide/aide.conf`:

    FIPSR = p+i+n+u+g+s+m+c+acl+selinux+xattrs+sha256

AIDE rules can be configured in multiple ways; this is merely one example that is already configured by default. The remediation provided with this rule adds `xattrs` to the InodeData rule in `/etc/aide/aide.conf`

Rationale: | Extended attributes in file systems are used to contain arbitrary data and file metadata with security implications.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_aide_verify_ext_attributes

References:

cis-csc | 2, 3
cobit5 | APO01.06, BAI03.05, BAI06.01, DSS06.02
isa-62443-2009 | 4.3.4.4.4
isa-62443-2013 | SR 3.1, SR 3.3, SR 3.4, SR 3.8
iso27001-2013 | A.11.2.4, A.12.2.1, A.12.5.1, A.14.1.2, A.14.1.3, A.14.2.4
nist | SI-7, SI-7(1), CM-6(a)
nist-csf | PR.DS-6, PR.DS-8
os-srg | SRG-OS-000480-GPOS-00227
anssi | R76

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "aide"

    aide_conf="/etc/aide/aide.conf"

    groups=$(LC_ALL=C grep "^InodeData" $aide_conf | grep -v "^ALLXTRAHASHES" | cut -f1 -d '=' | tr -d ' ' | sort -u)

    for group in $groups
    do
    	config=$(grep "^$group\s*=" $aide_conf | cut -f2 -d '=' | tr -d ' ')

    	if ! [[ $config = *xattrs* ]]
    	then
    		if [[ -z $config ]]
    		then
    			config="xattrs"
    		else
    			config=$config"+xattrs"
    		fi
    	fi
    	sed -i "s/^$group\s*=.*/$group = $config/g" $aide_conf
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_ext_attributes
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Gather list of packages
      ansible.builtin.package_facts:
        manager: auto
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_ext_attributes
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Get rules groups
      ansible.builtin.shell: |
        set -o pipefail
        LC_ALL=C grep "^[A-Z][A-Za-z_]*" /etc/aide.conf | grep -v "^ALLXTRAHASHES" | cut -f1 -d '=' | tr -d ' ' | sort -u || true
      when:
      - '"linux-base" in ansible_facts.packages'
      - '''aide'' in ansible_facts.packages'
      register: find_rules_groups_results
      changed_when: false
      check_mode: false
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_ext_attributes
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the xattrs rule is present when aide is installed.
      ansible.builtin.replace:
        path: /etc/aide.conf
        regexp: (^\s*{{ item }}\s*=\s*)(?!.*xattrs)([^\s]*)
        replace: \g<1>\g<2>+xattrs
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_rules_groups_results is not skipped and "'aide' in ansible_facts.packages"
      with_items: '{{ find_rules_groups_results.stdout_lines | map(''trim'') | list }}'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-7
      - NIST-800-53-SI-7(1)
      - aide_verify_ext_attributes
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - restrict_strategy

Group Disk Partitioning Group contains 9 rules

[ref] To ensure separation and protection of data, there are top-level system directories which should be placed on their own physical partition or logical volume. The installer's default partitioning scheme creates separate logical volumes for `/`, `/boot`, and `swap`.

- If starting with any of the default layouts, check the box to \"Review and modify partitioning.\" This allows for the easy creation of additional logical volumes inside the volume group already created, though it may require making `/`'s logical volume smaller to create space. In general, using logical volumes is preferable to using partitions because they can be more easily adjusted later.
- If creating a custom layout, create the partitions mentioned in the previous paragraph (which the installer will require anyway), as well as separate ones described in the following sections.

If a system has already been installed, and the default partitioning scheme was used, it is possible but nontrivial to modify it to create separate logical volumes for the directories listed above. The Logical Volume Manager (LVM) makes this possible.

#### Rule Ensure /boot Located On Separate Partition [ref]

It is recommended that the `/boot` directory resides on a separate partition. This makes it easier to apply restrictions e.g. through the `noexec` mount option. Eventually, the `/boot` partition can be configured not to be mounted automatically with the `noauto` mount option.
Rationale: | The `/boot` partition contains the kernel and bootloader files. Access to this partition should be restricted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_boot

References:

anssi | R28

#### Rule Ensure /home Located On Separate Partition [ref]

If user home directories will be stored locally, create a separate partition for `/home` at installation time (or migrate it later using LVM). If `/home` will be mounted from another system such as an NFS server, then creating a separate partition is not necessary at installation time, and the mountpoint can instead be configured later.
Rationale: | Ensuring that `/home` is mounted on its own partition enables the setting of more restrictive mount options, and also helps ensure that users cannot trivially fill partitions used for log or audit data storage.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_home

References:

cis-csc | 12, 15, 8
cobit5 | APO13.01, DSS05.02
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.13.1.1, A.13.2.1, A.14.1.3
nist | CM-6(a), SC-5(2)
nist-csf | PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R28

#### Rule Ensure /opt Located On Separate Partition [ref]

It is recommended that the `/opt` directory resides on a separate partition.
Rationale: | The `/opt` partition contains additional software, usually installed outside the packaging system. Putting this directory on a separate partition makes it easier to apply restrictions e.g. through the `nosuid` mount option.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_opt

References:

anssi | R28

#### Rule Ensure /srv Located On Separate Partition [ref]

If a file server (FTP, TFTP...) is hosted locally, create a separate partition for `/srv` at installation time (or migrate it later using LVM). If `/srv` will be mounted from another system such as an NFS server, then creating a separate partition is not necessary at installation time, and the mountpoint can instead be configured later.
Rationale: | Srv deserves files for local network file server such as FTP. Ensuring that `/srv` is mounted on its own partition enables the setting of more restrictive mount options, and also helps ensure that users cannot trivially fill partitions used for log or audit data storage.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_srv

References:

anssi | R28

#### Rule Ensure /usr Located On Separate Partition [ref]

It is recommended that the `/usr` directory resides on a separate partition.
Rationale: | The `/usr` partition contains system software, utilities and files. Putting it on a separate partition allows limiting its size and applying restrictions through mount options.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_usr

References:

anssi | R28

#### Rule Ensure /var Located On Separate Partition [ref]

The `/var` directory is used by daemons and other system services to store frequently-changing data. Ensure that `/var` has its own partition or logical volume at installation time, or migrate it using LVM.
Rationale: | Ensuring that `/var` is mounted on its own partition enables the setting of more restrictive mount options. This helps protect system services such as daemons or other programs which use it. It is not uncommon for the `/var` directory to contain world-writable directories installed by other software packages.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_var

References:

cis-csc | 12, 15, 8
cobit5 | APO13.01, DSS05.02
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.13.1.1, A.13.2.1, A.14.1.3
nist | CM-6(a), SC-5(2)
nist-csf | PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R28

#### Rule Ensure /var/log Located On Separate Partition [ref]

System logs are stored in the `/var/log` directory. Ensure that `/var/log` has its own partition or logical volume at installation time, or migrate it using LVM.
Rationale: | Placing `/var/log` in its own partition enables better separation between log files and other files in `/var/`.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_var_log

References:

cis-csc | 1, 12, 14, 15, 16, 3, 5, 6, 8
cobit5 | APO11.04, APO13.01, BAI03.05, DSS05.02, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3
nerc-cip | CIP-007-3 R6.5
nist | CM-6(a), AU-4, SC-5(2)
nist-csf | PR.PT-1, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R28

#### Rule Ensure /var/log/audit Located On Separate Partition [ref]

Audit logs are stored in the `/var/log/audit` directory. Ensure that `/var/log/audit` has its own partition or logical volume at installation time, or migrate it using LVM. Make absolutely certain that it is large enough to store all audit logs that will be created by the auditing daemon.
Rationale: | Placing `/var/log/audit` in its own partition enables better separation between audit files and other files, and helps ensure that auditing cannot be halted due to the partition running out of space.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_var_log_audit

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 8
cobit5 | APO11.04, APO13.01, BAI03.05, BAI04.04, DSS05.02, DSS05.04, DSS05.07, MEA02.01
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.12.1.3, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.17.2.1
nerc-cip | CIP-007-3 R6.5
nist | CM-6(a), AU-4, SC-5(2)
nist-csf | PR.DS-4, PR.PT-1, PR.PT-4
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000341-GPOS-00132, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000357-CTR-000800
anssi | R71

#### Rule Ensure /var/tmp Located On Separate Partition [ref]

The `/var/tmp` directory is a world-writable directory used for temporary file storage. Ensure it has its own partition or logical volume at installation time, or migrate it using LVM.
Rationale: | The `/var/tmp` partition is used as temporary storage by many programs. Placing `/var/tmp` in its own partition enables the setting of more restrictive mount options, which can help protect programs which use it.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_partition_for_var_tmp

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R28

Group Sudo Group contains 18 rules

[ref] `Sudo`, which stands for "su 'do'", provides the ability to delegate authority to certain users, groups of users, or system administrators. When configured for system users and/or groups, `Sudo` can allow a user or group to execute privileged commands that normally only `root` is allowed to execute.
For more information on `Sudo` and addition `Sudo` configuration options, see https://www.sudo.ws.

#### Rule Install sudo Package [ref]

The `sudo` package can be installed with the following command:

    $ apt-get install sudo

Rationale: | `sudo` is a program designed to allow a system administrator to give limited root privileges to users and log root activity. The basic philosophy is to give as few privileges as possible but still allow system users to get their work done.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_sudo_installed

References:

nist | CM-6(a)
ospp | FMT_MOF_EXT.1
os-srg | SRG-OS-000324-GPOS-00125
anssi | R33
ism | 1386
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "sudo"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_sudo

    class install_sudo {
      package { 'sudo':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sudo_installed

    - name: Ensure sudo is installed
      ansible.builtin.package:
        name: sudo
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sudo_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "sudo"
    version = "*"

#### Rule Verify Group Who Owns /etc/sudoers.d Directory [ref]

To properly set the group owner of `/etc/sudoers.d`, run the command:

    $ sudo chgrp root /etc/sudoers.d

Rationale: | The ownership of the /etc/sudoers.d directory by the root group is important because this directory hosts sudo configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the sudo configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_groupowner_etc_sudoersd

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /etc/sudoers.d/ -maxdepth 0 -type d  ! -group root -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_groupowner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - directory_groupowner_etc_sudoersd_newgroup is undefined
      tags:
      - configure_strategy
      - directory_groupowner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_etc_sudoersd_newgroup variable if root found
      ansible.builtin.set_fact:
        directory_groupowner_etc_sudoersd_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - directory_groupowner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/sudoers.d/
      ansible.builtin.file:
        path: /etc/sudoers.d/
        follow: false
        state: directory
        group: '{{ directory_groupowner_etc_sudoersd_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_groupowner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/sudoers.d Directory [ref]

To properly set the owner of `/etc/sudoers.d`, run the command:

    $ sudo chown root /etc/sudoers.d

Rationale: | The ownership of the /etc/sudoers.d directory by the root user is important because this directory hosts sudo configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the sudo configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_owner_etc_sudoersd

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/sudoers.d/ -maxdepth 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_owner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_etc_sudoersd_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_etc_sudoersd_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/sudoers.d/
      ansible.builtin.file:
        path: /etc/sudoers.d/
        follow: false
        state: directory
        owner: '{{ directory_owner_etc_sudoersd_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/sudoers.d Directory [ref]

To properly set the permissions of `/etc/sudoers.d`, run the command:

    $ sudo chmod 0750 /etc/sudoers.d

Rationale: | Setting correct permissions on the /etc/sudoers.d directory is important because this directory hosts sudo configuration. Protection of this directory is critical for system security. Restricting the permissions ensures exclusive control of the sudo configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_etc_sudoersd

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    find -H /etc/sudoers.d/ -maxdepth 0 -perm /u+s,g+ws,o+xwrt -type d -exec chmod u-s,g-ws,o-xwrt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_permissions_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/sudoers.d/ file(s)
      ansible.builtin.command: 'find -P /etc/sudoers.d/ -maxdepth 0 -perm /u+s,g+ws,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/sudoers.d/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-ws,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_sudoersd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/sudoers File [ref]

To properly set the group owner of `/etc/sudoers`, run the command:

    $ sudo chgrp root /etc/sudoers

Rationale: | The ownership of the /etc/sudoers file by the root group is important because this file hosts sudo configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the sudo configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_sudoers

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/sudoers" | grep -E -w -q "root"; then
        chgrp --no-dereference "$newgroup" /etc/sudoers
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_groupowner_etc_sudoers_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_etc_sudoers_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_etc_sudoers_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/sudoers
      ansible.builtin.stat:
        path: /etc/sudoers
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/sudoers
      ansible.builtin.file:
        path: /etc/sudoers
        follow: false
        group: '{{ file_groupowner_etc_sudoers_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/sudoers File [ref]

To properly set the owner of `/etc/sudoers`, run the command:

    $ sudo chown root /etc/sudoers

Rationale: | The ownership of the /etc/sudoers file by the root user is important because this file hosts sudo configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the sudo configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_sudoers

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/sudoers" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/sudoers
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_etc_sudoers_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_sudoers_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/sudoers
      ansible.builtin.stat:
        path: /etc/sudoers
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/sudoers
      ansible.builtin.file:
        path: /etc/sudoers
        follow: false
        owner: '{{ file_owner_etc_sudoers_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/sudoers File [ref]

To properly set the permissions of `/etc/sudoers`, run the command:

    $ sudo chmod 0440 /etc/sudoers

Rationale: | Setting correct permissions on the /etc/sudoers file is important because this file hosts sudo configuration. Protection of this file is critical for system security. Restricting the permissions ensures exclusive control of the sudo configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_sudoers

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xws,g-xws,o-xwrt /etc/sudoers

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/sudoers
      ansible.builtin.stat:
        path: /etc/sudoers
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xws,g-xws,o-xwrt on /etc/sudoers
      ansible.builtin.file:
        path: /etc/sudoers
        mode: u-xws,g-xws,o-xwrt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_sudoers
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure That the sudo Binary Has the Correct Permissions [ref]

To properly set the permissions of `/usr/bin/sudo`, run the command:

    $ sudo chmod 4110 /usr/bin/sudo

In order to use this rule, the group owner for /usr/bin/sudo needs to be changed to a group other than root to effectively limit access to sudo.

Rationale: | The sudoers program should only be usable by people who have the correct permissions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_sudo

References:

anssi | R38

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'sudo' 2>/dev/null | grep -q '^installed$'; }; then

    chmod 4110 /usr/bin/sudo

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /usr/bin/sudo
      ansible.builtin.stat:
        path: /usr/bin/sudo
      register: file_exists
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission 4110 on /usr/bin/sudo
      ansible.builtin.file:
        path: /usr/bin/sudo
        mode: '4110'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_sudo
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure sudo Runs In A Minimal Environment - sudo env_reset [ref]

The sudo `env_reset` tag, when specified, will run the command in a minimal environment, containing the TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER and SUDO_* variables. This should be enabled by making sure that the `env_reset` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | Forcing sudo to reset the environment ensures that environment variables are not passed on to the command accidentally, preventing leak of potentially sensitive information.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_add_env_reset

References:

anssi | R39

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults\b[^!\n]*\benv_reset.*$' /etc/sudoers; then
            # sudoers file doesn't define Option env_reset
            echo "Defaults env_reset" >> /etc/sudoers
        fi

        # Check validity of sudoers and cleanup bak
        if /usr/sbin/visudo -qcf /etc/sudoers; then
            rm -f /etc/sudoers.bak
        else
            echo "Fail to validate remediated /etc/sudoers, reverting to original file."
            mv /etc/sudoers.bak /etc/sudoers
            false
        fi
    else
        echo "Skipping remediation, /etc/sudoers failed to validate"
        false
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_env_reset

    - name: Ensure env_reset is enabled in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults.*\benv_reset\b.*$
        line: Defaults env_reset
        validate: /usr/sbin/visudo -cf %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_env_reset

#### Rule Ensure sudo Ignores Commands In Current Dir - sudo ignore_dot [ref]

The sudo `ignore_dot` tag, when specified, will ignore the current directory in the PATH environment variable. This should be enabled by making sure that the `ignore_dot` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | Ignoring the commands in the user's current directory prevents an attacker from executing commands downloaded locally.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_add_ignore_dot

References:

anssi | R39

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults\b[^!\n]*\bignore_dot.*$' /etc/sudoers; then
            # sudoers file doesn't define Option ignore_dot
            echo "Defaults ignore_dot" >> /etc/sudoers
        fi

        # Check validity of sudoers and cleanup bak
        if /usr/sbin/visudo -qcf /etc/sudoers; then
            rm -f /etc/sudoers.bak
        else
            echo "Fail to validate remediated /etc/sudoers, reverting to original file."
            mv /etc/sudoers.bak /etc/sudoers
            false
        fi
    else
        echo "Skipping remediation, /etc/sudoers failed to validate"
        false
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_ignore_dot

    - name: Ensure ignore_dot is enabled in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults.*\bignore_dot\b.*$
        line: Defaults ignore_dot
        validate: /usr/sbin/visudo -cf %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_ignore_dot

#### Rule Ensure Privileged Escalated Commands Cannot Execute Other Commands - sudo NOEXEC [ref]

The sudo `NOEXEC` tag, when specified, prevents user executed commands from executing other commands, like a shell for example. This should be enabled by making sure that the `NOEXEC` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | Restricting the capability of sudo allowed commands to execute sub-commands prevents users from running programs with privileges they wouldn't have otherwise.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_add_noexec

References:

anssi | R39

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults\b[^!\n]*\bnoexec.*$' /etc/sudoers; then
            # sudoers file doesn't define Option noexec
            echo "Defaults noexec" >> /etc/sudoers
        fi

        # Check validity of sudoers and cleanup bak
        if /usr/sbin/visudo -qcf /etc/sudoers; then
            rm -f /etc/sudoers.bak
        else
            echo "Fail to validate remediated /etc/sudoers, reverting to original file."
            mv /etc/sudoers.bak /etc/sudoers
            false
        fi
    else
        echo "Skipping remediation, /etc/sudoers failed to validate"
        false
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_noexec

    - name: Ensure noexec is enabled in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults.*\bnoexec\b.*$
        line: Defaults noexec
        validate: /usr/sbin/visudo -cf %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_noexec

#### Rule Ensure Only Users Logged In To Real tty Can Execute Sudo - sudo requiretty [ref]

The sudo `requiretty` tag, when specified, will only execute sudo commands from users logged in to a real tty. This should be enabled by making sure that the `requiretty` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | Restricting the use cases in which a user is allowed to execute sudo commands reduces the attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_add_requiretty

References:

anssi | R39

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults\b[^!\n]*\brequiretty.*$' /etc/sudoers; then
            # sudoers file doesn't define Option requiretty
            echo "Defaults requiretty" >> /etc/sudoers
        fi

        # Check validity of sudoers and cleanup bak
        if /usr/sbin/visudo -qcf /etc/sudoers; then
            rm -f /etc/sudoers.bak
        else
            echo "Fail to validate remediated /etc/sudoers, reverting to original file."
            mv /etc/sudoers.bak /etc/sudoers
            false
        fi
    else
        echo "Skipping remediation, /etc/sudoers failed to validate"
        false
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_requiretty

    - name: Ensure requiretty is enabled in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults.*\brequiretty\b.*$
        line: Defaults requiretty
        validate: /usr/sbin/visudo -cf %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_requiretty

#### Rule Ensure sudo umask is appropriate - sudo umask [ref]

The sudo `umask` tag, when specified, will be added the to the user's umask in the command environment. The umask should be configured by making sure that the `umask=0077` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | The umask value influences the permissions assigned to files when they are created. A misconfigured umask value could result in files with excessive permissions that can be read or written to by unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_add_umask

References:

anssi | R39

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    var_sudo_umask='0077'

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults\b[^!\n]*\bumask=\w+\b.*$' /etc/sudoers; then
            # sudoers file doesn't define Option umask
            echo "Defaults umask=${var_sudo_umask}" >> /etc/sudoers
        else
            # sudoers file defines Option umask, remediate if appropriate value is not set
            if ! grep -P "^[\s]*Defaults.*\bumask=${var_sudo_umask}\b.*$" /etc/sudoers; then

                escaped_variable=${var_sudo_umask//$'/'/$'\/'}
                sed -Ei "s/(^[\s]*Defaults.*\bumask=)[-]?.+(\b.*$)/\1$escaped_variable\2/" /etc/sudoers
            fi
        fi

        # Check validity of sudoers and cleanup bak
        if /usr/sbin/visudo -qcf /etc/sudoers; then
            rm -f /etc/sudoers.bak
        else
            echo "Fail to validate remediated /etc/sudoers, reverting to original file."
            mv /etc/sudoers.bak /etc/sudoers
            false
        fi
    else
        echo "Skipping remediation, /etc/sudoers failed to validate"
        false
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_umask
    - name: XCCDF Value var_sudo_umask # promote to variable
      set_fact:
        var_sudo_umask: !!str 0077
      tags:
        - always

    - name: Ensure umask is enabled with the appropriate value in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults\s(.*)\bumask=[-]?.+\b(.*)$
        line: Defaults \1umask={{ var_sudo_umask }}\2
        validate: /usr/sbin/visudo -cf %s
        backrefs: true
      register: edit_sudoers_umask_option
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_umask

    - name: Enable umask option with appropriate value in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        line: Defaults umask={{ var_sudo_umask }}
        validate: /usr/sbin/visudo -cf %s
      when:
      - '"linux-base" in ansible_facts.packages'
      - edit_sudoers_umask_option is defined and not edit_sudoers_umask_option.changed
      tags:
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_umask

#### Rule Ensure Only Users Logged In To Real tty Can Execute Sudo - sudo use_pty [ref]

The sudo `use_pty` tag, when specified, will only execute sudo commands from users logged in to a real tty. This should be enabled by making sure that the `use_pty` tag exists in `/etc/sudoers` configuration file or any sudo configuration snippets in `/etc/sudoers.d/`.
Rationale: | Requiring that sudo commands be run in a pseudo-terminal can prevent an attacker from retaining access to the user's terminal after the main program has finished executing.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_add_use_pty

References:

pcidss | Req-10.2.5
anssi | R39
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'sudo' 2>/dev/null | grep -q '^installed$'; }; then

    if /usr/sbin/visudo -qcf /etc/sudoers; then
        cp /etc/sudoers /etc/sudoers.bak
        if ! grep -P '^[\s]*Defaults\b[^!\n]*\buse_pty.*$' /etc/sudoers; then
            # sudoers file doesn't define Option use_pty
            echo "Defaults use_pty" >> /etc/sudoers
        fi

        # Check validity of sudoers and cleanup bak
        if /usr/sbin/visudo -qcf /etc/sudoers; then
            rm -f /etc/sudoers.bak
        else
            echo "Fail to validate remediated /etc/sudoers, reverting to original file."
            mv /etc/sudoers.bak /etc/sudoers
            false
        fi
    else
        echo "Skipping remediation, /etc/sudoers failed to validate"
        false
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_use_pty

    - name: Ensure use_pty is enabled in /etc/sudoers
      ansible.builtin.lineinfile:
        path: /etc/sudoers
        regexp: ^[\s]*Defaults.*\buse_pty\b.*$
        line: Defaults use_pty
        validate: /usr/sbin/visudo -cf %s
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"sudo" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sudo_add_use_pty

#### Rule Ensure a dedicated group owns sudo [ref]

Restrict the execution of privilege escalated commands to a dedicated group of users. Ensure the group owner of /usr/bin/sudo is sudogrp.
Warning: Changing group owner of `/usr/bin/sudo` to a group with no member users will prevent any and all escalatation of privileges. Additionally, the system may become unmanageable if root logins are not allowed.
Warning: This rule doesn't come with a remediation, before remediating the sysadmin needs to add users to the dedicated sudo group.

Rationale: | Restricting the set of users able to execute commands as privileged user reduces the attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudo_dedicated_group

References:

anssi | R38

#### Rule Explicit arguments in sudo specifications [ref]

All commands in the sudoers file must strictly specify the arguments allowed to be used for a given user. If the command is supposed to be executed only without arguments, pass "" as an argument in the corresponding user specification.
Warning: This rule doesn't come with a remediation, as absence of arguments in the user spec doesn't mean that the command is intended to be executed with no arguments.
Warning: The rule can produce false findings when an argument contains a comma - sudoers syntax allows comma escaping using backslash, but the check doesn't support that. For example, `root ALL=(ALL) echo 1\,2` allows root to execute `echo 1,2`, but the check would interpret it as two commands `echo 1\` and `2`.

Rationale:

Any argument can modify quite significantly the behavior of a program, whether regarding the realized operation (read, write, delete, etc.) or accessed resources (path in a file system tree). To avoid any possibility of misuse of a command by a user, the ambiguities must be removed at the level of its specification. For example, on some systems, the kernel messages are only accessible by root. If a user nevertheless must have the privileges to read them, the argument of the dmesg command has to be restricted in order to prevent the user from flushing the buffer through the -c option:

    user ALL = dmesg ""

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudoers_explicit_command_args

References:

anssi | R43

#### Rule Don't define allowed commands in sudoers by means of exclusion [ref]

Policies applied by sudo through the sudoers file should not involve negation. Each user specification in the `sudoers` file contains a comma-delimited list of command specifications. The definition can make use glob patterns, as well as of negations. Indirect definition of those commands by means of exclusion of a set of commands is trivial to bypass, so it is not allowed to use such constructs.
Warning: This rule doesn't come with a remediation, as negations indicate design issues with the sudoers user specifications design. Just removing negations doesn't increase the security - you typically have to rethink the definition of allowed commands to fix the issue.

Rationale:

Specifying access right using negation is inefficient and can be easily circumvented. For example, it is expected that a specification like

    # To avoid absolutely , this rule can be easily circumvented!
    user ALL = ALL ,!/ bin/sh

prevents the execution of the shell but that’s not the case: just copy the binary `/bin/sh` to a different name to make it executable again through the rule keyword `ALL`.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudoers_no_command_negation

References:

anssi | R42

#### Rule Don't target root user in the sudoers file [ref]

The targeted users of a user specification should be, as much as possible, non privileged users (i.e.: non-root). User specifications have to explicitly list the runas spec (i.e. the list of target users that can be impersonated), and `ALL` or `root` should not be used.
Warning: This rule doesn't come with a remediation, as the exact requirement allows exceptions, and removing lines from the sudoers file can make the system non-administrable.

Rationale: | It is common that the command to be executed does not require superuser rights (editing a file whose the owner is not root, sending a signal to an unprivileged process,etc.). In order to limit any attempt of privilege escalation through a command, it is better to apply normal user rights.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sudoers_no_root_target

References:

anssi | R40

Group Updating Software Group contains 1 rule

[ref] The `apt_get` command line tool is used to install and update software packages. The system also provides a graphical software update tool in the System menu, in the Administration submenu, called Software Update.
Debian 13 systems contain an installed software catalog called the RPM database, which records metadata of installed packages. Consistently using `apt_get` or the graphical Software Update for all software installation allows for insight into the current inventory of installed software on the system.

#### Rule Ensure Software Patches Installed [ref]

If the system has an apt repository available, run the following command to install updates:

    $ apt update && apt full-upgrade

NOTE: U.S. Defense systems are required to be patched within 30 days or sooner as local policy dictates.
Warning: The OVAL feed of Debian 13 is not a XML file, which may not be understood by all scanners.

Rationale: | Installing software updates is a fundamental mitigation against the exploitation of publicly-known vulnerabilities. If the most recent security patches and updates are not installed, unauthorized users may take advantage of weaknesses in the unpatched software. The lack of prompt attention to patching could result in a system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_security_patches_up_to_date

References:

cis-csc | 18, 20, 4
cjis | 5.10.4.1
cobit5 | APO12.01, APO12.02, APO12.03, APO12.04, BAI03.10, DSS05.01, DSS05.02
isa-62443-2009 | 4.2.3, 4.2.3.12, 4.2.3.7, 4.2.3.9
iso27001-2013 | A.12.6.1, A.14.2.3, A.16.1.3, A.18.2.2, A.18.2.3
nist | SI-2(5), SI-2(c), CM-6(a)
nist-csf | ID.RA-1, PR.IP-12
ospp | FMT_MOF_EXT.1
pcidss | Req-6.2
os-srg | SRG-OS-000480-GPOS-00227
anssi | R61
ism | 1409
pcidss4 | 6.3.3, 6.3

#### Rule Prefer to use a 64-bit Operating System when supported [ref]

Prefer installation of 64-bit operating systems when the CPU supports it. Warning: There is no remediation besides installing a 64-bit operating system.
Rationale: | Use of a 64-bit operating system offers a few advantages, like a larger address space range for Address Space Layout Randomization (ASLR) and systematic presence of No eXecute and Execute Disable (NX/XD) protection bits.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_prefer_64bit_os

References:

anssi | R1

Group Account and Access Control Group contains 12 groups and 28 rules

[ref] In traditional Unix security, if an attacker gains shell access to a certain login account, they can perform any action or access any file to which that account has access. Therefore, making it more difficult for unauthorized people to gain shell access to accounts, particularly to privileged accounts, is a necessary part of securing a system. This section introduces mechanisms for restricting access to accounts under Debian 13.

Group Protect Accounts by Configuring PAM Group contains 4 groups and 14 rules

[ref] PAM, or Pluggable Authentication Modules, is a system which implements modular authentication for Linux programs. PAM provides a flexible and configurable architecture for authentication, and it should be configured to minimize exposure to unnecessary risk. This section contains guidance on how to accomplish that.
PAM is implemented as a set of shared objects which are loaded and invoked whenever an application wishes to authenticate a user. Typically, the application must be running as root in order to take advantage of PAM, because PAM's modules often need to be able to access sensitive stores of account information, such as /etc/shadow. Traditional privileged network listeners (e.g. sshd) or SUID programs (e.g. sudo) already meet this requirement. An SUID root application, userhelper, is provided so that programs which are not SUID or privileged themselves can still take advantage of PAM.
PAM looks in the directory `/etc/pam.d` for application-specific configuration information. For instance, if the program login attempts to authenticate a user, then PAM's libraries follow the instructions in the file `/etc/pam.d/login` to determine what actions should be taken.
One very important file in `/etc/pam.d` is `/etc/pam.d/system-auth`. This file, which is included by many other PAM configuration files, defines 'default' system authentication measures. Modifying this file is a good way to make far-reaching authentication changes, for instance when implementing a centralized authentication service.
Warning: Be careful when making changes to PAM's configuration files. The syntax for these files is complex, and modifications can have unexpected consequences. The default configurations shipped with applications should be sufficient for most users.
Warning: Running `authconfig` or `system-config-authentication` will re-write the PAM configuration files, destroying any manually made changes and replacing them with a series of system defaults. One reference to the configuration file syntax can be found at https://fossies.org/linux/Linux-PAM-docs/doc/sag/Linux-PAM_SAG.pdf.

Group Set Lockouts for Failed Password Attempts Group contains 5 rules

[ref] The `pam_faillock` PAM module provides the capability to lock out user accounts after a number of failed login attempts. Its documentation is available in `/usr/share/doc/pam-VERSION/txts/README.pam_faillock`.
Warning: Locking out user accounts presents the risk of a denial-of-service attack. The lockout policy must weigh whether the risk of such a denial-of-service attack outweighs the benefits of thwarting password guessing attacks.

#### Rule Limit Password Reuse [ref]

Do not allow users to reuse recent passwords. This can be accomplished by using the `remember` option for the `pam_unix` or `pam_pwhistory` PAM modules.
Warning: If the system relies on `authselect` tool to manage PAM settings, the remediation will also use `authselect` tool. However, if any manual modification was made in PAM files, the `authselect` integrity check will fail and the remediation will be aborted in order to preserve intentional changes. In this case, an informative message will be shown in the remediation report.
Warning: Newer versions of `authselect` contain an authselect feature to easily and properly enable `pam_pwhistory.so` module. If this feature is not yet available in your system, an authselect custom profile must be used to avoid integrity issues in PAM files.

Rationale: | Preventing reuse of previous passwords helps ensure that a compromised password is not reused by a user.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_unix_remember

References:

cis-csc | 1, 12, 15, 16, 5
cjis | 5.6.2.1.1
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.5.8
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(f), IA-5(1)(e)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
pcidss | Req-8.2.5
os-srg | SRG-OS-000077-GPOS-00045
anssi | R31
pcidss4 | 8.3.7, 8.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_unix_remember='2'

    if [ -e "/etc/pam.d/common-password" ] ; then
        valueRegex="$var_password_pam_unix_remember" defaultValue="$var_password_pam_unix_remember"
        # 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*(?"'!'"password\\s)[[:alnum:]]+\\s+[[:alnum:]]+\\s+pam_unix.so" < "/etc/pam.d/common-password" ; then
            sed --follow-symlinks -i -E -e "s/^(\\s*)[[:alnum:]]+(\\s+[[:alnum:]]+\\s+pam_unix.so)/\\1password\\2/" "/etc/pam.d/common-password"
        fi

        # fix 'control' if it's wrong
        if grep -q -P "^\\s*password\\s+(?"'!'"\[success=[[:alnum:]].*\])[[:alnum:]]+\\s+pam_unix.so" < "/etc/pam.d/common-password" ; then
            sed --follow-symlinks -i -E -e "s/^(\\s*password\\s+)[[:alnum:]]+(\\s+pam_unix.so)/\\1\[success=[[:alnum:]].*\]\\2/" "/etc/pam.d/common-password"
        fi

        # fix the value for 'option' if one exists but does not match 'valueRegex'
        if grep -q -P "^\\s*password\\s+\[success=[[:alnum:]].*\]\\s+pam_unix.so(\\s.+)?\\s+remember(?"'!'"${valueRegex}(\\s|\$))" < "/etc/pam.d/common-password" ; then
            sed --follow-symlinks -i -E -e "s/^(\\s*password\\s+\[success=[[:alnum:]].*\]\\s+pam_unix.so(\\s.+)?\\s)remember=[^[:space:]]*/\\1remember${defaultValue}/" "/etc/pam.d/common-password"

        # add 'option=default' if option is not set
        elif grep -q -E "^\\s*password\\s+\[success=[[:alnum:]].*\]\\s+pam_unix.so" < "/etc/pam.d/common-password" &&
                grep    -E "^\\s*password\\s+\[success=[[:alnum:]].*\]\\s+pam_unix.so" < "/etc/pam.d/common-password" | grep -q -E -v "\\sremember(=|\\s|\$)" ; then

            sed --follow-symlinks -i -E -e "s/^(\\s*password\\s+\[success=[[:alnum:]].*\]\\s+pam_unix.so[^\\n]*)/\\1 remember${defaultValue}/" "/etc/pam.d/common-password"
        # add a new entry if none exists
        elif ! grep -q -P "^\\s*password\\s+\[success=[[:alnum:]].*\]\\s+pam_unix.so(\\s.+)?\\s+remember${valueRegex}(\\s|\$)" < "/etc/pam.d/common-password" ; then
            echo "password \[success=[[:alnum:]].*\] pam_unix.so remember${defaultValue}" >> "/etc/pam.d/common-password"
        fi
    else
        echo "/etc/pam.d/common-password doesn't exist" >&2
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.6.2.1.1
      - NIST-800-171-3.5.8
      - NIST-800-53-IA-5(1)(e)
      - NIST-800-53-IA-5(f)
      - PCI-DSS-Req-8.2.5
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.7
      - accounts_password_pam_unix_remember
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_password_pam_unix_remember # promote to variable
      set_fact:
        var_password_pam_unix_remember: !!str 2
      tags:
        - always

    - name: Limit Password Reuse - Check if the required PAM module option is present
        in /etc/pam.d/common-password
      ansible.builtin.lineinfile:
        path: /etc/pam.d/common-password
        regexp: ^\s*password\s+\[success=[A-Za-z0-9].*\]\s+pam_unix.so\s*.*\sremember\b
        state: absent
      check_mode: true
      changed_when: false
      register: result_pam_module_remember_option_present
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - NIST-800-171-3.5.8
      - NIST-800-53-IA-5(1)(e)
      - NIST-800-53-IA-5(f)
      - PCI-DSS-Req-8.2.5
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.7
      - accounts_password_pam_unix_remember
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Limit Password Reuse - Ensure the "remember" PAM option for "pam_unix.so"
        is included in /etc/pam.d/common-password
      ansible.builtin.lineinfile:
        path: /etc/pam.d/common-password
        backrefs: true
        regexp: ^(\s*password\s+\[success=[A-Za-z0-9].*\]\s+pam_unix.so.*)
        line: \1 remember={{ var_password_pam_unix_remember }}
        state: present
      register: result_pam_remember_add
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      - result_pam_module_remember_option_present.found == 0
      tags:
      - CJIS-5.6.2.1.1
      - NIST-800-171-3.5.8
      - NIST-800-53-IA-5(1)(e)
      - NIST-800-53-IA-5(f)
      - PCI-DSS-Req-8.2.5
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.7
      - accounts_password_pam_unix_remember
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

    - name: Limit Password Reuse - Ensure the required value for "remember" PAM option
        from "pam_unix.so" in /etc/pam.d/common-password
      ansible.builtin.lineinfile:
        path: /etc/pam.d/common-password
        backrefs: true
        regexp: ^(\s*password\s+\[success=[A-Za-z0-9].*\]\s+pam_unix.so\s+.*)(remember)=[0-9a-zA-Z]+\s*(.*)
        line: \1\2={{ var_password_pam_unix_remember }} \3
      register: result_pam_remember_edit
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      - result_pam_module_remember_option_present.found > 0
      tags:
      - CJIS-5.6.2.1.1
      - NIST-800-171-3.5.8
      - NIST-800-53-IA-5(1)(e)
      - NIST-800-53-IA-5(f)
      - PCI-DSS-Req-8.2.5
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.7
      - accounts_password_pam_unix_remember
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Lock Accounts After Failed Password Attempts [ref]

This rule configures the system to lock out accounts after a number of incorrect login attempts using `pam_faillock.so`. pam_faillock.so module requires multiple entries in pam files. These entries must be carefully defined to work as expected. Ensure that the file `/etc/security/faillock.conf` contains the following entry: `deny = <count>` Where count should be less than or equal to 3 and greater than 0.
Warning: If the system relies on `authselect` tool to manage PAM settings, the remediation will also use `authselect` tool. However, if any manual modification was made in PAM files, the `authselect` integrity check will fail and the remediation will be aborted in order to preserve intentional changes. In this case, an informative message will be shown in the remediation report. If the system supports the `/etc/security/faillock.conf` file, the pam_faillock parameters should be defined in `faillock.conf` file.

Rationale: | By limiting the number of failed logon attempts, the risk of unauthorized system access via user password guessing, also known as brute-forcing, is reduced. Limits are imposed by locking the account.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_deny

References:

cis-csc | 1, 12, 15, 16
cjis | 5.5.3
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.8
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), AC-7(a)
nist-csf | PR.AC-7
ospp | FIA_AFL.1
pcidss | Req-8.1.6
os-srg | SRG-OS-000329-GPOS-00128, SRG-OS-000021-GPOS-00005
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.4, 8.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    var_accounts_passwords_pam_faillock_deny='3'

    if [ -f /usr/bin/authselect ]; then
        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
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

    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

    fi

    AUTH_FILES=("/etc/pam.d/common-auth")
    SKIP_FAILLOCK_CHECK=true

    FAILLOCK_CONF="/etc/security/faillock.conf"
    if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
        regex="^\s*deny\s*="
        line="deny = $var_accounts_passwords_pam_faillock_deny"
        if ! grep -q $regex $FAILLOCK_CONF; then
            echo $line >> $FAILLOCK_CONF
        else
            sed -i --follow-symlinks 's|^\s*\(deny\s*=\s*\)\(\S\+\)|\1'"$var_accounts_passwords_pam_faillock_deny"'|g' $FAILLOCK_CONF
        fi

        for pam_file in "${AUTH_FILES[@]}"
        do
            if [ -e "$pam_file" ] ; then
                PAM_FILE_PATH="$pam_file"
                if [ -f /usr/bin/authselect ]; then

                    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

                    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"

                        authselect apply-changes -b --backup=before-hardening-custom-profile
                        authselect select $CURRENT_PROFILE
                        for feature in $ENABLED_FEATURES; do
                            authselect enable-feature $feature;
                        done

                        authselect apply-changes -b --backup=after-hardening-custom-profile
                    fi
                    PAM_FILE_NAME=$(basename "$pam_file")
                    PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

                    authselect apply-changes -b
                fi

            if grep -qP "^\s*auth\s.*\bpam_faillock.so\s.*\bdeny\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\bdeny\b=?[[:alnum:]]*(.*)/\1\2/g" "$PAM_FILE_PATH"
            fi
                if [ -f /usr/bin/authselect ]; then

                    authselect apply-changes -b
                fi
            else
                echo "$pam_file was not found" >&2
            fi
        done

    else
        for pam_file in "${AUTH_FILES[@]}"
        do
            if ! grep -qE '^\s*auth.*pam_faillock\.so\s+(preauth|authfail).*deny' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ deny='"$var_accounts_passwords_pam_faillock_deny"'/' "$pam_file"
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ deny='"$var_accounts_passwords_pam_faillock_deny"'/' "$pam_file"
            else
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*\)\('"deny"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_deny"'\3/' "$pam_file"
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"deny"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_deny"'\3/' "$pam_file"
            fi
        done
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Configure the root Account for Failed Password Attempts [ref]

This rule configures the system to lock out the `root` account after a number of incorrect login attempts using `pam_faillock.so`. pam_faillock.so module requires multiple entries in pam files. These entries must be carefully defined to work as expected. In order to avoid errors when manually editing these files, it is recommended to use the appropriate tools, such as `authselect` or `authconfig`, depending on the OS version.
Warning: If the system relies on `authselect` tool to manage PAM settings, the remediation will also use `authselect` tool. However, if any manual modification was made in PAM files, the `authselect` integrity check will fail and the remediation will be aborted in order to preserve intentional changes. In this case, an informative message will be shown in the remediation report. If the system supports the `/etc/security/faillock.conf` file, the pam_faillock parameters should be defined in `faillock.conf` file.

Rationale: | By limiting the number of failed logon attempts, the risk of unauthorized system access via user password guessing, also known as brute-forcing, is reduced. Limits are imposed by locking the account.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_deny_root

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), AC-7(b), IA-5(c)
nist-csf | PR.AC-7
os-srg | SRG-OS-000329-GPOS-00128, SRG-OS-000021-GPOS-00005
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    if [ -f /usr/bin/authselect ]; then
        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
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

    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

    fi

    AUTH_FILES=("/etc/pam.d/common-auth")
    SKIP_FAILLOCK_CHECK=true

    FAILLOCK_CONF="/etc/security/faillock.conf"
    if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
        regex="^\s*even_deny_root"
        line="even_deny_root"
        if ! grep -q $regex $FAILLOCK_CONF; then
            echo $line >> $FAILLOCK_CONF
        fi

        for pam_file in "${AUTH_FILES[@]}"
        do
            if [ -e "$pam_file" ] ; then
                PAM_FILE_PATH="$pam_file"
                if [ -f /usr/bin/authselect ]; then

                    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

                    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"

                        authselect apply-changes -b --backup=before-hardening-custom-profile
                        authselect select $CURRENT_PROFILE
                        for feature in $ENABLED_FEATURES; do
                            authselect enable-feature $feature;
                        done

                        authselect apply-changes -b --backup=after-hardening-custom-profile
                    fi
                    PAM_FILE_NAME=$(basename "$pam_file")
                    PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

                    authselect apply-changes -b
                fi

            if grep -qP "^\s*auth\s.*\bpam_faillock.so\s.*\beven_deny_root\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\beven_deny_root\b=?[[:alnum:]]*(.*)/\1\2/g" "$PAM_FILE_PATH"
            fi
                if [ -f /usr/bin/authselect ]; then

                    authselect apply-changes -b
                fi
            else
                echo "$pam_file was not found" >&2
            fi
        done

    else
        for pam_file in "${AUTH_FILES[@]}"
        do
            if ! grep -qE '^\s*auth.*pam_faillock\.so\s+(preauth|authfail).*even_deny_root' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ even_deny_root/' "$pam_file"
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ even_deny_root/' "$pam_file"
            fi
        done
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Set Interval For Counting Failed Password Attempts [ref]

Utilizing `pam_faillock.so`, the `fail_interval` directive configures the system to lock out an account after a number of incorrect login attempts within a specified time period. Ensure that the file `/etc/security/faillock.conf` contains the following entry: `fail_interval = <interval-in-seconds>` where `interval-in-seconds` is `900` or greater.
Warning: If the system relies on `authselect` tool to manage PAM settings, the remediation will also use `authselect` tool. However, if any manual modification was made in PAM files, the `authselect` integrity check will fail and the remediation will be aborted in order to preserve intentional changes. In this case, an informative message will be shown in the remediation report. If the system supports the `/etc/security/faillock.conf` file, the pam_faillock parameters should be defined in `faillock.conf` file.

Rationale: | By limiting the number of failed logon attempts the risk of unauthorized system access via user password guessing, otherwise known as brute-forcing, is reduced. Limits are imposed by locking the account.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_interval

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), AC-7(a)
nist-csf | PR.AC-7
ospp | FIA_AFL.1
os-srg | SRG-OS-000329-GPOS-00128, SRG-OS-000021-GPOS-00005
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    var_accounts_passwords_pam_faillock_fail_interval='900'

    if [ -f /usr/bin/authselect ]; then
        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
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

    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

    fi

    AUTH_FILES=("/etc/pam.d/common-auth")
    SKIP_FAILLOCK_CHECK=true

    FAILLOCK_CONF="/etc/security/faillock.conf"
    if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
        regex="^\s*fail_interval\s*="
        line="fail_interval = $var_accounts_passwords_pam_faillock_fail_interval"
        if ! grep -q $regex $FAILLOCK_CONF; then
            echo $line >> $FAILLOCK_CONF
        else
            sed -i --follow-symlinks 's|^\s*\(fail_interval\s*=\s*\)\(\S\+\)|\1'"$var_accounts_passwords_pam_faillock_fail_interval"'|g' $FAILLOCK_CONF
        fi

        for pam_file in "${AUTH_FILES[@]}"
        do
            if [ -e "$pam_file" ] ; then
                PAM_FILE_PATH="$pam_file"
                if [ -f /usr/bin/authselect ]; then

                    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

                    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"

                        authselect apply-changes -b --backup=before-hardening-custom-profile
                        authselect select $CURRENT_PROFILE
                        for feature in $ENABLED_FEATURES; do
                            authselect enable-feature $feature;
                        done

                        authselect apply-changes -b --backup=after-hardening-custom-profile
                    fi
                    PAM_FILE_NAME=$(basename "$pam_file")
                    PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

                    authselect apply-changes -b
                fi

            if grep -qP "^\s*auth\s.*\bpam_faillock.so\s.*\bfail_interval\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\bfail_interval\b=?[[:alnum:]]*(.*)/\1\2/g" "$PAM_FILE_PATH"
            fi
                if [ -f /usr/bin/authselect ]; then

                    authselect apply-changes -b
                fi
            else
                echo "$pam_file was not found" >&2
            fi
        done

    else
        for pam_file in "${AUTH_FILES[@]}"
        do
            if ! grep -qE '^\s*auth.*pam_faillock\.so\s+(preauth|authfail).*fail_interval' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ fail_interval='"$var_accounts_passwords_pam_faillock_fail_interval"'/' "$pam_file"
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ fail_interval='"$var_accounts_passwords_pam_faillock_fail_interval"'/' "$pam_file"
            else
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*\)\('"fail_interval"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_fail_interval"'\3/' "$pam_file"
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"fail_interval"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_fail_interval"'\3/' "$pam_file"
            fi
        done
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Set Lockout Time for Failed Password Attempts [ref]

This rule configures the system to lock out accounts during a specified time period after a number of incorrect login attempts using `pam_faillock.so`. Ensure that the file `/etc/security/faillock.conf` contains the following entry: `unlock_time=<interval-in-seconds>` where `interval-in-seconds` is `900` or greater. pam_faillock.so module requires multiple entries in pam files. These entries must be carefully defined to work as expected. In order to avoid any errors when manually editing these files, it is recommended to use the appropriate tools, such as `authselect` or `authconfig`, depending on the OS version. If `unlock_time` is set to `0`, manual intervention by an administrator is required to unlock a user. This should be done using the `faillock` tool.
Warning: If the system supports the new `/etc/security/faillock.conf` file but the pam_faillock.so parameters are defined directly in `/etc/pam.d/system-auth` and `/etc/pam.d/password-auth`, the remediation will migrate the `unlock_time` parameter to `/etc/security/faillock.conf` to ensure compatibility with `authselect` tool. The parameters `deny` and `fail_interval`, if used, also have to be migrated by their respective remediation.
Warning: If the system relies on `authselect` tool to manage PAM settings, the remediation will also use `authselect` tool. However, if any manual modification was made in PAM files, the `authselect` integrity check will fail and the remediation will be aborted in order to preserve intentional changes. In this case, an informative message will be shown in the remediation report. If the system supports the `/etc/security/faillock.conf` file, the pam_faillock parameters should be defined in `faillock.conf` file.

Rationale: | By limiting the number of failed logon attempts the risk of unauthorized system access via user password guessing, otherwise known as brute-forcing, is reduced. Limits are imposed by locking the account.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_passwords_pam_faillock_unlock_time

References:

cis-csc | 1, 12, 15, 16
cjis | 5.5.3
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.8
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), AC-7(b)
nist-csf | PR.AC-7
ospp | FIA_AFL.1
pcidss | Req-8.1.7
os-srg | SRG-OS-000329-GPOS-00128, SRG-OS-000021-GPOS-00005
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.4, 8.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; }; then

    var_accounts_passwords_pam_faillock_unlock_time='900'

    if [ -f /usr/bin/authselect ]; then
        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
    authselect enable-feature with-faillock

    authselect apply-changes -b
    else

    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

    fi

    AUTH_FILES=("/etc/pam.d/common-auth")
    SKIP_FAILLOCK_CHECK=true

    FAILLOCK_CONF="/etc/security/faillock.conf"
    if [ -f $FAILLOCK_CONF ] || [ "$SKIP_FAILLOCK_CHECK" = "true" ]; then
        regex="^\s*unlock_time\s*="
        line="unlock_time = $var_accounts_passwords_pam_faillock_unlock_time"
        if ! grep -q $regex $FAILLOCK_CONF; then
            echo $line >> $FAILLOCK_CONF
        else
            sed -i --follow-symlinks 's|^\s*\(unlock_time\s*=\s*\)\(\S\+\)|\1'"$var_accounts_passwords_pam_faillock_unlock_time"'|g' $FAILLOCK_CONF
        fi

        for pam_file in "${AUTH_FILES[@]}"
        do
            if [ -e "$pam_file" ] ; then
                PAM_FILE_PATH="$pam_file"
                if [ -f /usr/bin/authselect ]; then

                    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

                    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"

                        authselect apply-changes -b --backup=before-hardening-custom-profile
                        authselect select $CURRENT_PROFILE
                        for feature in $ENABLED_FEATURES; do
                            authselect enable-feature $feature;
                        done

                        authselect apply-changes -b --backup=after-hardening-custom-profile
                    fi
                    PAM_FILE_NAME=$(basename "$pam_file")
                    PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

                    authselect apply-changes -b
                fi

            if grep -qP "^\s*auth\s.*\bpam_faillock.so\s.*\bunlock_time\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "s/(.*auth.*pam_faillock.so.*)\bunlock_time\b=?[[:alnum:]]*(.*)/\1\2/g" "$PAM_FILE_PATH"
            fi
                if [ -f /usr/bin/authselect ]; then

                    authselect apply-changes -b
                fi
            else
                echo "$pam_file was not found" >&2
            fi
        done

    else
        for pam_file in "${AUTH_FILES[@]}"
        do
            if ! grep -qE '^\s*auth.*pam_faillock\.so\s+(preauth|authfail).*unlock_time' "$pam_file"; then
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*preauth.*/ s/$/ unlock_time='"$var_accounts_passwords_pam_faillock_unlock_time"'/' "$pam_file"
                sed -i --follow-symlinks '/^auth.*required.*pam_faillock\.so.*authfail.*/ s/$/ unlock_time='"$var_accounts_passwords_pam_faillock_unlock_time"'/' "$pam_file"
            else
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*preauth.*\)\('"unlock_time"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_unlock_time"'\3/' "$pam_file"
                sed -i --follow-symlinks 's/\(^auth.*required.*pam_faillock\.so.*authfail.*\)\('"unlock_time"'=\)\S\+\b\(.*\)/\1\2'"$var_accounts_passwords_pam_faillock_unlock_time"'\3/' "$pam_file"
            fi
        done
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Group Set Password Quality Requirements Group contains 1 group and 7 rules

[ref] The default `pam_pwquality` PAM module provides strength checking for passwords. It performs a number of checks, such as making sure passwords are not similar to dictionary words, are of at least a certain length, are not the previous password reversed, and are not simply a change of case from the previous password. It can also require passwords to be in certain character classes. The `pam_pwquality` module is the preferred way of configuring password requirements.
The man pages `pam_pwquality(8)` provide information on the capabilities and configuration of each.

Group Set Password Quality Requirements with pam_pwquality Group contains 7 rules

[ref] The `pam_pwquality` PAM module can be configured to meet requirements for a variety of policies.
For example, to configure `pam_pwquality` to require at least one uppercase character, lowercase character, digit, and other (special) character, make sure that `pam_pwquality` exists in `/etc/pam.d/system-auth`:

    password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=

If no such line exists, add one as the first line of the password section in `/etc/pam.d/system-auth`. Next, modify the settings in `/etc/security/pwquality.conf` to match the following:

    difok = 4
    minlen = 14
    dcredit = -1
    ucredit = -1
    lcredit = -1
    ocredit = -1
    maxrepeat = 3

The arguments can be modified to ensure compliance with your organization's security policy. Discussion of each parameter follows.

#### Rule Ensure PAM Enforces Password Requirements - Minimum Digit Characters [ref]

The pam_pwquality module's `dcredit` parameter controls requirements for usage of digits in a password. When set to a negative number, any password will be required to contain that many digits. When set to a positive number, pam_pwquality will grant +1 additional length credit for each digit. Modify the `dcredit` setting in `/etc/security/pwquality.conf` to require the use of a digit in passwords.

Rationale:

Use of a complex password helps to increase the time and resources required to compromise the password. Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks.
Password complexity is one factor of several that determines how long it takes to crack a password. The more complex the password, the greater the number of possible combinations that need to be tested before the password is compromised. Requiring digits makes password guessing attacks more difficult by ensuring a larger search space.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_dcredit

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
ospp | FMT_SMF_EXT.1
pcidss | Req-8.2.3
os-srg | SRG-OS-000071-GPOS-00039
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.6, 8.3

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_dcredit='-1'

    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

    # 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' <<< "^dcredit")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_password_pam_dcredit"

    # 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 "^dcredit\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^dcredit\\>.*/$escaped_formatted_output/gi" "/etc/security/pwquality.conf"
    else
        if [[ -s "/etc/security/pwquality.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/security/pwquality.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/security/pwquality.conf"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/security/pwquality.conf"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_dcredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_dcredit # promote to variable
      set_fact:
        var_password_pam_dcredit: !!str -1
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Digit Characters - Ensure
        PAM variable dcredit is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*dcredit
        line: dcredit = {{ var_password_pam_dcredit }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_dcredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Minimum Lowercase Characters [ref]

The pam_pwquality module's `lcredit` parameter controls requirements for usage of lowercase letters in a password. When set to a negative number, any password will be required to contain that many lowercase characters. When set to a positive number, pam_pwquality will grant +1 additional length credit for each lowercase character. Modify the `lcredit` setting in `/etc/security/pwquality.conf` to require the use of a lowercase character in passwords.

Rationale:

Use of a complex password helps to increase the time and resources required to compromise the password. Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks.
Password complexity is one factor of several that determines how long it takes to crack a password. The more complex the password, the greater the number of possible combinations that need to be tested before the password is compromised. Requiring a minimum number of lowercase characters makes password guessing attacks more difficult by ensuring a larger search space.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_lcredit

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
ospp | FMT_SMF_EXT.1
pcidss | Req-8.2.3
os-srg | SRG-OS-000070-GPOS-00038
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.6, 8.3

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_lcredit='-1'

    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

    # 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' <<< "^lcredit")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_password_pam_lcredit"

    # 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 "^lcredit\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^lcredit\\>.*/$escaped_formatted_output/gi" "/etc/security/pwquality.conf"
    else
        if [[ -s "/etc/security/pwquality.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/security/pwquality.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/security/pwquality.conf"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/security/pwquality.conf"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_lcredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_lcredit # promote to variable
      set_fact:
        var_password_pam_lcredit: !!str -1
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Lowercase Characters -
        Ensure PAM variable lcredit is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*lcredit
        line: lcredit = {{ var_password_pam_lcredit }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_lcredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Minimum Different Categories [ref]

The pam_pwquality module's `minclass` parameter controls requirements for usage of different character classes, or types, of character that must exist in a password before it is considered valid. For example, setting this value to three (3) requires that any password must have characters from at least three different categories in order to be approved. The default value is zero (0), meaning there are no required classes. There are four categories available:

    * Upper-case characters
    * Lower-case characters
    * Digits
    * Special characters (for example, punctuation)

Modify the `minclass` setting in `/etc/security/pwquality.conf` entry to require 4 differing categories of characters when changing passwords.

Rationale:

Use of a complex password helps to increase the time and resources required to compromise the password. Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks.
Password complexity is one factor of several that determines how long it takes to crack a password. The more complex the password, the greater the number of possible combinations that need to be tested before the password is compromised.
Requiring a minimum number of character categories makes password guessing attacks more difficult by ensuring a larger search space.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_minclass

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000072-GPOS-00040
anssi | R68
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_minclass='4'

    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

    # 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' <<< "^minclass")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_password_pam_minclass"

    # 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 "^minclass\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^minclass\\>.*/$escaped_formatted_output/gi" "/etc/security/pwquality.conf"
    else
        if [[ -s "/etc/security/pwquality.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/security/pwquality.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/security/pwquality.conf"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/security/pwquality.conf"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_minclass
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_minclass # promote to variable
      set_fact:
        var_password_pam_minclass: !!str 4
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Different Categories -
        Ensure PAM variable minclass is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*minclass
        line: minclass = {{ var_password_pam_minclass }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_minclass
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Minimum Length [ref]

The pam_pwquality module's `minlen` parameter controls requirements for minimum characters required in a password. Add `minlen=15` after pam_pwquality to set minimum password length requirements.

Rationale:

The shorter the password, the lower the number of possible combinations that need to be tested before the password is compromised.
Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks. Password length is one factor of several that helps to determine strength and how long it takes to crack a password. Use of more characters in a password helps to exponentially increase the time and/or resources required to compromise the password.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_minlen

References:

cis-csc | 1, 12, 15, 16, 5
cjis | 5.6.2.1.1
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
ospp | FMT_SMF_EXT.1
pcidss | Req-8.2.3
os-srg | SRG-OS-000078-GPOS-00046
anssi | R31, R68
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561
pcidss4 | 8.3.6, 8.3

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_minlen='15'

    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

    # 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' <<< "^minlen")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_password_pam_minlen"

    # 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 "^minlen\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^minlen\\>.*/$escaped_formatted_output/gi" "/etc/security/pwquality.conf"
    else
        if [[ -s "/etc/security/pwquality.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/security/pwquality.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/security/pwquality.conf"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/security/pwquality.conf"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.6.2.1.1
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_minlen
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_minlen # promote to variable
      set_fact:
        var_password_pam_minlen: !!str 15
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Length - Ensure PAM variable
        minlen is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*minlen
        line: minlen = {{ var_password_pam_minlen }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - CJIS-5.6.2.1.1
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - PCI-DSSv4-8.3
      - PCI-DSSv4-8.3.6
      - accounts_password_pam_minlen
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Minimum Special Characters [ref]

The pam_pwquality module's `ocredit=` parameter controls requirements for usage of special (or "other") characters in a password. When set to a negative number, any password will be required to contain that many special characters. When set to a positive number, pam_pwquality will grant +1 additional length credit for each special character. Modify the `ocredit` setting in `/etc/security/pwquality.conf` to equal -1 to require use of a special character in passwords.

Rationale:

Use of a complex password helps to increase the time and resources required to compromise the password. Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks.
Password complexity is one factor of several that determines how long it takes to crack a password. The more complex the password, the greater the number of possible combinations that need to be tested before the password is compromised. Requiring a minimum number of special characters makes password guessing attacks more difficult by ensuring a larger search space.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_ocredit

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000266-GPOS-00101
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_ocredit='-1'

    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

    # 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' <<< "^ocredit")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_password_pam_ocredit"

    # 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 "^ocredit\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^ocredit\\>.*/$escaped_formatted_output/gi" "/etc/security/pwquality.conf"
    else
        if [[ -s "/etc/security/pwquality.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/security/pwquality.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/security/pwquality.conf"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/security/pwquality.conf"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_ocredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_ocredit # promote to variable
      set_fact:
        var_password_pam_ocredit: !!str -1
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Special Characters - Ensure
        PAM variable ocredit is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*ocredit
        line: ocredit = {{ var_password_pam_ocredit }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - accounts_password_pam_ocredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure PAM Enforces Password Requirements - Authentication Retry Prompts Permitted Per-Session [ref]

To configure the number of retry prompts that are permitted per-session: Edit the `pam_pwquality.so` statement in `/etc/pam.d/common-password` to show `retry=3` , or a lower value if site policy is more restrictive. The profile requirement is a maximum of `retry=3` prompts per session.
Rationale: | Setting the password retry prompts that are permitted on a per-session basis to a low value requires some software, such as SSH, to re-connect. This can slow down and draw additional attention to some types of password-guessing attacks. Note that this is different from account lockout, which is provided by the pam_faillock module.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_retry

References:

cis-csc | 1, 11, 12, 15, 16, 3, 5, 9
cjis | 5.5.3
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), AC-7(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7, PR.IP-1
os-srg | SRG-OS-000069-GPOS-00037, SRG-OS-000480-GPOS-00227
anssi | R68

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_retry='3'

    if [ -e "/etc/pam.d/common-password" ] ; then
        valueRegex="$var_password_pam_retry" defaultValue="$var_password_pam_retry"
        # 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*(?"'!'"password\\s)[[:alnum:]]+\\s+[[:alnum:]]+\\s+pam_pwquality.so" < "/etc/pam.d/common-password" ; then
            sed --follow-symlinks -i -E -e "s/^(\\s*)[[:alnum:]]+(\\s+[[:alnum:]]+\\s+pam_pwquality.so)/\\1password\\2/" "/etc/pam.d/common-password"
        fi

        # fix 'control' if it's wrong
        if grep -q -P "^\\s*password\\s+(?"'!'"requisite)[[:alnum:]]+\\s+pam_pwquality.so" < "/etc/pam.d/common-password" ; then
            sed --follow-symlinks -i -E -e "s/^(\\s*password\\s+)[[:alnum:]]+(\\s+pam_pwquality.so)/\\1requisite\\2/" "/etc/pam.d/common-password"
        fi

        # fix the value for 'option' if one exists but does not match 'valueRegex'
        if grep -q -P "^\\s*password\\s+requisite\\s+pam_pwquality.so(\\s.+)?\\s+retry(?"'!'"${valueRegex}(\\s|\$))" < "/etc/pam.d/common-password" ; then
            sed --follow-symlinks -i -E -e "s/^(\\s*password\\s+requisite\\s+pam_pwquality.so(\\s.+)?\\s)retry=[^[:space:]]*/\\1retry${defaultValue}/" "/etc/pam.d/common-password"

        # add 'option=default' if option is not set
        elif grep -q -E "^\\s*password\\s+requisite\\s+pam_pwquality.so" < "/etc/pam.d/common-password" &&
                grep    -E "^\\s*password\\s+requisite\\s+pam_pwquality.so" < "/etc/pam.d/common-password" | grep -q -E -v "\\sretry(=|\\s|\$)" ; then

            sed --follow-symlinks -i -E -e "s/^(\\s*password\\s+requisite\\s+pam_pwquality.so[^\\n]*)/\\1 retry${defaultValue}/" "/etc/pam.d/common-password"
        # add a new entry if none exists
        elif ! grep -q -P "^\\s*password\\s+requisite\\s+pam_pwquality.so(\\s.+)?\\s+retry${valueRegex}(\\s|\$)" < "/etc/pam.d/common-password" ; then
            echo "password requisite pam_pwquality.so retry${defaultValue}" >> "/etc/pam.d/common-password"
        fi
    else
        echo "/etc/pam.d/common-password doesn't exist" >&2
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Ensure PAM Enforces Password Requirements - Minimum Uppercase Characters [ref]

The pam_pwquality module's `ucredit=` parameter controls requirements for usage of uppercase letters in a password. When set to a negative number, any password will be required to contain that many uppercase characters. When set to a positive number, pam_pwquality will grant +1 additional length credit for each uppercase character. Modify the `ucredit` setting in `/etc/security/pwquality.conf` to require the use of an uppercase character in passwords.

Rationale:

Use of a complex password helps to increase the time and resources required to compromise the password. Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks.
Password complexity is one factor of several that determines how long it takes to crack a password. The more complex the password, the greater the number of possible combinations that need to be tested before the password is compromised.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_ucredit

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(a), CM-6(a), IA-5(4)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
ospp | FMT_SMF_EXT.1
pcidss | Req-8.2.3
os-srg | SRG-OS-000069-GPOS-00037, SRG-OS-000070-GPOS-00038
anssi | R31
ism | 0421, 0422, 0974, 1173, 1401, 1504, 1505, 1546, 1557, 1558, 1559, 1560, 1561

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'libpwquality1' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_pam_ucredit='-1'

    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

    # 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' <<< "^ucredit")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$var_password_pam_ucredit"

    # 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 "^ucredit\\>" "/etc/security/pwquality.conf"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^ucredit\\>.*/$escaped_formatted_output/gi" "/etc/security/pwquality.conf"
    else
        if [[ -s "/etc/security/pwquality.conf" ]] && [[ -n "$(tail -c 1 -- "/etc/security/pwquality.conf" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/security/pwquality.conf"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/security/pwquality.conf"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - accounts_password_pam_ucredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_password_pam_ucredit # promote to variable
      set_fact:
        var_password_pam_ucredit: !!str -1
      tags:
        - always

    - name: Ensure PAM Enforces Password Requirements - Minimum Uppercase Characters -
        Ensure PAM variable ucredit is set accordingly
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/security/pwquality.conf
        regexp: ^#?\s*ucredit
        line: ucredit = {{ var_password_pam_ucredit }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"libpwquality1" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(1)(a)
      - NIST-800-53-IA-5(4)
      - NIST-800-53-IA-5(c)
      - PCI-DSS-Req-8.2.3
      - accounts_password_pam_ucredit
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Set Password Hashing Algorithm Group contains 1 rule
[ref] The system's default algorithm for storing password hashes in `/etc/shadow` is SHA-512. This can be configured in several locations.

#### Rule Set Password Hashing Algorithm in /etc/login.defs [ref]

In `/etc/login.defs`, add or update the following line to ensure the system will use YESCRYPT as the hashing algorithm:

    ENCRYPT_METHOD YESCRYPT

Rationale:

Passwords need to be protected at all times, and encryption is the standard method for protecting passwords. If passwords are not encrypted, they can be plainly read (i.e., clear text) and easily compromised. Passwords that are encrypted with a weak algorithm are no more protected than if they are kept in plain text.
Using a stronger hashing algorithm makes password cracking attacks more difficult.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_set_password_hashing_algorithm_logindefs

References:

cis-csc | 1, 12, 15, 16, 5
cjis | 5.6.2.2
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.13.11
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-5(c), IA-5(1)(c), CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
pcidss | Req-8.2.1
os-srg | SRG-OS-000073-GPOS-00041
ism | 0418, 1055, 1402
pcidss4 | 8.3.2, 8.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'login' 2>/dev/null | grep -q '^installed$'; }; then

    var_password_hashing_algorithm='YESCRYPT'

    # Allow multiple algorithms, but choose the first one for remediation
    #
    var_password_hashing_algorithm="$(echo $var_password_hashing_algorithm | cut -d \| -f 1)"

    # 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' <<< "^ENCRYPT_METHOD")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s %s" "$stripped_key" "$var_password_hashing_algorithm"

    # 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 "^ENCRYPT_METHOD\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^ENCRYPT_METHOD\\>.*/$escaped_formatted_output/gi" "/etc/login.defs"
    else
        if [[ -s "/etc/login.defs" ]] && [[ -n "$(tail -c 1 -- "/etc/login.defs" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/login.defs"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/login.defs"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Install pam_pwquality Package [ref]

The `libpam-pwquality` package can be installed with the following command:

    $ apt-get install libpam-pwquality

Rationale: | Use of a complex password helps to increase the time and resources required to compromise the password. Password complexity, or strength, is a measure of the effectiveness of a password in resisting attempts at guessing and brute-force attacks. "pwquality" enforces complex password construction configuration and has the ability to limit brute-force attacks on the system.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_pam_pwquality_installed

References:

os-srg | SRG-OS-000480-GPOS-00225

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "libpam-pwquality"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_libpam-pwquality

    class install_libpam-pwquality {
      package { 'libpam-pwquality':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_pam_pwquality_installed

    - name: Ensure libpam-pwquality is installed
      ansible.builtin.package:
        name: libpam-pwquality
        state: present
      when: '"libpam-runtime" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_pam_pwquality_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "libpam-pwquality"
    version = "*"

Group Protect Physical Console Access Group contains 1 rule
[ref] It is impossible to fully protect a system from an attacker with physical access, so securing the space in which the system is located should be considered a necessary step. However, there are some steps which, if taken, make it more difficult for an attacker to quickly or undetectably modify a system from its console.

#### Rule Configure Logind to terminate idle sessions after certain time of inactivity [ref]

To configure `logind` service to terminate inactive user sessions after 600 seconds, edit the file `/etc/systemd/logind.conf`. Ensure that there is a section

    [Login]

which contains the configuration

    StopIdleSessionSec=600

.

Rationale: | Terminating an idle session within a short time period reduces the window of opportunity for unauthorized personnel to take control of a management session enabled on the console or console port that has been let unattended.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_logind_session_timeout

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 3, 5, 7, 8
cjis | 5.5.6
cobit5 | APO13.01, BAI03.01, BAI03.02, BAI03.03, DSS01.03, DSS03.05, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.1.11
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.3, A.14.1.1, A.14.2.1, A.14.2.5, A.18.1.4, A.6.1.2, A.6.1.5, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.3, CIP-007-3 R5.1, CIP-007-3 R5.2, CIP-007-3 R5.3.1, CIP-007-3 R5.3.2, CIP-007-3 R5.3.3
nist | CM-6(a), AC-17(a), AC-2(5), AC-12, AC-17(a), SC-10, CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.IP-2
ospp | FMT_SMF_EXT.1.1
pcidss | Req-8.1.8
os-srg | SRG-OS-000163-GPOS-00072
anssi | R32

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ( grep -qP "^ID=[\"']?rhel[\"']?$" "/etc/os-release" && { real="$(grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" /etc/os-release | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/")"; expected="8.7"; printf "%s\n%s" "$expected" "$real" | sort -VC; } && grep -qP "^ID=[\"']?rhel[\"']?$" "/etc/os-release" && { real="$(grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" /etc/os-release | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/")"; expected="9.0"; [[ "$real" != "$expected" ]]; } ) || grep -qP "^ID=[\"']?ol[\"']?$" "/etc/os-release" && { real="$(grep -P "^VERSION_ID=[\"']?[\w.]+[\"']?$" /etc/os-release | sed "s/^VERSION_ID=[\"']\?\([^\"']\+\)[\"']\?$/\1/")"; expected="8.7"; printf "%s\n%s" "$expected" "$real" | sort -VC; }; }; then

    var_logind_session_timeout='600'

    # Try find '[Login]' and 'StopIdleSessionSec' in '/etc/systemd/logind.conf', if it exists, set
    # to '$var_logind_session_timeout', if it isn't here, add it, if '[Login]' doesn't exist, add it there
    if grep -qzosP '[[:space:]]*\[Login]([^\n\[]*\n+)+?[[:space:]]*StopIdleSessionSec' '/etc/systemd/logind.conf'; then

        sed -i "s/StopIdleSessionSec[^(\n)]*/StopIdleSessionSec=$var_logind_session_timeout/" '/etc/systemd/logind.conf'
    elif grep -qs '[[:space:]]*\[Login]' '/etc/systemd/logind.conf'; then
        sed -i "/[[:space:]]*\[Login]/a StopIdleSessionSec=$var_logind_session_timeout" '/etc/systemd/logind.conf'
    else
        if test -d "/etc/systemd"; then
            printf '%s\n' '[Login]' "StopIdleSessionSec=$var_logind_session_timeout" >> '/etc/systemd/logind.conf'
        else
            echo "Config file directory '/etc/systemd' doesnt exist, not remediating, assuming non-applicability." >&2
        fi
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.6
      - NIST-800-171-3.1.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSS-Req-8.1.8
      - logind_session_timeout
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_logind_session_timeout # promote to variable
      set_fact:
        var_logind_session_timeout: !!str 600
      tags:
        - always

    - name: Set 'StopIdleSessionSec' to '{{ var_logind_session_timeout }}' in the [Login]
        section of '/etc/systemd/logind.conf'
      community.general.ini_file:
        path: /etc/systemd/logind.conf
        section: Login
        option: StopIdleSessionSec
        value: '{{ var_logind_session_timeout }}'
        create: true
        mode: 420
      when:
      - '"linux-base" in ansible_facts.packages'
      - ( ansible_distribution == 'RedHat' and ansible_distribution_version is version('8.7',
        '>=') and ansible_distribution == 'RedHat' and ansible_distribution_version is
        version('9.0', '!=') ) or ansible_distribution == 'OracleLinux' and ansible_distribution_version
        is version('8.7', '>=')
      tags:
      - CJIS-5.5.6
      - NIST-800-171-3.1.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSS-Req-8.1.8
      - logind_session_timeout
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

Group Protect Accounts by Restricting Password-Based Login Group contains 3 groups and 3 rules

[ref] Conventionally, Unix shell accounts are accessed by providing a username and password to a login program, which tests these values for correctness using the `/etc/passwd` and `/etc/shadow` files. Password-based login is vulnerable to guessing of weak passwords, and to sniffing and man-in-the-middle attacks against passwords entered over a network or at an insecure console. Therefore, mechanisms for accessing accounts by entering usernames and passwords should be restricted to those which are operationally necessary.

Group Set Password Expiration Parameters Group contains 1 rule

[ref] The file `/etc/login.defs` controls several password-related settings. Programs such as `passwd`, `su`, and `login` consult `/etc/login.defs` to determine behavior with regard to password aging, expiration warnings, and length. See the man page `login.defs(5)` for more information.
Users should be forced to change their passwords, in order to decrease the utility of compromised passwords. However, the need to change passwords often should be balanced against the risk that users will reuse or write down passwords if forced to change them too often. Forcing password changes every 90-360 days, depending on the environment, is recommended. Set the appropriate value as `PASS_MAX_DAYS` and apply it to existing accounts with the `-M` flag.
The `PASS_MIN_DAYS` (`-m`) setting prevents password changes for 7 days after the first change, to discourage password cycling. If you use this setting, train users to contact an administrator for an emergency password change in case a new password becomes compromised. The `PASS_WARN_AGE` (`-W`) setting gives users 7 days of warnings at login time that their passwords are about to expire.
For example, for each existing human user USER, expiration parameters could be adjusted to a 180 day maximum password age, 7 day minimum password age, and 7 day warning period with the following command:

    $ sudo chage -M 180 -m 7 -W 7 USER

#### Rule Set Root Account Password Maximum Age [ref]

Configure the root account to enforce a 365-day maximum password lifetime restriction by running the following command:

    $ sudo chage -M 365 root

Rationale: | Any password, no matter how complex, can eventually be cracked. Therefore, passwords need to be changed periodically. If the operating system does not limit the lifetime of passwords and force users to change their passwords, there is the risk that the operating system passwords could be compromised.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_set_max_life_root

References:

anssi | R31

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    var_accounts_maximum_age_root='365'

    chage -M $var_accounts_maximum_age_root root

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Group Verify Proper Storage and Existence of Password Hashes Group contains 1 rule

[ref] By default, password hashes for local accounts are stored in the second field (colon-separated) in `/etc/shadow`. This file should be readable only by processes running with root credentials, preventing users from casually accessing others' password hashes and attempting to crack them. However, it remains possible to misconfigure the system and store password hashes in world-readable files such as `/etc/passwd`, or to even store passwords themselves in plaintext on the system. Using system-provided tools for password change/creation should allow administrators to avoid such misconfiguration.

#### Rule Set number of Password Hashing Rounds - password-auth [ref]

Configure the number or rounds for the password hashing algorithm. This can be accomplished by using the `rounds` option for the `pam_unix` PAM module.
In file `/etc/pam.d/common-password` append `rounds=11` to the `pam_unix.so` entry, as shown below:

    password [success=1 default=ignore] pam_unix.so ...existing_options... rounds=11

Warning: Setting a high number of hashing rounds makes it more difficult to brute force the password, but requires more CPU resources to authenticate users.

Rationale: | Using a higher number of rounds makes password cracking attacks more difficult.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_password_pam_unix_rounds_password_auth

References:

os-srg | SRG-OS-000073-GPOS-00041
anssi | R68

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'libpam-runtime' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    var_password_pam_unix_rounds='11'

    if [ -e "/etc/pam.d/common-password" ] ; then
        PAM_FILE_PATH="/etc/pam.d/common-password"
        if [ -f /usr/bin/authselect ]; then

            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

            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"

                authselect apply-changes -b --backup=before-hardening-custom-profile
                authselect select $CURRENT_PROFILE
                for feature in $ENABLED_FEATURES; do
                    authselect enable-feature $feature;
                done

                authselect apply-changes -b --backup=after-hardening-custom-profile
            fi
            PAM_FILE_NAME=$(basename "/etc/pam.d/common-password")
            PAM_FILE_PATH="/etc/authselect/$CURRENT_PROFILE/$PAM_FILE_NAME"

            authselect apply-changes -b
        fi

            if ! grep -qP "^\s*password\s+\\[success=1 default=ignore\\]\s+pam_unix.so\s*.*" "$PAM_FILE_PATH"; then
                # Line matching group + control + module was not found. Check group + module.
                if [ "$(grep -cP '^\s*password\s+.*\s+pam_unix.so\s*' "$PAM_FILE_PATH")" -eq 1 ]; then
                    # The control is updated only if one single line matches.
                    sed -i -E --follow-symlinks "s/^(\s*password\s+).*(\bpam_unix.so.*)/\1\[success=1 default=ignore\] \2/" "$PAM_FILE_PATH"
                else
                    echo "password    \[success=1 default=ignore\]    pam_unix.so" >> "$PAM_FILE_PATH"
                fi
            fi
            # Check the option
            if ! grep -qP "^\s*password\s+\\[success=1 default=ignore\\]\s+pam_unix.so\s*.*\srounds\b" "$PAM_FILE_PATH"; then
                sed -i -E --follow-symlinks "/\s*password\s+\\[success=1 default=ignore\\]\s+pam_unix.so.*/ s/$/ rounds=$var_password_pam_unix_rounds/" "$PAM_FILE_PATH"
            else
                sed -i -E --follow-symlinks "s/(\s*password\s+\\[success=1 default=ignore\\]\s+pam_unix.so\s+.*)(rounds=)[[:alnum:]]*\s*(.*)/\1\2$var_password_pam_unix_rounds \3/" "$PAM_FILE_PATH"
            fi
        if [ -f /usr/bin/authselect ]; then

            authselect apply-changes -b
        fi
    else
        echo "/etc/pam.d/common-password was not found" >&2
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Group Restrict Root Logins Group contains 1 rule

[ref] Direct root logins should be allowed only for emergency use. In normal situations, the administrator should access the system via a unique unprivileged account, and then use `su` or `sudo` to execute privileged commands. Discouraging administrators from accessing the root account directly ensures an audit trail in organizations with multiple administrators. Locking down the channels through which root can connect directly also reduces opportunities for password-guessing against the root account. The `login` program uses the file `/etc/securetty` to determine which interfaces should allow root logins. The virtual devices `/dev/console` and `/dev/tty*` represent the system consoles (accessible via the Ctrl-Alt-F1 through Ctrl-Alt-F6 keyboard sequences on a default installation). The default securetty file also contains `/dev/vc/*`. These are likely to be deprecated in most environments, but may be retained for compatibility. Root should also be prohibited from connecting via network protocols. Other sections of this document include guidance describing how to prevent root from logging in via SSH.

#### Rule Direct root Logins Not Allowed [ref]

To further limit access to the `root` account, administrators can disable root logins at the console by editing the `/etc/securetty` file. This file lists all devices the root user is allowed to login to. If the file does not exist at all, the root user can login through any communication device on the system, whether via the console or via a raw network interface. This is dangerous as user can login to the system as root via Telnet, which sends the password in plain text over the network. By default, Debian 13's `/etc/securetty` file only allows the root user to login at the console physically attached to the system. To prevent root from logging in, remove the contents of this file. To prevent direct root logins, remove the contents of this file by typing the following command:

    $ sudo echo > /etc/securetty

Warning: This rule only checks the `/etc/securetty` file existence and its content. If you need to restrict user access using the `/etc/securetty` file, make sure the `pam_securetty.so` PAM module is properly enabled in relevant PAM files.

Rationale: | Disabling direct root logins ensures proper accountability and multifactor authentication to privileged accounts. Users will first login, then escalate to privileged (root) access via su / sudo. This is required for FISMA Low and FISMA Moderate systems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_direct_root_logins

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
cui | 3.1.1, 3.1.6
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.2.3, CIP-004-6 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.2, CIP-007-3 R5.2, CIP-007-3 R5.3.1, CIP-007-3 R5.3.2, CIP-007-3 R5.3.3
nist | IA-2, CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
anssi | R33
pcidss4 | 8.6.1, 8.6

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    echo > /etc/securetty

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - PCI-DSSv4-8.6
      - PCI-DSSv4-8.6.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_direct_root_logins
      - no_reboot_needed
      - restrict_strategy

    - name: Direct root Logins Not Allowed
      ansible.builtin.copy:
        dest: /etc/securetty
        content: ''
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.6
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2
      - PCI-DSSv4-8.6
      - PCI-DSSv4-8.6.1
      - low_complexity
      - low_disruption
      - medium_severity
      - no_direct_root_logins
      - no_reboot_needed
      - restrict_strategy

Group Secure Session Configuration Files for Login Accounts Group contains 1 group and 10 rules

[ref] When a user logs into a Unix account, the system configures the user's session by reading a number of files. Many of these files are located in the user's home directory, and may have weak permissions as a result of user error or misconfiguration. If an attacker can modify or even read certain types of account configuration information, they can often gain full access to the affected user's account. Therefore, it is important to test and correct configuration file permissions for interactive accounts, particularly those of privileged users such as root or system administrators.

Group Ensure that Users Have Sensible Umask Values Group contains 3 rules

[ref] The umask setting controls the default permissions for the creation of new files. With a default `umask` setting of 077, files and directories created by users will not be readable by any other user on the system. Users who wish to make specific files group- or world-readable can accomplish this by using the chmod command. Additionally, users can make all their files readable to their group by default by setting a `umask` of 027 in their shell configuration files. If default per-user groups exist (that is, if every user has a default group whose name is the same as that user's username and whose only member is the user), then it may even be safe for users to select a `umask` of 007, making it very easy to intentionally share files with groups of which the user is a member.

#### Rule Ensure the Default Bash Umask is Set Correctly [ref]

To ensure the default umask for users of the Bash shell is set properly, add or correct the `umask` setting in `/etc/bash.bashrc` to read as follows:

    umask 077

Rationale: | The umask value influences the permissions assigned to files when they are created. A misconfigured umask value could result in files with excessive permissions that can be read or written to by unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_umask_etc_bashrc

References:

cis-csc | 18
cobit5 | APO13.01, BAI03.01, BAI03.02, BAI03.03
isa-62443-2009 | 4.3.4.3.3
iso27001-2013 | A.14.1.1, A.14.2.1, A.14.2.5, A.6.1.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-6(1), CM-6(a)
nist-csf | PR.IP-2
os-srg | SRG-OS-000480-GPOS-00228, SRG-OS-000480-GPOS-00227
anssi | R36

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'bash' 2>/dev/null | grep -q '^installed$'; }; then

    var_accounts_user_umask='077'

    grep -q "^[^#]*\bumask" /etc/bash.bashrc && \
      sed -i -E -e "s/^([^#]*\bumask)[[:space:]]+[[:digit:]]+/\1 $var_accounts_user_umask/g" /etc/bash.bashrc
    if ! [ $? -eq 0 ]; then
        echo "umask $var_accounts_user_umask" >> /etc/bash.bashrc
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_bashrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_user_umask # promote to variable
      set_fact:
        var_accounts_user_umask: !!str 077
      tags:
        - always

    - name: Check if umask in /etc/bash.bashrc is already set
      ansible.builtin.lineinfile:
        path: /etc/bash.bashrc
        regexp: ^[^#]*\bumask\s+\d+$
        state: absent
      check_mode: true
      changed_when: false
      register: umask_replace
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"bash" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_bashrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Replace user umask in /etc/bash.bashrc
      ansible.builtin.replace:
        path: /etc/bash.bashrc
        regexp: ^([^#]*\b)umask\s+\d+$
        replace: \g<1>umask {{ var_accounts_user_umask }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"bash" in ansible_facts.packages'
      - umask_replace.found > 0
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_bashrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default umask is Appended Correctly
      ansible.builtin.lineinfile:
        create: true
        path: /etc/bash.bashrc
        line: umask {{ var_accounts_user_umask }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"bash" in ansible_facts.packages'
      - umask_replace.found == 0
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_bashrc
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure the Default Umask is Set Correctly in login.defs [ref]

To ensure the default umask controlled by `/etc/login.defs` is set properly, add or correct the `UMASK` setting in `/etc/login.defs` to read as follows:

    UMASK 077

Rationale: | The umask value influences the permissions assigned to files when they are created. A misconfigured umask value could result in files with excessive permissions that can be read and written to by unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_umask_etc_login_defs

References:

cis-csc | 11, 18, 3, 9
cobit5 | APO13.01, BAI03.01, BAI03.02, BAI03.03, BAI10.01, BAI10.02, BAI10.03, BAI10.05
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.1.1, A.14.2.1, A.14.2.2, A.14.2.3, A.14.2.4, A.14.2.5, A.6.1.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-6(1), CM-6(a)
nist-csf | PR.IP-1, PR.IP-2
os-srg | SRG-OS-000480-GPOS-00228
anssi | R36

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'login' 2>/dev/null | grep -q '^installed$'; }; then

    var_accounts_user_umask='077'

    # 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' <<< "^UMASK")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s %s" "$stripped_key" "$var_accounts_user_umask"

    # 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 "^UMASK\\>" "/etc/login.defs"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^UMASK\\>.*/$escaped_formatted_output/gi" "/etc/login.defs"
    else
        if [[ -s "/etc/login.defs" ]] && [[ -n "$(tail -c 1 -- "/etc/login.defs" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/login.defs"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/login.defs"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_user_umask # promote to variable
      set_fact:
        var_accounts_user_umask: !!str 077
      tags:
        - always

    - name: Check if UMASK is already set
      ansible.builtin.lineinfile:
        path: /etc/login.defs
        regexp: ^(\s*)UMASK\s+.*
        state: absent
      check_mode: true
      changed_when: false
      register: result_umask_is_set
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"login" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Replace user UMASK in /etc/login.defs
      ansible.builtin.replace:
        path: /etc/login.defs
        regexp: ^(\s*)UMASK(\s+).*
        replace: \g<1>UMASK\g<2>{{ var_accounts_user_umask }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"login" in ansible_facts.packages'
      - result_umask_is_set.found > 0
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default UMASK is Appended Correctly
      ansible.builtin.lineinfile:
        create: true
        path: /etc/login.defs
        line: UMASK {{ var_accounts_user_umask }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"login" in ansible_facts.packages'
      - result_umask_is_set.found == 0
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_login_defs
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure the Default Umask is Set Correctly in /etc/profile [ref]

To ensure the default umask controlled by `/etc/profile` is set properly, add or correct the `umask` setting in `/etc/profile` to read as follows:

    umask 077

Note that `/etc/profile` also reads scripts within `/etc/profile.d` directory. These scripts are also valid files to set umask value. Therefore, they should also be considered during the check and properly remediated, if necessary.

Rationale: | The umask value influences the permissions assigned to files when they are created. A misconfigured umask value could result in files with excessive permissions that can be read or written to by unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_umask_etc_profile

References:

cis-csc | 18
cobit5 | APO13.01, BAI03.01, BAI03.02, BAI03.03
isa-62443-2009 | 4.3.4.3.3
iso27001-2013 | A.14.1.1, A.14.2.1, A.14.2.5, A.6.1.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-6(1), CM-6(a)
nist-csf | PR.IP-2
os-srg | SRG-OS-000480-GPOS-00228, SRG-OS-000480-GPOS-00227
anssi | R36

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    var_accounts_user_umask='077'

    readarray -t profile_files < <(find /etc/profile.d/ -type f -name '*.sh' -or -name 'sh.local')

    for file in "${profile_files[@]}" /etc/profile; do
      grep -qE '^[^#]*umask' "$file" && sed -i -E "s/^(\s*umask\s*)[0-7]+/\1$var_accounts_user_umask/g" "$file"
    done

    if ! grep -qrE '^[^#]*umask' /etc/profile*; then
      echo "umask $var_accounts_user_umask" >> /etc/profile
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_profile
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_user_umask # promote to variable
      set_fact:
        var_accounts_user_umask: !!str 077
      tags:
        - always

    - name: Ensure the Default Umask is Set Correctly in /etc/profile - Locate Profile
        Configuration Files Where umask Is Defined
      ansible.builtin.find:
        paths:
        - /etc/profile.d
        patterns:
        - sh.local
        - '*.sh'
        contains: ^[\s]*umask\s+\d+
      register: result_profile_d_files
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_profile
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly in /etc/profile - Replace Existing
        umask Value in Files From /etc/profile.d
      ansible.builtin.replace:
        path: '{{ item.path }}'
        regexp: ^(\s*)umask\s+\d+
        replace: \1umask {{ var_accounts_user_umask }}
      loop: '{{ result_profile_d_files.files }}'
      register: result_umask_replaced_profile_d
      when:
      - '"linux-base" in ansible_facts.packages'
      - result_profile_d_files.matched
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_profile
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly in /etc/profile - Ensure umask Is
        Set in /etc/profile if Not Already Set Elsewhere
      ansible.builtin.lineinfile:
        create: true
        mode: 420
        path: /etc/profile
        line: umask {{ var_accounts_user_umask }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - not result_profile_d_files.matched
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_profile
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure the Default Umask is Set Correctly in /etc/profile - Ensure umask Value
        For All Existing umask Definition in /etc/profile
      ansible.builtin.replace:
        path: /etc/profile
        regexp: ^(\s*)umask\s+\d+
        replace: \1umask {{ var_accounts_user_umask }}
      register: result_umask_replaced_profile
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - accounts_umask_etc_profile
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Set Interactive Session Timeout [ref]

Setting the `TMOUT` option in `/etc/profile` ensures that all user sessions will terminate based on inactivity. A value of `0` (zero) disables the automatic logout feature and is therefore not a compliant setting. The value of TMOUT should be a positive integer, exported, and read only. The `TMOUT` setting in a file loaded by `/etc/profile`, e.g. `/etc/profile.d/tmout.sh` should read as follows:

    typeset -xr TMOUT=600

or

    declare -xr TMOUT=600

Using the `typeset` keyword is preferred for wider compatibility with ksh and other shells.

Rationale: | Terminating an idle session within a short time period reduces the window of opportunity for unauthorized personnel to take control of a management session enabled on the console or console port that has been left unattended.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_tmout

References:

cis-csc | 1, 12, 15, 16
cobit5 | DSS05.04, DSS05.10, DSS06.10
cui | 3.1.11
isa-62443-2009 | 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.5, SR 1.7, SR 1.8, SR 1.9
iso27001-2013 | A.18.1.4, A.9.2.1, A.9.2.4, A.9.3.1, A.9.4.2, A.9.4.3
nerc-cip | CIP-004-6 R2.2.3, CIP-007-3 R5.1, CIP-007-3 R5.2, CIP-007-3 R5.3.1, CIP-007-3 R5.3.2, CIP-007-3 R5.3.3
nist | AC-12, SC-10, AC-2(5), CM-6(a)
nist-csf | PR.AC-7
os-srg | SRG-OS-000163-GPOS-00072, SRG-OS-000029-GPOS-00010
anssi | R32
pcidss4 | 8.6.1, 8.6

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    var_accounts_tmout='600'

    # if 0, no occurrence of tmout found, if 1, occurrence found
    tmout_found=0

    for f in /etc/profile /etc/profile.d/*.sh; do

        if grep --silent '^[^#].*TMOUT' $f; then
            sed -i -E "s/^(.*)TMOUT\s*=\s*(\w|\$)*(.*)$/typeset -xr TMOUT=$var_accounts_tmout\3/g" $f
            tmout_found=1
        fi
    done

    if [ $tmout_found -eq 0 ]; then
            echo -e "\n# Set TMOUT to $var_accounts_tmout per security requirements" >> /etc/profile.d/tmout.sh
            echo "typeset -xr TMOUT=$var_accounts_tmout" >> /etc/profile.d/tmout.sh
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSSv4-8.6
      - PCI-DSSv4-8.6.1
      - accounts_tmout
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_tmout # promote to variable
      set_fact:
        var_accounts_tmout: !!str 600
      tags:
        - always

    - name: Correct any occurrence of TMOUT in /etc/profile
      ansible.builtin.replace:
        path: /etc/profile
        regexp: ^[^#].*TMOUT=.*
        replace: typeset -xr TMOUT={{ var_accounts_tmout }}
      register: profile_replaced
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSSv4-8.6
      - PCI-DSSv4-8.6.1
      - accounts_tmout
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set Interactive Session Timeout
      ansible.builtin.lineinfile:
        path: /etc/profile.d/tmout.sh
        create: true
        regexp: TMOUT=
        line: typeset -xr TMOUT={{ var_accounts_tmout }}
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.11
      - NIST-800-53-AC-12
      - NIST-800-53-AC-2(5)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-10
      - PCI-DSSv4-8.6
      - PCI-DSSv4-8.6.1
      - accounts_tmout
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule User Initialization Files Must Be Group-Owned By The Primary Group [ref]

Change the group owner of interactive users files to the group found in

    /etc/passwd

for the user. To change the group owner of a local interactive user home directory, use the following command:

    $ sudo chgrp USER_GROUP /home/USER/.INIT_FILE

This rule ensures every initialization file related to an interactive user is group-owned by an interactive user.
Warning: Due to OVAL limitation, this rule can report a false negative in a specific situation where two interactive users swap the group-ownership of their respective initialization files.

Rationale: | Local initialization files for interactive users are used to configure the user's shell environment upon logon. Malicious modification of these files could compromise accounts upon logon.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_user_dot_group_ownership

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    awk -F: '{if ($4 >= 1000 && $4 != 65534) print $4":"$6}' /etc/passwd | while IFS=: read -r gid home; do find -P "$home" -maxdepth 1 -type f -name "\.[^.]*" -exec chgrp -f --no-dereference -- $gid "{}" \;; done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - accounts_user_dot_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Group-Owned By The Primary Group - Get interactive
        users from passwd file
      ansible.builtin.getent:
        database: passwd
      register: passwd_entries
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_user_dot_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Group-Owned By The Primary Group - Create
        list of interactive users with GID and home directory
      ansible.builtin.set_fact:
        interactive_users: '{{ interactive_users | default([]) + [{''home'': item.value[4],
          ''gid'': item.value[2]}] }}'
      loop: '{{ passwd_entries.ansible_facts.getent_passwd | dict2items }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value[2] | int >= 1000 | int
      - item.value[2] | int != 65534 | int
      - item.value[4] != ""
      tags:
      - accounts_user_dot_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Group-Owned By The Primary Group - Find
        dot files in interactive user home directories
      ansible.builtin.find:
        paths: '{{ item.home }}'
        patterns: .*
        file_type: file
        hidden: true
        depth: 1
        follow: false
      register: user_dotfiles
      loop: '{{ interactive_users | default([]) }}'
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.home != ""
      tags:
      - accounts_user_dot_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Group-Owned By The Primary Group - Set correct
        group ownership for user initialization files
      ansible.builtin.file:
        path: '{{ item.1.path }}'
        group: '{{ item.0.item.gid }}'
        follow: false
      loop: '{{ user_dotfiles.results | subelements(''files'', skip_missing=True) }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.0 is not skipped
      - item.1.path is defined
      tags:
      - accounts_user_dot_group_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule User Initialization Files Must Be Owned By the Primary User [ref]

Set the owner of the user initialization files for interactive users to the primary owner with the following command:

    $ sudo chown USER /home/USER/.*

This rule ensures every initialization file related to an interactive user is owned by an interactive user.
Warning: Due to OVAL limitation, this rule can report a false negative in a specific situation where two interactive users swap the ownership of their respective initialization files.

Rationale: | Local initialization files are used to configure the user's shell environment upon logon. Malicious modification of these files could compromise accounts upon logon.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_user_dot_user_ownership

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    awk -F: '{if ($3 >= 1000 && $3 != 65534) print $3":"$6}' /etc/passwd | while IFS=: read -r uid home; do find -P "$home" -maxdepth 1 -type f -name "\.[^.]*" -exec chown -f --no-dereference -- $uid "{}" \;; done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - accounts_user_dot_user_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Owned By the Primary User - Get interactive
        users from passwd file
      ansible.builtin.getent:
        database: passwd
      register: passwd_entries
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_user_dot_user_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Owned By the Primary User - Create list
        of interactive users with UID and home directory
      ansible.builtin.set_fact:
        interactive_users: '{{ interactive_users | default([]) + [{''uid'': item.value[1],
          ''home'': item.value[4], ''username'': item.key}] }}'
      loop: '{{ passwd_entries.ansible_facts.getent_passwd | dict2items }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value[1] | int >= 1000 | int
      - item.value[1] | int != 65534 | int
      - item.value[4] != ""
      tags:
      - accounts_user_dot_user_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Owned By the Primary User - Find dot files
        in interactive user home directories
      ansible.builtin.find:
        paths: '{{ item.home }}'
        patterns: .*
        file_type: file
        hidden: true
        depth: 1
        follow: false
      register: user_dotfiles
      loop: '{{ interactive_users | default([]) }}'
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.home != ""
      tags:
      - accounts_user_dot_user_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: User Initialization Files Must Be Owned By the Primary User - Set correct
        ownership for user initialization files
      ansible.builtin.file:
        path: '{{ item.1.path }}'
        owner: '{{ item.0.item.username }}'
        follow: false
      loop: '{{ user_dotfiles.results | subelements(''files'', skip_missing=True) }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.0 is not skipped
      - item.0 is not failed
      - item.0.item is defined
      - item.0.item.username is defined
      - item.1.path is defined
      tags:
      - accounts_user_dot_user_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule All User Files and Directories In The Home Directory Must Be Group-Owned By The Primary Group [ref]

Change the group of a local interactive users files and directories to a group that the interactive user is a member of. To change the group owner of a local interactive users files and directories, use the following command:

    $ sudo chgrp USER_GROUP /home/USER/FILE_DIR

This rule ensures every file or directory under the home directory related to an interactive user is group-owned by an interactive user.
Warning: Due to OVAL limitation, this rule can report a false negative in a specific situation where two interactive users swap the group-ownership of folders or files in their respective home directories.

Rationale: | If a local interactive users files are group-owned by a group of which the user is not a member, unintended users may be able to access them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_users_home_files_groupownership

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    for user in $(awk -F':' '{ if ($3 >= 1000 && $3 != 65534 && $6 != "/") print $1 }' /etc/passwd); do
        home_dir=$(getent passwd $user | cut -d: -f6)
        group=$(getent passwd $user | cut -d: -f4)
        # Only update the group-ownership when necessary. This will avoid changing the inode timestamp
        # when the group is already defined as expected, therefore not impacting in possible integrity
        # check systems that also check inodes timestamps.
        find $home_dir -not -group $group -exec chgrp -f --no-dereference $group {} \;
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - accounts_users_home_files_groupownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Get all local users from /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_users_home_files_groupownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Create local_users variable from the getent output
      ansible.builtin.set_fact:
        local_users: '{{ ansible_facts.getent_passwd|dict2items }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_users_home_files_groupownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Test for existence of home directories to avoid creating them, but only fixing
        ownership
      ansible.builtin.stat:
        path: '{{ item.value[4] }}'
      register: path_exists
      loop: '{{ local_users }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      - item.value[4] != "/"
      tags:
      - accounts_users_home_files_groupownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure interactive local users are the owners of their respective home directories
      ansible.builtin.file:
        path: '{{ item.0.value[4] }}'
        group: '{{ item.0.value[2] }}'
        recurse: true
      loop: '{{ local_users|zip(path_exists.results)|list }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.1.stat is defined and item.1.stat.exists
      tags:
      - accounts_users_home_files_groupownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule All User Files and Directories In The Home Directory Must Have a Valid Owner [ref]

Either remove all files and directories from the system that do not have a valid user, or assign a valid user to all unowned files and directories. To assign a valid owner to a local interactive user's files and directories, use the following command:

    $ sudo chown -R USER /home/USER

This rule ensures every file or directory under the home directory related to an interactive user is owned by an interactive user.
Warning: Due to OVAL limitation, this rule can report a false negative in a specific situation where two interactive users swap the ownership of folders or files in their respective home directories.

Rationale: | If local interactive users do not own the files in their directories, unauthorized users may be able to access them. Additionally, if files are not owned by the user, this could be an indication of system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_users_home_files_ownership

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    for user in $(awk -F':' '{ if ($3 >= 1000 && $3 != 65534 && $6 != "/") print $1 }' /etc/passwd); do
        home_dir=$(getent passwd $user | cut -d: -f6)
        # Only update the ownership when necessary. This will avoid changing the inode timestamp
        # when the owner is already defined as expected, therefore not impacting in possible integrity
        # check systems that also check inodes timestamps.
        find $home_dir -not -user $user -exec chown -f --no-dereference $user {} \;
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - accounts_users_home_files_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Get all local users from /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_users_home_files_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Create local_users variable from the getent output
      ansible.builtin.set_fact:
        local_users: '{{ ansible_facts.getent_passwd|dict2items }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_users_home_files_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Test for existence of home directories to avoid creating them, but only fixing
        ownership
      ansible.builtin.stat:
        path: '{{ item.value[4] }}'
      register: path_exists
      loop: '{{ local_users }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      - item.value[4] != "/"
      tags:
      - accounts_users_home_files_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure interactive local users are the owners of their respective home directories
      ansible.builtin.file:
        path: '{{ item.0.value[4] }}'
        owner: '{{ item.0.value[1] }}'
        recurse: true
      loop: '{{ local_users|zip(path_exists.results)|list }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.1.stat is defined and item.1.stat.exists
      tags:
      - accounts_users_home_files_ownership
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule All User Files and Directories In The Home Directory Must Have Mode 0750 Or Less Permissive [ref]

Set the mode on files and directories in the local interactive user home directory with the following command:

    $ sudo chmod 0750 /home/USER/FILE_DIR

Files that begin with a "." are excluded from this requirement.

Rationale: | If a local interactive user files have excessive permissions, unintended users may be able to access or modify them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_accounts_users_home_files_permissions

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    for home_dir in $(awk -F':' '{ if ($3 >= 1000 && $3 != 65534 && $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.
        find "$home_dir" -perm /7027 \! -type l -exec chmod u-s,g-w-s,o=- {} \;
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - accounts_users_home_files_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Get all local users from /etc/passwd
      ansible.builtin.getent:
        database: passwd
        split: ':'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_users_home_files_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Create local_users variable from the getent output
      ansible.builtin.set_fact:
        local_users: '{{ ansible_facts.getent_passwd|dict2items }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - accounts_users_home_files_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Test for existence home directories to avoid creating them.
      ansible.builtin.stat:
        path: '{{ item.value[4] }}'
      register: path_exists
      loop: '{{ local_users }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.value[1]|int >= 1000
      - item.value[1]|int != 65534
      - item.value[4] != "/"
      tags:
      - accounts_users_home_files_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - 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: false
        recurse: true
      loop: '{{ local_users|zip(path_exists.results)|list }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - item.1.stat is defined and item.1.stat.exists
      tags:
      - accounts_users_home_files_permissions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure All User Initialization Files Have Mode 0740 Or Less Permissive [ref]

Set the mode of the user initialization files to `0740` with the following command:

    $ sudo chmod 0740 /home/USER/.INIT_FILE

Rationale: | Local initialization files are used to configure the user's shell environment upon logon. Malicious modification of these files could compromise accounts upon logon.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permission_user_init_files

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    var_user_initialization_files_regex='^(\.bashrc|\.zshrc|\.cshrc|\.profile|\.bash_login|\.bash_profile)$'

    readarray -t interactive_users < <(awk -F: '$3>=1000   {print $1}' /etc/passwd)
    readarray -t interactive_users_home < <(awk -F: '$3>=1000   {print $6}' /etc/passwd)
    readarray -t interactive_users_shell < <(awk -F: '$3>=1000   {print $7}' /etc/passwd)

    USERS_IGNORED_REGEX='nobody|nfsnobody'

    for (( i=0; i<"${#interactive_users[@]}"; i++ )); do
        if ! grep -qP "$USERS_IGNORED_REGEX" <<< "${interactive_users[$i]}" && \
            [ "${interactive_users_shell[$i]}" != "/sbin/nologin" ]; then

            readarray -t init_files < <(find "${interactive_users_home[$i]}" -maxdepth 1 \
                -exec basename {} \; | grep -P "$var_user_initialization_files_regex")
            for file in "${init_files[@]}"; do
                chmod u-s,g-wxs,o= "${interactive_users_home[$i]}/$file"
            done
        fi
    done

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: XCCDF Value var_user_initialization_files_regex # promote to variable
      set_fact:
        var_user_initialization_files_regex: !!str ^(\.bashrc|\.zshrc|\.cshrc|\.profile|\.bash_login|\.bash_profile)$
      tags:
        - always

    - name: Ensure All User Initialization Files Have Mode 0740 Or Less Permissive - Gather
        User Info
      ansible.builtin.getent:
        database: passwd
      tags:
      - file_permission_user_init_files
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All User Initialization Files Have Mode 0740 Or Less Permissive - Find
        Init Files
      ansible.builtin.find:
        paths: '{{ item.value[4] }}'
        pattern: '{{ var_user_initialization_files_regex }}'
        hidden: true
        use_regex: true
      with_dict: '{{ ansible_facts.getent_passwd }}'
      when:
      - item.value[4] != "/sbin/nologin"
      - item.key not in ["nobody", "nfsnobody"]
      - item.value[1] | int >= 1000
      register: found_init_files
      tags:
      - file_permission_user_init_files
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All User Initialization Files Have Mode 0740 Or Less Permissive - Fix
        Init Files Permissions
      ansible.builtin.file:
        path: '{{ item.1.path }}'
        mode: u-s,g-wxs,o=
      loop: '{{ q(''ansible.builtin.subelements'', found_init_files.results, ''files'',
        {''skip_missing'': True}) }}'
      tags:
      - file_permission_user_init_files
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group AppArmor Group contains 5 rules

[ref] Many security vulnerabilities result from bugs in trusted programs. A trusted program runs with privileges that attackers want to possess. The program fails to keep that trust if there is a bug in the program that allows the attacker to acquire said privilege.
AppArmor® is an application security solution designed specifically to apply privilege confinement to suspect programs. AppArmor allows the administrator to specify the domain of activities the program can perform by developing a security profile. A security profile is a listing of files that the program may access and the operations the program may perform. AppArmor secures applications by enforcing good application behavior without relying on attack signatures, so it can prevent attacks even if previously unknown vulnerabilities are being exploited.

#### Rule Ensure AppArmor is installed [ref]

AppArmor provide Mandatory Access Controls.
Rationale: | Without a Mandatory Access Control system installed only the default Discretionary Access Control system will be available.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_apparmor_installed

References:

os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000312-GPOS-00124, SRG-OS-000324-GPOS-00125, SRG-OS-000370-GPOS-00155
anssi | R45

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ]; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "apparmor"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_apparmor

    class install_apparmor {
      package { 'apparmor':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Ensure apparmor is installed
      ansible.builtin.package:
        name: apparmor
        state: present
      when: ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_apparmor_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "apparmor"
    version = "*"

#### Rule Install the pam_apparmor Package [ref]

The `pam_apparmor` package can be installed with the following command:

    $ apt-get install pam_apparmor

Rationale: | Protection of system integrity using AppArmor depends on this package being installed.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_pam_apparmor_installed

References:

nist | AC-3(4), AC-6(8), AC-6(10), CM-7(5)(b), CM-7(2), SC-7(21), CM-6(a)
os-srg | SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000312-GPOS-00124, SRG-OS-000324-GPOS-00125, SRG-OS-000326-GPOS-00126, SRG-OS-000370-GPOS-00155, SRG-OS-000480-GPOS-00230, SRG-OS-000480-GPOS-00227, SRG-OS-000480-GPOS-00231, SRG-OS-000480-GPOS-00232
anssi | R45

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ]; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "libpam-apparmor"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_libpam-apparmor

    class install_libpam-apparmor {
      package { 'libpam-apparmor':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Ensure libpam-apparmor is installed
      ansible.builtin.package:
        name: libpam-apparmor
        state: present
      when: ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      tags:
      - NIST-800-53-AC-3(4)
      - NIST-800-53-AC-6(10)
      - NIST-800-53-AC-6(8)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(2)
      - NIST-800-53-CM-7(5)(b)
      - NIST-800-53-SC-7(21)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_pam_apparmor_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "libpam-apparmor"
    version = "*"

#### Rule Enforce all AppArmor Profiles [ref]

AppArmor profiles define what resources applications are able to access. To set all profiles to enforce mode run the following command:

    $ sudo aa-enforce /etc/apparmor.d/*

To list unconfined processes run the following command:

    $ sudo apparmor_status | grep processes

Any unconfined processes may need to have a profile created or activated for them and then be restarted.

Rationale: | Security configuration requirements vary from site to site. Some sites may mandate a policy that is stricter than the default policy, which is perfectly acceptable. This recommendation is intended to ensure that any policies that exist on the system are activated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_all_apparmor_profiles_enforced

References:

anssi | R45

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ] && { ( [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ] && dpkg-query --show --showformat='${db:Status-Status}' 'apparmor' 2>/dev/null | grep -q '^installed$' ); }; then

    # make sure apparmor-utils is installed for aa-complain and aa-enforce
    DEBIAN_FRONTEND=noninteractive apt-get install -y "apparmor-utils"

    # Ensure all AppArmor Profiles are enforcing
    apparmor_parser -q -r /etc/apparmor.d/

    aa-enforce /etc/apparmor.d/*

    UNCONFINED=$(aa-unconfined)
    if [ ! -z "$UNCONFINED" ]

    then
      echo -e "***WARNING***: There are some unconfined processes:"
      echo -e "----------------------------"
      echo "The may need to have a profile created or activated for them and then be restarted."
      for PROCESS in "${UNCONFINED[@]}"
      do
          echo "$PROCESS"
      done
      echo -e "----------------------------"
      echo "The may need to have a profile created or activated for them and then be restarted."
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - all_apparmor_profiles_enforced
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure apparmor-utils is installed
      ansible.builtin.package:
        name: apparmor-utils
        state: present
      when:
      - ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      - ( ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
        and "apparmor" in ansible_facts.packages )
      tags:
      - all_apparmor_profiles_enforced
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Enforce all AppArmor Profiles - Ensure all AppArmor Profiles are reloaded
      ansible.builtin.command: apparmor_parser -q -r /etc/apparmor.d/
      when:
      - ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      - ( ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
        and "apparmor" in ansible_facts.packages )
      tags:
      - all_apparmor_profiles_enforced
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Enforce all AppArmor Profiles - Ensure all AppArmor Profiles are enforcing
      ansible.builtin.command: aa-enforce /etc/apparmor.d/*
      when:
      - ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      - ( ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
        and "apparmor" in ansible_facts.packages )
      tags:
      - all_apparmor_profiles_enforced
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Enforce all AppArmor Profiles - Collect unconfined processes
      ansible.builtin.command: aa-unconfined
      register: unconfined_processes
      when:
      - ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      - ( ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
        and "apparmor" in ansible_facts.packages )
      tags:
      - all_apparmor_profiles_enforced
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Enforce all AppArmor Profiles - Provide details about unconfined processes
      ansible.builtin.assert:
        that:
        - unconfined_processes.stdout_lines | length > 0
        success_msg: The process {{ item }} may need to have a profile created or activated
          for them and then be restarted.
        fail_msg: ''
      with_items: '{{ unconfined_processes.stdout_lines }}'
      when:
      - ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      - ( ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
        and "apparmor" in ansible_facts.packages )
      - unconfined_processes is not skipped
      tags:
      - all_apparmor_profiles_enforced
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure AppArmor is Active and Configured [ref]

Verify that the Apparmor tool is configured to control whitelisted applications and user home directory access control.
The `apparmor` service can be enabled with the following command:

    $ sudo systemctl enable apparmor.service

Rationale:

Using a whitelist provides a configuration management method for allowing the execution of only authorized software. Using only authorized software decreases risk by limiting the number of potential vulnerabilities.
The organization must identify authorized software programs and permit execution of authorized software by adding each authorized program to the "pam_apparmor" exception policy. The process used to identify software programs that are authorized to execute on organizational information systems is commonly referred to as whitelisting.
Verification of whitelisted software occurs prior to execution or at system startup.
Users' home directories/folders may contain information of a sensitive nature. Nonprivileged users should coordinate any sharing of information with a System Administrator (SA) through shared resources.
Apparmor can confine users to their home directory, not allowing them to make any changes outside of their own home directories. Confining users to their home directory will minimize the risk of sharing information.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_apparmor_configured

References:

nist | AC-3(4), AC-6(8), AC-6(10), CM-7(5)(b), CM-7(2), SC-7(21), CM-6(a)
os-srg | SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000312-GPOS-00124, SRG-OS-000324-GPOS-00125, SRG-OS-000326-GPOS-00126, SRG-OS-000370-GPOS-00155, SRG-OS-000480-GPOS-00230, SRG-OS-000480-GPOS-00227, SRG-OS-000480-GPOS-00231, SRG-OS-000480-GPOS-00232
anssi | R45

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include enable_apparmor

    class enable_apparmor {
      service {'apparmor':
        enable => true,
        ensure => 'running',
      }
    }

Remediation Ansible snippet ⇲

    - name: Start apparmor.service
      ansible.builtin.systemd:
        name: apparmor.service
        state: started
        enabled: true
      when: ansible_virtualization_type not in ["docker", "lxc", "openvz", "podman", "container"]
      tags:
      - NIST-800-53-AC-3(4)
      - NIST-800-53-AC-6(10)
      - NIST-800-53-AC-6(8)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(2)
      - NIST-800-53-CM-7(5)(b)
      - NIST-800-53-SC-7(21)
      - apparmor_configured
      - medium_severity

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["apparmor"]

#### Rule Ensure AppArmor is enabled in the bootloader configuration [ref]

Configure AppArmor to be enabled at boot time and verify that it has not been overwritten by the bootloader boot parameters. Note: This recommendation is designed around the grub bootloader, if LILO or another bootloader is in use in your environment, enact equivalent settings.
Rationale: | AppArmor must be enabled at boot time in your bootloader configuration to ensure that the controls it provides are not overridden.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_enable_apparmor

References:

anssi | R45

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if [ ! -f /.dockerenv ] && [ ! -f /run/.containerenv ]; then

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

    update-grub

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Group GRUB2 bootloader configuration Group contains 2 groups and 26 rules

[ref] During the boot process, the boot loader is responsible for starting the execution of the kernel and passing options to it. The boot loader allows for the selection of different kernels - possibly on different partitions or media. The default Debian 13 boot loader for x86 systems is called GRUB2. Options it can pass to the kernel include single-user mode, which provides root access without any authentication, and the ability to disable SELinux. To prevent local users from modifying the boot parameters and endangering security, protect the boot loader configuration with a password and ensure its configuration file's permissions are set properly.

Group Non-UEFI GRUB2 bootloader configuration Group contains 7 rules
[ref] Non-UEFI GRUB2 bootloader configuration

#### Rule Verify /boot/grub/grub.cfg Group Ownership [ref]

The file `/boot/grub/grub.cfg` should be group-owned by the `root` group to prevent destruction or modification of the file. To properly set the group owner of `/boot/grub/grub.cfg`, run the command:

    $ sudo chgrp root /boot/grub/grub.cfg

Rationale: | The `root` group is a highly-privileged group. Furthermore, the group-owner of this file should not have any access privileges anyway.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
os-srg | SRG-OS-000480-GPOS-00227
anssi | R29
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ ! -d /sys/firmware/efi ] && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/boot/grub/grub.cfg" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /boot/grub/grub.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_grub2_cfg_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_grub2_cfg_newgroup: '0'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub/grub.cfg
      register: file_exists
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /boot/grub/grub.cfg
      ansible.builtin.file:
        path: /boot/grub/grub.cfg
        follow: false
        group: '{{ file_groupowner_grub2_cfg_newgroup }}'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub/user.cfg Group Ownership [ref]

The file `/boot/grub/user.cfg` should be group-owned by the `root` group to prevent reading or modification of the file. To properly set the group owner of `/boot/grub/user.cfg`, run the command:

    $ sudo chgrp root /boot/grub/user.cfg

Rationale: | The `root` group is a highly-privileged group. Furthermore, the group-owner of this file should not have any access privileges anyway. Non-root users who read the boot parameters may be able to identify weaknesses in security upon boot and be able to exploit them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_user_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
os-srg | SRG-OS-000480-GPOS-00227
anssi | R29
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ ! -d /sys/firmware/efi ] && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/boot/grub/user.cfg" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /boot/grub/user.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_user_cfg_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_user_cfg_newgroup: '0'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub/user.cfg
      ansible.builtin.stat:
        path: /boot/grub/user.cfg
      register: file_exists
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /boot/grub/user.cfg
      ansible.builtin.file:
        path: /boot/grub/user.cfg
        follow: false
        group: '{{ file_groupowner_user_cfg_newgroup }}'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub/grub.cfg User Ownership [ref]

The file `/boot/grub/grub.cfg` should be owned by the `root` user to prevent destruction or modification of the file. To properly set the owner of `/boot/grub/grub.cfg`, run the command:

    $ sudo chown root /boot/grub/grub.cfg

Rationale: | Only root should be able to modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
os-srg | SRG-OS-000480-GPOS-00227
anssi | R29
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ ! -d /sys/firmware/efi ] && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/boot/grub/grub.cfg" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /boot/grub/grub.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_grub2_cfg_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_grub2_cfg_newown: '0'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub/grub.cfg
      register: file_exists
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /boot/grub/grub.cfg
      ansible.builtin.file:
        path: /boot/grub/grub.cfg
        follow: false
        owner: '{{ file_owner_grub2_cfg_newown }}'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub/user.cfg User Ownership [ref]

The file `/boot/grub/user.cfg` should be owned by the `root` user to prevent reading or modification of the file. To properly set the owner of `/boot/grub/user.cfg`, run the command:

    $ sudo chown root /boot/grub/user.cfg

Rationale: | Only root should be able to modify important boot parameters. Also, non-root users who read the boot parameters may be able to identify weaknesses in security upon boot and be able to exploit them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_user_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
anssi | R29
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ ! -d /sys/firmware/efi ] && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/boot/grub/user.cfg" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /boot/grub/user.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_user_cfg_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_user_cfg_newown: '0'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub/user.cfg
      ansible.builtin.stat:
        path: /boot/grub/user.cfg
      register: file_exists
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /boot/grub/user.cfg
      ansible.builtin.file:
        path: /boot/grub/user.cfg
        follow: false
        owner: '{{ file_owner_user_cfg_newown }}'
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub/grub.cfg Permissions [ref]

File permissions for `/boot/grub/grub.cfg` should be set to 600. To properly set the permissions of `/boot/grub/grub.cfg`, run the command:

    $ sudo chmod 600 /boot/grub/grub.cfg

Rationale: | Proper permissions ensure that only the root user can modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
anssi | R29
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ ! -d /sys/firmware/efi ] && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    chmod u-xs,g-xwrs,o-xwrt /boot/grub/grub.cfg

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub/grub.cfg
      register: file_exists
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /boot/grub/grub.cfg
      ansible.builtin.file:
        path: /boot/grub/grub.cfg
        mode: u-xs,g-xwrs,o-xwrt
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub/user.cfg Permissions [ref]

File permissions for `/boot/grub/user.cfg` should be set to 600. To properly set the permissions of `/boot/grub/user.cfg`, run the command:

    $ sudo chmod 600 /boot/grub/user.cfg

Rationale: | Proper permissions ensure that only the root user can read or modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_user_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
anssi | R29
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ ! -d /sys/firmware/efi ] && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    chmod u-xs,g-xwrs,o-xwrt /boot/grub/user.cfg

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub/user.cfg
      ansible.builtin.stat:
        path: /boot/grub/user.cfg
      register: file_exists
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /boot/grub/user.cfg
      ansible.builtin.file:
        path: /boot/grub/user.cfg
        mode: u-xs,g-xwrs,o-xwrt
      when:
      - '"/boot/efi" not in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Set Boot Loader Password in grub2 [ref]

The grub2 boot loader should have a superuser account and password protection enabled to protect boot-time settings.
Since plaintext passwords are a security risk, generate a hash for the password by running the following command:

    # grub2-setpassword

When prompted, enter the password that was selected.
Warning: To prevent hard-coded passwords, automatic remediation of this control is not available. Remediation must be automated as a component of machine provisioning, or followed manually as outlined above. Also, do NOT manually add the superuser account and password to the `grub.cfg` file as the grub2-mkconfig command overwrites this file.

Rationale: | Password protection on the boot loader configuration ensures users with physical access cannot trivially alter important bootloader settings. These include which kernel to use, and whether to enter single-user mode.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_password

References:

cis-csc | 1, 11, 12, 14, 15, 16, 18, 3, 5
cobit5 | DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.06, DSS06.10
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7
iso27001-2013 | A.18.1.4, A.6.1.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nist | CM-6(a)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.PT-3
ospp | FIA_UAU.1
os-srg | SRG-OS-000080-GPOS-00048
anssi | R5

Group UEFI GRUB2 bootloader configuration Group contains 7 rules
[ref] UEFI GRUB2 bootloader configuration Warning: UEFI generally uses vfat file systems, which does not support Unix-style permissions managed by chmod command. In this case, in order to change file permissions for files within /boot/efi it is necessary to update the mount options in /etc/fstab file and reboot the system.

#### Rule Verify the UEFI Boot Loader grub.cfg Group Ownership [ref]

The file `/boot/grub2/grub.cfg` should be group-owned by the `root` group to prevent destruction or modification of the file. To properly set the group owner of `/boot/grub2/grub.cfg`, run the command:

    $ sudo chgrp root /boot/grub2/grub.cfg

Rationale: | The `root` group is a highly-privileged group. Furthermore, the group-owner of this file should not have any access privileges anyway.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_efi_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ -d /sys/firmware/efi ]; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/boot/grub2/grub.cfg" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /boot/grub2/grub.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_efi_grub2_cfg_newgroup variable if represented by
        gid
      ansible.builtin.set_fact:
        file_groupowner_efi_grub2_cfg_newgroup: '0'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub2/grub.cfg
      register: file_exists
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /boot/grub2/grub.cfg
      ansible.builtin.file:
        path: /boot/grub2/grub.cfg
        follow: false
        group: '{{ file_groupowner_efi_grub2_cfg_newgroup }}'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub2/user.cfg Group Ownership [ref]

The file `/boot/grub2/user.cfg` should be group-owned by the `root` group to prevent reading or modification of the file. To properly set the group owner of `/boot/grub2/user.cfg`, run the command:

    $ sudo chgrp root /boot/grub2/user.cfg

Rationale: | The `root` group is a highly-privileged group. Furthermore, the group-owner of this file should not have any access privileges anyway. Non-root users who read the boot parameters may be able to identify weaknesses in security upon boot and be able to exploit them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_efi_user_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ -d /sys/firmware/efi ]; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/boot/grub2/user.cfg" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /boot/grub2/user.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_efi_user_cfg_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_efi_user_cfg_newgroup: '0'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/user.cfg
      ansible.builtin.stat:
        path: /boot/grub2/user.cfg
      register: file_exists
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /boot/grub2/user.cfg
      ansible.builtin.file:
        path: /boot/grub2/user.cfg
        follow: false
        group: '{{ file_groupowner_efi_user_cfg_newgroup }}'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_groupowner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify the UEFI Boot Loader grub.cfg User Ownership [ref]

The file `/boot/grub2/grub.cfg` should be owned by the `root` user to prevent destruction or modification of the file. To properly set the owner of `/boot/grub2/grub.cfg`, run the command:

    $ sudo chown root /boot/grub2/grub.cfg

Rationale: | Only root should be able to modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_efi_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ -d /sys/firmware/efi ]; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/boot/grub2/grub.cfg" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /boot/grub2/grub.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_efi_grub2_cfg_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_efi_grub2_cfg_newown: '0'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub2/grub.cfg
      register: file_exists
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /boot/grub2/grub.cfg
      ansible.builtin.file:
        path: /boot/grub2/grub.cfg
        follow: false
        owner: '{{ file_owner_efi_grub2_cfg_newown }}'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub2/user.cfg User Ownership [ref]

The file `/boot/grub2/user.cfg` should be owned by the `root` user to prevent reading or modification of the file. To properly set the owner of `/boot/grub2/user.cfg`, run the command:

    $ sudo chown root /boot/grub2/user.cfg

Rationale: | Only root should be able to modify important boot parameters. Also, non-root users who read the boot parameters may be able to identify weaknesses in security upon boot and be able to exploit them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_efi_user_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-7.1
anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ -d /sys/firmware/efi ]; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/boot/grub2/user.cfg" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /boot/grub2/user.cfg
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_efi_user_cfg_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_efi_user_cfg_newown: '0'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/user.cfg
      ansible.builtin.stat:
        path: /boot/grub2/user.cfg
      register: file_exists
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /boot/grub2/user.cfg
      ansible.builtin.file:
        path: /boot/grub2/user.cfg
        follow: false
        owner: '{{ file_owner_efi_user_cfg_newown }}'
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-7.1
      - configure_strategy
      - file_owner_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify the UEFI Boot Loader grub.cfg Permissions [ref]

File permissions for `/boot/grub2/grub.cfg` should be set to 700. To properly set the permissions of `/boot/grub2/grub.cfg`, run the command:

    $ sudo chmod 700 /boot/grub2/grub.cfg

Rationale: | Proper permissions ensure that only the root user can modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_efi_grub2_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ -d /sys/firmware/efi ]; then

    chmod u-s,g-xwrs,o-xwrt /boot/grub2/grub.cfg

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/grub.cfg
      ansible.builtin.stat:
        path: /boot/grub2/grub.cfg
      register: file_exists
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-s,g-xwrs,o-xwrt on /boot/grub2/grub.cfg
      ansible.builtin.file:
        path: /boot/grub2/grub.cfg
        mode: u-s,g-xwrs,o-xwrt
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_efi_grub2_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify /boot/grub2/user.cfg Permissions [ref]

File permissions for `/boot/grub2/user.cfg` should be set to 600. To properly set the permissions of `/boot/grub2/user.cfg`, run the command:

    $ sudo chmod 600 /boot/grub2/user.cfg

Rationale: | Proper permissions ensure that only the root user can read or modify important boot parameters.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_efi_user_cfg

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.4.5
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ) && [ -d /sys/firmware/efi ]; then

    chmod u-s,g-xwrs,o-xwrt /boot/grub2/user.cfg

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /boot/grub2/user.cfg
      ansible.builtin.stat:
        path: /boot/grub2/user.cfg
      register: file_exists
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-s,g-xwrs,o-xwrt on /boot/grub2/user.cfg
      ansible.builtin.file:
        path: /boot/grub2/user.cfg
        mode: u-s,g-xwrs,o-xwrt
      when:
      - '"/boot/efi" in ansible_mounts | map(attribute="mount") | list'
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-171-3.4.5
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_efi_user_cfg
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Set the UEFI Boot Loader Password [ref]

The grub2 boot loader should have a superuser account and password protection enabled to protect boot-time settings.
Since plaintext passwords are a security risk, generate a hash for the password by running the following command:

    # grub2-setpassword

When prompted, enter the password that was selected.
Warning: To prevent hard-coded passwords, automatic remediation of this control is not available. Remediation must be automated as a component of machine provisioning, or followed manually as outlined above. Also, do NOT manually add the superuser account and password to the `grub.cfg` file as the grub2-mkconfig command overwrites this file.

Rationale: | Password protection on the boot loader configuration ensures users with physical access cannot trivially alter important bootloader settings. These include which kernel to use, and whether to enter single-user mode.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_uefi_password

References:

cis-csc | 11, 12, 14, 15, 16, 18, 3, 5
cobit5 | DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.03, DSS06.06
cui | 3.4.5
hipaa | 164.308(a)(1)(ii)(B), 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.310(a)(1), 164.310(a)(2)(i), 164.310(a)(2)(ii), 164.310(a)(2)(iii), 164.310(b), 164.310(c), 164.310(d)(1), 164.310(d)(2)(iii)
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7
iso27001-2013 | A.6.1.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a)
nist-csf | PR.AC-4, PR.AC-6, PR.PT-3
ospp | FIA_UAU.1
os-srg | SRG-OS-000080-GPOS-00048
anssi | R5

#### Rule IOMMU configuration directive [ref]

On x86 architecture supporting VT-d, the IOMMU manages the access control policy between the hardware devices and some of the system critical units such as the memory. Configure the default Grub2 kernel command line to contain iommu=force as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) iommu=force"

Warning: Depending on the hardware, devices and operating system used, enabling IOMMU can cause hardware instabilities. Proper function and stability should be assessed before applying remediation to production systems.

Rationale: | On x86 architectures, activating the I/OMMU prevents the system from arbitrary accesses potentially made by hardware devices.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_enable_iommu_force

References:

anssi | R7

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "iommu" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"iommu=[^\"]*\"(.*]\s*)/\1\"iommu=force\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"iommu=force\"]" >> "$KARGS_DIR/10-iommu.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

    - name: Check iommu argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*iommu=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

    - name: Check iommu argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

    - name: Add iommu argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="iommu=force "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

    - name: Replace existing iommu argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: iommu=[a-zA-Z0-9,]+
        replace: iommu=force
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

    - name: Add iommu argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 iommu=force"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_enable_iommu_force
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
      - unknown_severity

#### Rule Configure L1 Terminal Fault mitigations [ref]

L1 Terminal Fault (L1TF) is a hardware vulnerability which allows unprivileged speculative access to data which is available in the Level 1 Data Cache when the page table entry isn't present. Select the appropriate mitigation by adding the argument `l1tf=full,force` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain l1tf=full,force as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) l1tf=full,force"

Since Linux Kernel 4.19 you can check the L1TF vulnerability state with the following command: `cat /sys/devices/system/cpu/vulnerabilities/l1tf`
Warning: Enabling L1TF mitigations may impact performance of the system.

Rationale: | The L1TF vulnerability allows an attacker to bypass memory access security controls imposed by the system or hypervisor. The L1TF vulnerability allows read access to any physical memory location that is cached in the L1 Data Cache.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_l1tf_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    var_l1tf_options='full,force'

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "l1tf" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"l1tf=[^\"]*\"(.*]\s*)/\1\"l1tf=$var_l1tf_options\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"l1tf=$var_l1tf_options\"]" >> "$KARGS_DIR/10-l1tf.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_l1tf_options # promote to variable
      set_fact:
        var_l1tf_options: !!str full,force
      tags:
        - always

    - name: Check l1tf argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*l1tf=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check l1tf argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add l1tf argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="l1tf={{ var_l1tf_options }} "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Replace existing l1tf argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: l1tf=[a-zA-Z0-9,]+
        replace: l1tf={{ var_l1tf_options }}
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add l1tf argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 l1tf={{ var_l1tf_options }}"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_l1tf_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

#### Rule Force kernel panic on uncorrected MCEs [ref]

A Machine Check Exception is an error generated by the CPU itdetects an error in itself, memory or I/O devices. These errors may be corrected and generate a check log entry, if an error cannot be corrected the kernel may panic or SIGBUS. To force the kernel to panic on any uncorrected error reported by Machine Check set the MCE tolerance to zero by adding `mce=0` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain mce=0 as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) mce=0"

Rationale: | Allowing uncorrected errors to result on a SIGBUS may allow an attacker to continue trying to exploit a vulnerability such as Rowhammer.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_mce_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "mce" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"mce=[^\"]*\"(.*]\s*)/\1\"mce=0\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"mce=0\"]" >> "$KARGS_DIR/10-mce.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check mce argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*mce=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check mce argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add mce argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="mce=0 "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing mce argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: mce=[a-zA-Z0-9,]+
        replace: mce=0
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add mce argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 mce=0"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_mce_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Configure Microarchitectural Data Sampling mitigation [ref]

Microarchitectural Data Sampling (MDS) is a hardware vulnerability which allows unprivileged speculative access to data which is available in various CPU internal buffers. When performing store, load, L1 refill operations, processors write data into temporary microarchitectural structures (buffers), and the data in the buffer can be forwarded to load operations as an optimization. Under certain conditions, data unrelated to the load operations can be speculatively forwarded from the buffers to a disclosure gadget which allows in turn to infer the value via a cache side channel attack. Select the appropriate mitigation by adding the argument `mds=full,nosmt` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain mds=full,nosmt as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) mds=full,nosmt"

Not all processors are affected by all variants of MDS, but the mitigation mechanism is identical for all of them. Since Linux Kernel 5.2 you can check whether the system is vulnerable or mitigated with the following command: `cat /sys/devices/system/cpu/vulnerabilities/mds`
Warning: Enabling MDS mitigations will impact performance of the system, mainly by workloads with high rates of user-kernel-user space transitions. For example, system calls, NMIs and interrupts.

Rationale: | The MDS vulnerability allows an attacker to sample data from internal CPU buffers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_mds_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    var_mds_options='full,nosmt'

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "mds" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"mds=[^\"]*\"(.*]\s*)/\1\"mds=$var_mds_options\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"mds=$var_mds_options\"]" >> "$KARGS_DIR/10-mds.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_mds_options # promote to variable
      set_fact:
        var_mds_options: !!str full,nosmt
      tags:
        - always

    - name: Check mds argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*mds=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check mds argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add mds argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="mds={{ var_mds_options }} "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing mds argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: mds=[a-zA-Z0-9,]+
        replace: mds={{ var_mds_options }}
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add mds argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 mds={{ var_mds_options }}"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_mds_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure SMAP is not disabled during boot [ref]

The SMAP is used to prevent the supervisor mode from unintentionally reading/writing into memory pages in the user space, it is enabled by default since Linux kernel 3.7. But it could be disabled through kernel boot parameters. Ensure that Supervisor Mode Access Prevention (SMAP) is not disabled by the `nosmap` boot parameter option. Check that the line

    GRUB_CMDLINE_LINUX="..."

within `/etc/default/grub` doesn't contain the argument `nosmap`. Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --remove-args="nosmap"

Rationale: | Disabling SMAP can facilitate exploitation of vulnerabilities caused by unintended access and manipulation of data in the user space.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_nosmap_argument_absent

References:

anssi | R1

#### Rule Ensure SMEP is not disabled during boot [ref]

The SMEP is used to prevent the supervisor mode from executing user space code, it is enabled by default since Linux kernel 3.0. But it could be disabled through kernel boot parameters. Ensure that Supervisor Mode Execution Prevention (SMEP) is not disabled by the `nosmep` boot parameter option. Check that the line

    GRUB_CMDLINE_LINUX="..."

within `/etc/default/grub` doesn't contain the argument `nosmep`. Run the following command to update command line for already installed kernels:

    # grubby --update-kernel=ALL --remove-args="nosmep"

Rationale: | Disabling SMEP can facilitate exploitation of certain vulnerabilities because it allows the kernel to unintentionally execute code in less privileged memory space.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_nosmep_argument_absent

References:

anssi | R1

#### Rule Enable randomization of the page allocator [ref]

To enable randomization of the page allocator in the kernel, add the `page_alloc.shuffle=1` argument to the default GRUB 2 command line. Configure the default Grub2 kernel command line to contain page_alloc.shuffle=1 as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) page_alloc.shuffle=1"

Rationale:

The `CONFIG_SHUFFLE_PAGE_ALLOCATOR` config option is primarily focused on improving the average utilization of a direct-mapped memory-side-cache. Aside of this performance effect, it also reduces predictability of page allocations in situations when the bad actor can crash the system and somehow leverage knowledge of (page) allocation order right after a fresh reboot, or can control the timing between a hot-pluggable memory node (as in NUMA node) and applications allocating memory ouf of that node. The `page_alloc.shuffle=1` kernel command line parameter then forces this functionality irrespectively of memory cache architecture.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_page_alloc_shuffle_argument

References:

ospp | AVA_VAN.1
anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "page_alloc.shuffle" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"page_alloc.shuffle=[^\"]*\"(.*]\s*)/\1\"page_alloc.shuffle=1\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"page_alloc.shuffle=1\"]" >> "$KARGS_DIR/10-page_alloc_shuffle.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check page_alloc.shuffle argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*page_alloc.shuffle=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check page_alloc.shuffle argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add page_alloc.shuffle argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="page_alloc.shuffle=1 "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing page_alloc.shuffle argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: page_alloc.shuffle=[a-zA-Z0-9,]+
        replace: page_alloc.shuffle=1
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add page_alloc.shuffle argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 page_alloc.shuffle=1"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_page_alloc_shuffle_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Enable Kernel Page-Table Isolation (KPTI) [ref]

To enable Kernel page-table isolation, add the argument `pti=on` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain pti=on as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) pti=on"

Rationale: | Kernel page-table isolation is a kernel feature that mitigates the Meltdown security vulnerability and hardens the kernel against attempts to bypass kernel address space layout randomization (KASLR).
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_pti_argument

References:

nist | SI-16
os-srg | SRG-OS-000433-GPOS-00193, SRG-OS-000095-GPOS-00049
anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "pti" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"pti=[^\"]*\"(.*]\s*)/\1\"pti=on\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"pti=on\"]" >> "$KARGS_DIR/10-pti.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check pti argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*pti=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check pti argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add pti argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="pti=on "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Replace existing pti argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: pti=[a-zA-Z0-9,]+
        replace: pti=on
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add pti argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 pti=on"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - NIST-800-53-SI-16
      - grub2_pti_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

#### Rule Configure the confidence in TPM for entropy [ref]

The TPM security chip that is available in most modern systems has a hardware RNG. It is also used to feed the entropy pool, but generally not credited entropy. Use `rng_core.default_quality` in the kernel command line to set the trust level on the hardware generators. The trust level defines the amount of entropy to credit. A value of `0` tells the system not to trust the hardware random number generators available, and doesn't credit any entropy to the pool. A value of `1000` assigns full confidence in the generators, and credits all the entropy it provides to the pool. Note that the value of `rng_core.default_quality` is global, affecting the trust on all hardware random number generators. Select the appropriate confidence by adding the argument `rng_core.default_quality=500` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain rng_core.default_quality=500 as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) rng_core.default_quality=500"

Rationale: | A system may struggle to initialize its entropy pool and end up starving. Crediting entropy from the hardware number generators available in the system helps fill up the entropy pool.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_rng_core_default_quality_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    var_rng_core_default_quality='500'

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "rng_core.default_quality" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"rng_core.default_quality=[^\"]*\"(.*]\s*)/\1\"rng_core.default_quality=$var_rng_core_default_quality\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"rng_core.default_quality=$var_rng_core_default_quality\"]" >> "$KARGS_DIR/10-rng_core_default_quality.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_rng_core_default_quality # promote to variable
      set_fact:
        var_rng_core_default_quality: !!str 500
      tags:
        - always

    - name: Check rng_core.default_quality argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*rng_core.default_quality='
        /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check rng_core.default_quality argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add rng_core.default_quality argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="rng_core.default_quality={{ var_rng_core_default_quality
          }} "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Replace existing rng_core.default_quality argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: rng_core.default_quality=[a-zA-Z0-9,]+
        replace: rng_core.default_quality={{ var_rng_core_default_quality }}
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add rng_core.default_quality argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 rng_core.default_quality={{ var_rng_core_default_quality }}"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_rng_core_default_quality_argument
      - low_disruption
      - low_severity
      - medium_complexity
      - reboot_required
      - restrict_strategy

#### Rule Disable merging of slabs with similar size [ref]

The kernel may merge similar slabs together to reduce overhead and increase cache hotness of objects. Disabling merging of slabs keeps the slabs separate and reduces the risk of kernel heap overflows overwriting objects in merged caches. To disable merging of slabs in the Kernel add the argument `slab_nomerge=yes` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain slab_nomerge=yes as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) slab_nomerge=yes"

Warning: Disabling merge of slabs will slightly increase kernel memory utilization.

Rationale:

Disabling the merge of slabs of similar sizes prevents the kernel from merging a seemingly useless but vulnerable slab with a useful and valuable slab. This increase the risk that a heap overflow could overwrite objects from merged caches, with unmerged caches the heap overflow would only affect the objects in the same cache. Overall, this reduces the kernel attack surface area by isolating slabs from each other.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_slab_nomerge_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "slab_nomerge" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"slab_nomerge=[^\"]*\"(.*]\s*)/\1\"slab_nomerge=yes\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"slab_nomerge=yes\"]" >> "$KARGS_DIR/10-slab_nomerge.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check slab_nomerge argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*slab_nomerge=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check slab_nomerge argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add slab_nomerge argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="slab_nomerge=yes "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing slab_nomerge argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: slab_nomerge=[a-zA-Z0-9,]+
        replace: slab_nomerge=yes
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add slab_nomerge argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 slab_nomerge=yes"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_slab_nomerge_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Configure Speculative Store Bypass Mitigation [ref]

Certain CPUs are vulnerable to an exploit against a common wide industry wide performance optimization known as Speculative Store Bypass (SSB). In such cases, recent stores to the same memory location cannot always be observed by later loads during speculative execution. However, such stores are unlikely and thus they can be detected prior to instruction retirement at the end of a particular speculation execution window. Since Linux Kernel 4.17 you can check the SSB mitigation state with the following command: `cat /sys/devices/system/cpu/vulnerabilities/spec_store_bypass` Select the appropriate SSB state by adding the argument `spec_store_bypass_disable=seccomp` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain spec_store_bypass_disable=seccomp as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) spec_store_bypass_disable=seccomp"

Warning: Disabling Speculative Store Bypass may impact performance of the system.

Rationale: | In vulnerable processors, the speculatively forwarded store can be used in a cache side channel attack. An example of this is reading memory to which the attacker does not directly have access, for example inside the sandboxed code.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_spec_store_bypass_disable_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    var_spec_store_bypass_disable_options='seccomp'

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "spec_store_bypass_disable" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"spec_store_bypass_disable=[^\"]*\"(.*]\s*)/\1\"spec_store_bypass_disable=$var_spec_store_bypass_disable_options\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"spec_store_bypass_disable=$var_spec_store_bypass_disable_options\"]" >> "$KARGS_DIR/10-spec_store_bypass_disable.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_spec_store_bypass_disable_options # promote to variable
      set_fact:
        var_spec_store_bypass_disable_options: !!str seccomp
      tags:
        - always

    - name: Check spec_store_bypass_disable argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*spec_store_bypass_disable='
        /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check spec_store_bypass_disable argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add spec_store_bypass_disable argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="spec_store_bypass_disable={{ var_spec_store_bypass_disable_options
          }} "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing spec_store_bypass_disable argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: spec_store_bypass_disable=[a-zA-Z0-9,]+
        replace: spec_store_bypass_disable={{ var_spec_store_bypass_disable_options }}
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add spec_store_bypass_disable argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 spec_store_bypass_disable={{ var_spec_store_bypass_disable_options
          }}"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_spec_store_bypass_disable_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Enforce Spectre v2 mitigation [ref]

Spectre V2 is an indirect branch poisoning attack that can lead to data leakage. An exploit for Spectre V2 tricks the indirect branch predictor into executing code from a future indirect branch chosen by the attacker, even if the privilege level is different. Since Linux Kernel 4.15 you can check the Spectre V2 mitigation state with the following command: `cat /sys/devices/system/cpu/vulnerabilities/spectre_v2` Enforce the Spectre V2 mitigation by adding the argument `spectre_v2=on` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain spectre_v2=on as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) spectre_v2=on"

Rationale: | The Spectre V2 vulnerability allows an attacker to read memory that he should not have access to.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_spectre_v2_argument

References:

anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "spectre_v2" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"spectre_v2=[^\"]*\"(.*]\s*)/\1\"spectre_v2=on\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"spectre_v2=on\"]" >> "$KARGS_DIR/10-spectre_v2.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check spectre_v2 argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*spectre_v2=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Check spectre_v2 argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add spectre_v2 argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="spectre_v2=on "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Replace existing spectre_v2 argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: spectre_v2=[a-zA-Z0-9,]+
        replace: spectre_v2=on
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Add spectre_v2 argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 spectre_v2=on"
      when:
      - ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when: ( "grub2-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )
      tags:
      - grub2_spectre_v2_argument
      - high_severity
      - low_disruption
      - medium_complexity
      - reboot_required
      - restrict_strategy

Group Kernel Configuration Group contains 1 group and 67 rules
[ref] Contains rules that check the kernel configuration that was used to build it.
Group Kernel GCC plugin configuration Group contains 5 rules
[ref] Contains rules that check the configuration of GCC plugins used by the compiler

#### Rule Generate some entropy during boot and runtime [ref]

Instrument some kernel code to extract some entropy from both original and artificially created program state. This will help especially embedded systems where there is little 'natural' source of entropy normally. This configuration is available from kernel 4.9, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_GCC_PLUGIN_LATENT_ENTROPY`, run the following command: `grep CONFIG_GCC_PLUGIN_LATENT_ENTROPY /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.
Warning: Note that entropy extracted this way is not cryptographically secure!
Warning: There is a performance cost during the boot process (about 0.5%) and fork and irq processing.

Rationale: | This helps generate entropy during startup and is particularly relevant for devices with inappropriate entropy sources.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_gcc_plugin_latent_entropy

References:

anssi | R21

#### Rule Randomize layout of sensitive kernel structures [ref]

Randomize at compile-time the layouts of structures that are entirely function pointers (and have not been manually annotated with __no_randomize_layout), or structures that have been explicitly marked with __randomize_layout. This configuration is available from kernel 4.13, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_GCC_PLUGIN_RANDSTRUCT`, run the following command: `grep CONFIG_GCC_PLUGIN_RANDSTRUCT /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Randomizing the layout of kernel data structures make it more difficult for an attacker to know the location of sensitive data.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_gcc_plugin_randstruct

References:

anssi | R21

#### Rule Poison kernel stack before returning from syscalls [ref]

This option makes the kernel erase the kernel stack before returning from system calls. This has the effect of leaving the stack initialized to the poison value, which both reduces the lifetime of any sensitive stack contents and reduces potential for uninitialized stack variable exploits or information exposures (it does not cover functions reaching the same stack depth as prior functions during the same syscall). This configuration is available from kernel 4.20, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_GCC_PLUGIN_STACKLEAK`, run the following command: `grep CONFIG_GCC_PLUGIN_STACKLEAK /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.
Warning: The performance impact on a single CPU system kernel is of 1% slowdown.

Rationale: | This blocks most uninitialized stack variable attacks, with the performance impact being driven by the depth of the stack usage, rather than the function calling complexity.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_gcc_plugin_stackleak

References:

anssi | R21

#### Rule Force initialization of variables containing userspace addresses [ref]

While the kernel is built with warnings enabled for any missed stack variable initializations, this warning is silenced for anything passed by reference to another function, under the occasionally misguided assumption that the function will do the initialization. As this regularly leads to exploitable flaws, this plugin is available to identify and zero-initialize such variables, depending on the chosen level of coverage. This configuration is available from kernel 4.11, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_GCC_PLUGIN_STRUCTLEAK`, run the following command: `grep CONFIG_GCC_PLUGIN_STRUCTLEAK /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Initializing structures from userspace can prevent some classes of information exposure.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_gcc_plugin_structleak

References:

anssi | R21

#### Rule zero-init everything passed by reference [ref]

Zero-initialize any stack variables that may be passed by reference and had not already been explicitly initialized. This configuration is available from kernel 4.14, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL`, run the following command: `grep CONFIG_GCC_PLUGIN_STRUCTLEAK_BYREF_ALL /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This eliminates all classes of uninitialized stack variable exploits and information exposures.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_gcc_plugin_structleak_byref_all

References:

anssi | R21

#### Rule Do not allow ACPI methods to be inserted/replaced at run time [ref]

This debug facility allows ACPI AML methods to be inserted and/or replaced without rebooting the system. This configuration is available from kernel 3.0. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_ACPI_CUSTOM_METHOD`, run the following command: `grep CONFIG_ACPI_CUSTOM_METHOD /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Enabling this feature allows arbitrary kernel memory to be written to by root (uid=0) users, allowing them to bypass certain security measures
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_acpi_custom_method

References:

anssi | R15

#### Rule Emulate Privileged Access Never (PAN) [ref]

Enabling this option prevents the kernel from accessing user-space memory directly by pointing TTBR0_EL1 to a reserved zeroed area and reserved ASID. The user access routines restore the valid TTBR0_EL1 temporarily. This configuration is available from kernel 4.10, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_ARM64_SW_TTBR0_PAN`, run the following command: `grep CONFIG_ARM64_SW_TTBR0_PAN /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | The Privileged Access Never (PAN) is the ARM equivalent of the x86 Supervisor Mode Access Prevention (SMAP), and it prevents privileged access to user data unless explicitly enabled.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_arm64_sw_ttbr0_pan

References:

anssi | R27

#### Rule Disable kernel support for MISC binaries [ref]

Enabling `CONFIG_BINFMT_MISC` makes it possible to plug wrapper-driven binary formats into the kernel. This is specially useful for programs that need an interpreter to run like Java, Python and DOS emulators. Once you have registered such a binary class with the kernel, you can start one of those programs simply by typing in its name at a shell prompt. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_BINFMT_MISC`, run the following command: `grep CONFIG_BINFMT_MISC /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This disables arbitrary binary format support and helps reduce attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_binfmt_misc

References:

anssi | R23

#### Rule Enable support for BUG() [ref]

Disabling this option eliminates support for BUG and WARN, reducing the size of your kernel image and potentially quietly ignoring numerous fatal conditions. You should only consider disabling this option for embedded systems with no facilities for reporting errors. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_BUG`, run the following command: `grep CONFIG_BUG /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Not setting this variable may hide a number of critical errors.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_bug

References:

anssi | R19

#### Rule Trigger a kernel BUG when data corruption is detected [ref]

This option makes the kernel BUG when it encounters data corruption in kernel memory structures when they get checked for validity. This configuration is available from kernel 4.10. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_BUG_ON_DATA_CORRUPTION`, run the following command: `grep CONFIG_BUG_ON_DATA_CORRUPTION /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This helps detect data corruptions early and stop with a BUG() error message.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_bug_on_data_corruption

References:

anssi | R16

#### Rule Disable compatibility with brk() [ref]

Enabling compatiliby with `brk()` allows legacy binaries to run (i.e. those linked against libc5). But this compatibility comes at the cost of not being able to randomize the heap placement (ASLR). Unless legacy binaries need to run on the system, set `CONFIG_COMPAT_BRK` to `"n"`. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_COMPAT_BRK`, run the following command: `grep CONFIG_COMPAT_BRK /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Enabling compatibility with brk() disables support for ASLR.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_compat_brk

References:

anssi | R17

#### Rule Disable the 32-bit vDSO [ref]

Certain buggy versions of glibc (2.3.3) will crash if they are presented with a 32-bit vDSO that is not mapped at the address indicated in its segment table. Setting `CONFIG_COMPAT_VDSO` to `y` turns off the 32-bit VDSO and works around the glibc bug. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_COMPAT_VDSO`, run the following command: `grep CONFIG_COMPAT_VDSO /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Enabling VDSO compatibility hurts performance and disables ASLR.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_compat_vdso

References:

anssi | R15

#### Rule Enable checks on credential management [ref]

Enable this to turn on some debug checking for credential management. The additional code keeps track of the number of pointers from task_structs to any given cred struct, and checks to see that this number never exceeds the usage count of the cred struct. Furthermore, if SELinux is enabled, this also checks that the security pointer in the cred struct is never seen to be invalid. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEBUG_CREDENTIALS`, run the following command: `grep CONFIG_DEBUG_CREDENTIALS /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This adds sanity checks and validations to credential data structures.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_debug_credentials

References:

anssi | R16

#### Rule Disable kernel debugfs [ref]

`debugfs` is a virtual file system that kernel developers use to put debugging files into. Enable this option to be able to read and write to these files. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEBUG_FS`, run the following command: `grep CONFIG_DEBUG_FS /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | To reduce the attack surface, this file system should be disabled if not in use.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_debug_fs

References:

anssi | R15

#### Rule Enable checks on linked list manipulation [ref]

Enable this to turn on extended checks in the linked-list walking routines. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEBUG_LIST`, run the following command: `grep CONFIG_DEBUG_LIST /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This add sanity checks to manipulation of linked lists structures in the kernel and may prevent exploits such as CVE-2017-1661, where a race condition and simultaneous operations caused a list to corrupt.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_debug_list

References:

anssi | R16

#### Rule Enable checks on notifier call chains [ref]

Enable this to turn on sanity checking for notifier call chains. This is most useful for kernel developers to make sure that modules properly unregister themselves from notifier chains. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEBUG_NOTIFIERS`, run the following command: `grep CONFIG_DEBUG_NOTIFIERS /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This provides validation of notifier chains, it checks whether the notifiers are from the kernel or a module that is still loaded prior to being invoked.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_debug_notifiers

References:

anssi | R16

#### Rule Enable checks on scatter-gather (SG) table operations [ref]

Scatter-gather tables are mechanism used for high performance I/O on DMA devices. Enable this to turn on checks on scatter-gather tables. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEBUG_SG`, run the following command: `grep CONFIG_DEBUG_SG /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This can help find problems with drivers that do not properly initialize their SG tables.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_debug_sg

References:

anssi | R16

#### Rule Warn on W+X mappings found at boot [ref]

Generate a warning if any W+X mappings are found at boot. This configuration is available from kernel 5.8. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEBUG_WX`, run the following command: `grep CONFIG_DEBUG_WX /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This is useful for discovering cases where the kernel is leaving W+X mappings after applying NX, as such mappings are a security risk. Note that even if the check fails, your kernel is possibly still fine, as W+X mappings are not a security hole in themselves, what they do is that they make the exploitation of other unfixed kernel bugs easier.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_debug_wx

References:

anssi | R15

#### Rule Configure Low Address Space To Protect From User Allocation [ref]

This is the portion of low virtual memory which should be protected from userspace allocation. This configuration is available from kernel 3.14, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEFAULT_MMAP_MIN_ADDR`, run the following command: `grep CONFIG_DEFAULT_MMAP_MIN_ADDR /boot/config-*` For each kernel installed, a line with value should be returned. If the system architecture is x86_64, the value should be 65536. If the system architecture is aarch64, the value should be 32768.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Keeping a user from writing to low pages can help reduce the impact of kernel NULL pointer bugs.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_default_mmap_min_addr

References:

anssi | R25, R27

#### Rule Disable /dev/kmem virtual device support [ref]

Disable support for the /dev/kmem device. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_DEVKMEM`, run the following command: `grep CONFIG_DEVKMEM /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | The /dev/kmem device is rarely used, but can be used for certain kind of kernel debugging operations.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_devkmem

References:

anssi | R15

#### Rule Harden common str/mem functions against buffer overflows [ref]

Detect overflows of buffers in common string and memory functions where the compiler can determine and validate the buffer sizes. This configuration is available from kernel 4.13, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_FORTIFY_SOURCE`, run the following command: `grep CONFIG_FORTIFY_SOURCE /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This features helps reduce likelihood of memory corruption of kernel structures.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_fortify_source

References:

anssi | R15

#### Rule Harden memory copies between kernel and userspace [ref]

This option checks for obviously wrong memory regions when copying memory to/from the kernel (via copy_to_user() and copy_from_user() functions) by rejecting memory ranges that are larger than the specified heap object, span multiple separately allocated pages, are not on the process stack, or are part of the kernel text. This configuration is available from kernel 4.8, and may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_HARDENED_USERCOPY`, run the following command: `grep CONFIG_HARDENED_USERCOPY /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This config prevents entire classes of heap overflow exploits and similar kernel memory exposures.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_hardened_usercopy

References:

anssi | R15

#### Rule Do not allow usercopy whitelist violations to fallback to object size [ref]

This is a temporary option that allows missing usercopy whitelists to be discovered via a WARN() to the kernel log, instead of rejecting the copy, falling back to non-whitelisted hardened usercopy that checks the slab allocation size instead of the whitelist size. This configuration is available from kernel 4.16. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_HARDENED_USERCOPY_FALLBACK`, run the following command: `grep CONFIG_HARDENED_USERCOPY_FALLBACK /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This config prevents entire classes of heap overflow exploits and similar kernel memory exposures.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_hardened_usercopy_fallback

References:

anssi | R15

#### Rule Disable hibernation [ref]

Enable the suspend to disk (STD) functionality, which is usually called "hibernation" in user interfaces. STD checkpoints the system and powers it off; and restores that checkpoint on reboot. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_HIBERNATION`, run the following command: `grep CONFIG_HIBERNATION /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Suspending to disk allows one to replace the running kernel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_hibernation

References:

anssi | R23

#### Rule Disable IA32 emulation [ref]

Disables support for legacy 32-bit programs under a 64-bit kernel. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_IA32_EMULATION`, run the following command: `grep CONFIG_IA32_EMULATION /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.
Warning: Only disable support for 32-bit programs if you are sure you don't need any 32-bit program.

Rationale: | Disabling 32-bit backwards compatibility helps reduce the attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_ia32_emulation

References:

anssi | R25

#### Rule Disable kexec system call [ref]

`kexec` is a system call that implements the ability to shutdown your current kernel, and to start another kernel. It is like a reboot but it is independent of the system firmware. And like a reboot you can start any kernel with it, not just Linux. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_KEXEC`, run the following command: `grep CONFIG_KEXEC /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Prohibits the execution of a new kernel image after reboot.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_kexec

References:

anssi | R23

#### Rule Disable legacy (BSD) PTY support [ref]

Disable the Linux traditional BSD-like terminal names /dev/ptyxx for masters and /dev/ttyxx for slaves of pseudo terminals, and use only the modern ptys (devpts) interface. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_LEGACY_PTYS`, run the following command: `grep CONFIG_LEGACY_PTYS /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | The legacy scheme has a number of security problems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_legacy_ptys

References:

anssi | R23

#### Rule Disable vsyscall emulation [ref]

The kernel traps and emulates calls into the fixed vsyscall address mapping. This configuration is available from kernel 5.3, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_LEGACY_VSYSCALL_EMULATE`, run the following command: `grep CONFIG_LEGACY_VSYSCALL_EMULATE /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | The mapping is non-executable, but it still contains known contents, which could be used in certain rare security vulnerability exploits.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_legacy_vsyscall_emulate

References:

anssi | R15

#### Rule Disable vsyscall mapping [ref]

This config disables the vsyscall mapping at all. Attempts to use the vsyscalls will be reported to dmesg, so that either old or malicious userspace programs can be identified. This configuration is available from kernel 4.4. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_LEGACY_VSYSCALL_NONE`, run the following command: `grep CONFIG_LEGACY_VSYSCALL_NONE /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This will eliminate any risk of ASLR bypass due to the vsyscall fixed address mapping.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_legacy_vsyscall_none

References:

anssi | R15

#### Rule Disable vsyscall emulate execution only [ref]

The kernel traps and emulates calls into the fixed vsyscall address mapping and does not allow reads. This configuration is available from kernel 5.3. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_LEGACY_VSYSCALL_XONLY`, run the following command: `grep CONFIG_LEGACY_VSYSCALL_XONLY /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Disabling this mitigates certain uses of the vsyscall area as an ASLR-bypassing buffer.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_legacy_vsyscall_xonly

References:

anssi | R15

#### Rule Disable the LDT (local descriptor table) [ref]

Linux can allow user programs to install a per-process x86 Local Descriptor Table (LDT) using the modify_ldt(2) system call. This is required to run 16-bit or segmented code such as DOSEMU or some Wine programs. It is also used by some very old threading libraries. This configuration is available from kernel 4.3, but may be available if backported by distros. Disable LDT if 16-bit program emulation is not necessary. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODIFY_LDT_SYSCALL`, run the following command: `grep CONFIG_MODIFY_LDT_SYSCALL /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Disabling support for unnecessary code reduces attack surface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_modify_ldt_syscall

References:

anssi | R25

#### Rule Enable module signature verification [ref]

Check modules for valid signatures upon load. Note that this option adds the OpenSSL development packages as a kernel build dependency so that the signing tool can use its crypto library. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODULE_SIG`, run the following command: `grep CONFIG_MODULE_SIG /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Loaded modules must be signed.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_module_sig

References:

anssi | R18

#### Rule Enable automatic signing of all modules [ref]

Sign all modules during make modules_install. Without this option, modules must be signed manually, using the scripts/sign-file tool. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODULE_SIG_ALL`, run the following command: `grep CONFIG_MODULE_SIG_ALL /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This ensures the modules are signed during install process.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_module_sig_all

References:

anssi | R18

#### Rule Require modules to be validly signed [ref]

Reject unsigned modules or signed modules with an unknown key. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODULE_SIG_FORCE`, run the following command: `grep CONFIG_MODULE_SIG_FORCE /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Prevent loading modules that are unsigned or signed with an unknown key.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_module_sig_force

References:

anssi | R18

#### Rule Specify the hash to use when signing modules [ref]

This configures the kernel to build and sign modules using sha512 as the hash function. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODULE_SIG_HASH`, run the following command: `grep CONFIG_MODULE_SIG_HASH /boot/config-*` For each kernel installed, a line with value "sha512" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Use of strong hash function is important to secure the module against counterfeit signatures.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_module_sig_hash

References:

anssi | R18

#### Rule Specify module signing key to use [ref]

Setting this option to something other than its default of `certs/signing_key.pem` will disable the autogeneration of signing keys and allow the kernel modules to be signed with a key of your choosing. The string provided should identify a file containing both a private key and its corresponding X.509 certificate in PEM form, or — on systems where the OpenSSL ENGINE_pkcs11 is functional — a PKCS#11 URI as defined by RFC7512. In the latter case, the PKCS#11 URI should reference both a certificate and a private key. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODULE_SIG_KEY`, run the following command: `grep CONFIG_MODULE_SIG_KEY /boot/config-*` For each kernel installed, a line with value "certs/signing_key.pem" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | A key and certificate is required to sign the built modules.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_module_sig_key

References:

anssi | R18

#### Rule Sign kernel modules with SHA-512 [ref]

This configures the kernel to build and sign modules using SHA512 as the hash function. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_MODULE_SIG_SHA512`, run the following command: `grep CONFIG_MODULE_SIG_SHA512 /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Use of strong hash function is important to secure the module against counterfeit signatures.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_module_sig_sha512

References:

anssi | R18

#### Rule Enable poison of pages after freeing [ref]

Fill the pages with poison patterns after free_pages() and verify the patterns before alloc_pages. This does have a potential performance impact if enabled with the "page_poison=1" kernel boot option. This configuration is available from kernel 4.6. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PAGE_POISONING`, run the following command: `grep CONFIG_PAGE_POISONING /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | The filling of the memory helps reduce the risk of information leaks from freed data.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_page_poisoning

References:

anssi | R17

#### Rule Enable poison without sanity check [ref]

Skip the sanity checking on alloc, only fill the pages with poison on free. This reduces some of the overhead of the poisoning feature. This configuration is available from kernel 4.6. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PAGE_POISONING_NO_SANITY`, run the following command: `grep CONFIG_PAGE_POISONING_NO_SANITY /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This configuration helps alleviates the performance impact of poisonining.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_page_poisoning_no_sanity

References:

anssi | R17

#### Rule Use zero for poisoning instead of debugging value [ref]

Instead of using the existing poison value, fill the pages with zeros. This makes it harder to detect when errors are occurring due to sanitization but the zeroing at free means that it is no longer necessary to write zeros when GFP_ZERO is used on allocation. This configuration is available from kernel 4.19. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PAGE_POISONING_ZERO`, run the following command: `grep CONFIG_PAGE_POISONING_ZERO /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This configuration helps alleviates the performance impact of poisonining.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_page_poisoning_zero

References:

anssi | R17

#### Rule Remove the kernel mapping in user mode [ref]

This feature reduces the number of hardware side channels by ensuring that the majority of kernel addresses are not mapped into userspace. This configuration is available from kernel 4.15, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PAGE_TABLE_ISOLATION`, run the following command: `grep CONFIG_PAGE_TABLE_ISOLATION /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This is a countermeasure to the Meltdown attack.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_page_table_isolation

References:

anssi | R25

#### Rule Kernel panic oops [ref]

Enable the kernel to panic when it oopses. This has the same effect as setting oops=panic on the kernel command line. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PANIC_ON_OOPS`, run the following command: `grep CONFIG_PANIC_ON_OOPS /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This feature ensures that the kernel does not do anything erroneous after an oops which could result in data corruption or other issues.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_panic_on_oops

References:

anssi | R19

#### Rule Kernel panic timeout [ref]

Set the timeout value (in seconds) until a reboot occurs when the kernel panics. A timeout of 0 configures the system to wait forever. With a timeout value greater than 0, the system will wait the specified amount of seconds before rebooting. While a timeout value less than 0 makes the system reboot immediately. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PANIC_TIMEOUT`, run the following command: `grep CONFIG_PANIC_TIMEOUT /boot/config-*` For each kernel installed, a line with value "0" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This is required to enable protection against Spectre v2.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_panic_timeout

References:

anssi | R19

#### Rule Disable support for /proc/kkcore [ref]

Provides a virtual ELF core file of the live kernel. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_PROC_KCORE`, run the following command: `grep CONFIG_PROC_KCORE /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This feature exposes the memory to the userspace and can assist an attacker in discovering attack vectors.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_proc_kcore

References:

anssi | R15

#### Rule Randomize the address of the kernel image (KASLR) [ref]

In support of Kernel Address Space Layout Randomization (KASLR), this randomizes the physical address at which the kernel image is decompressed and the virtual address where the kernel image is mapped. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_RANDOMIZE_BASE`, run the following command: `grep CONFIG_RANDOMIZE_BASE /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | An unpredictable kernel address makes it more difficult to succeed with exploits that rely on knowledge of the location of kernel code internals.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_randomize_base

References:

anssi | R25, R27

#### Rule Randomize the kernel memory sections [ref]

Randomizes the base virtual address of kernel memory sections (physical memory mapping, vmalloc & vmemmap). This configuration is available from kernel 4.8, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_RANDOMIZE_MEMORY`, run the following command: `grep CONFIG_RANDOMIZE_MEMORY /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This security feature makes exploits relying on predictable memory locations less reliable.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_randomize_memory

References:

anssi | R25

#### Rule Perform full reference count validation [ref]

Enabling this switches the refcounting infrastructure from a fast unchecked atomic_t implementation to a fully state checked implementation, which can have a slight impact in performance. This configuration is available from kernel 4.13, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_REFCOUNT_FULL`, run the following command: `grep CONFIG_REFCOUNT_FULL /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Refcounting provides protections against various use-after-free conditions that can be used in security flaw exploits.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_refcount_full

References:

anssi | R15

#### Rule Avoid speculative indirect branches in kernel [ref]

Compile kernel with the retpoline compiler options to guard against kernel-to-user data leaks by avoiding speculative indirect branches. Requires a compiler with -mindirect-branch=thunk-extern support for full protection. The kernel may run slower. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_RETPOLINE`, run the following command: `grep CONFIG_RETPOLINE /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This is required to enable protection against Spectre v2.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_retpoline

References:

anssi | R15

#### Rule Detect stack corruption on calls to schedule() [ref]

This option checks for a stack overrun on calls to schedule(). If the stack end location is found to be overwritten always panic as the content of the corrupted region can no longer be trusted. This configuration is available from kernel 3.18. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SCHED_STACK_END_CHECK`, run the following command: `grep CONFIG_SCHED_STACK_END_CHECK /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This ensures no erroneous behaviour occurs which could result in data corruption or a sporadic crash at a later stage once the region is examined.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_sched_stack_end_check

References:

anssi | R15

#### Rule Enable seccomp to safely compute untrusted bytecode [ref]

This kernel feature is useful for number crunching applications that may need to compute untrusted bytecode during their execution. By using pipes or other transports made available to the process as file descriptors supporting the read/write syscalls, it's possible to isolate those applications in their own address space using seccomp. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SECCOMP`, run the following command: `grep CONFIG_SECCOMP /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | `seccomp` enables the ability to filter system calls made by an application, effectively isolating the system's resources from it.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_seccomp

References:

anssi | R20

#### Rule Enable use of Berkeley Packet Filter with seccomp [ref]

Enable tasks to build secure computing environments defined in terms of Berkeley Packet Filter programs which implement task-defined system call filtering polices. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SECCOMP_FILTER`, run the following command: `grep CONFIG_SECCOMP_FILTER /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Use of BPF filters allows for expressive filtering of system calls using a filter program language with a long history of being exposed to userland.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_seccomp_filter

References:

anssi | R20

#### Rule Enable different security models [ref]

This allows you to choose different security modules to be configured into your kernel. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SECURITY`, run the following command: `grep CONFIG_SECURITY /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This is enables kernel security primitives required by the LSM framework.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_security

References:

anssi | R20

#### Rule Restrict unprivileged access to the kernel syslog [ref]

Enforce restrictions on unprivileged users reading the kernel syslog via dmesg(8). The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SECURITY_DMESG_RESTRICT`, run the following command: `grep CONFIG_SECURITY_DMESG_RESTRICT /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Prevents unprivileged users from retrieving kernel addresses with dmesg.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_security_dmesg_restrict

References:

anssi | R15

#### Rule Disable mutable hooks [ref]

Ensure kernel structures associated with LSMs are always mapped as read-only after system boot. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SECURITY_WRITABLE_HOOKS`, run the following command: `grep CONFIG_SECURITY_WRITABLE_HOOKS /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | If CONFIG_SECURITY_WRITABLE_HOOKS is enabled, then hooks can be loaded at runtime and being able to manipulate hooks is a way to bypass all LSMs.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_security_writable_hooks

References:

anssi | R20

#### Rule Enable Yama support [ref]

This enables support for LSM module Yama, which extends DAC support with additional system-wide security settings beyond regular Linux discretionary access controls. The module will limit the use of the system call `ptrace()`. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SECURITY_YAMA`, run the following command: `grep CONFIG_SECURITY_YAMA /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Unrestricted usage of ptrace allows compromised binaries to run ptrace on another processes of the user.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_security_yama

References:

anssi | R20

#### Rule Harden slab freelist metadata [ref]

This feature protects integrity of the allocator's metadata. This configuration is available from kernel 4.14. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SLAB_FREELIST_HARDENED`, run the following command: `grep CONFIG_SLAB_FREELIST_HARDENED /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | Many kernel heap attacks try to target slab cache metadata and other infrastructure. This options makes minor performance sacrifices to harden the kernel slab allocator against common freelist exploit methods.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_slab_freelist_hardened

References:

anssi | R17

#### Rule Randomize slab freelist [ref]

Randomizes the freelist order used on creating new pages. This configuration is available from kernel 5.9, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SLAB_FREELIST_RANDOM`, run the following command: `grep CONFIG_SLAB_FREELIST_RANDOM /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This security feature reduces the predictability of the kernel slab allocator against heap overflows.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_slab_freelist_random

References:

anssi | R17

#### Rule Disallow merge of slab caches [ref]

For reduced kernel memory fragmentation, slab caches can be merged when they share the same size and other characteristics. This carries a risk of kernel heap overflows being able to overwrite objects from merged caches (and more easily control cache layout), which makes such heap attacks easier to exploit by attackers. This configuration is available from kernel 4.13. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SLAB_MERGE_DEFAULT`, run the following command: `grep CONFIG_SLAB_MERGE_DEFAULT /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale:

Disabling the merge of slabs of similar sizes prevents the kernel from merging a seemingly useless but vulnerable slab with a useful and valuable slab. This increase the risk that a heap overflow could overwrite objects from merged caches, with unmerged caches the heap overflow would only affect the objects in the same cache. Overall, this reduces the kernel attack surface area by isolating slabs from each other.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_slab_merge_default

References:

anssi | R17

#### Rule Enable SLUB debugging support [ref]

SLUB has extensive debug support features and this allows the allocator validation checking to be enabled. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SLUB_DEBUG`, run the following command: `grep CONFIG_SLUB_DEBUG /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This activates the checking of the memory allocator structures and resets to zero the zones allocated when they are released.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_slub_debug

References:

anssi | R17

#### Rule Stack Protector buffer overflow detection [ref]

This feature puts, at the beginning of functions, a canary value on the stack just before the return address, and validates the value just before actually returning. This configuration is available from kernel 4.18. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_STACKPROTECTOR`, run the following command: `grep CONFIG_STACKPROTECTOR /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This halts the program when a stack overflow is detected, potentially reducing the impact of exploits.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_stackprotector

References:

anssi | R15

#### Rule Strong Stack Protector [ref]

This features adds canary logic protection to more kinds of vulnerable functions than CONFIG_STACKPROTECTOR, but not to all functions so that performance is not severily impacted. This configuration is available from kernel 4.18. This config requires gcc version 4.9 or above, or a distribution gcc with the feature backported ("-fstack-protector-strong"). The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_STACKPROTECTOR_STRONG`, run the following command: `grep CONFIG_STACKPROTECTOR_STRONG /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This provides a mechanism that protects more vulnerable functions than CONFIG_STACKPROTECTOR, balancing between security and performance.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_stackprotector_strong

References:

anssi | R15

#### Rule Make the kernel text and rodata read-only [ref]

When set, kernel text and rodata memory will be made read-only, and non-text memory will be made non-executable. This configuration is available from kernel 4.11. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_STRICT_KERNEL_RWX`, run the following command: `grep CONFIG_STRICT_KERNEL_RWX /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This provides protection against certain security exploits (e.g. executing the heap or modifying text)
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_strict_kernel_rwx

References:

anssi | R15

#### Rule Make the module text and rodata read-only [ref]

When set, module text and rodata memory will be made read-only, and non-text memory will be made non-executable. This configuration is available from kernel 4.11. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_STRICT_MODULE_RWX`, run the following command: `grep CONFIG_STRICT_MODULE_RWX /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This provides protection against certain security exploits (e.g. executing the heap or modifying text)
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_strict_module_rwx

References:

anssi | R18

#### Rule Enable TCP/IP syncookie support [ref]

Normal TCP/IP networking is open to an attack known as SYN flooding. It is denial-of-service attack that prevents legitimate remote users from being able to connect to your computer during an ongoing attack. When enabled the TCP/IP stack will use a cryptographic challenge protocol known as SYN cookies to enable legitimate users to continue to connect, even when your machine is under attack. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_SYN_COOKIES`, run the following command: `grep CONFIG_SYN_COOKIES /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | SYN cookies provide protection against SYN flooding attacks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_syn_cookies

References:

anssi | R22

#### Rule Unmap kernel when running in userspace (aka KAISER) [ref]

Speculation attacks against some high-performance processors can be used to bypass MMU permission checks and leak kernel data to userspace. This can be defended against by unmapping the kernel when running in userspace, mapping it back in on exception entry via a trampoline page in the vector table. This configuration is available from kernel 4.16, but may be available if backported by distros. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_UNMAP_KERNEL_AT_EL0`, run the following command: `grep CONFIG_UNMAP_KERNEL_AT_EL0 /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This is a countermeasure to the Meltdown attack.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_unmap_kernel_at_el0

References:

anssi | R27

#### Rule User a virtually-mapped stack [ref]

Enable this to use virtually-mapped kernel stacks with guard pages. This configuration is available from kernel 4.9. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_VMAP_STACK`, run the following command: `grep CONFIG_VMAP_STACK /boot/config-*` For each kernel installed, a line with value "y" should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | This causes kernel stack overflows to be caught immediately rather than causing difficult-to-diagnose corruption.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_vmap_stack

References:

anssi | R15

#### Rule Disable x86 vsyscall emulation [ref]

Disabling it is roughly equivalent to booting with vsyscall=none, except that it will also disable the helpful warning if a program tries to use a vsyscall. With this option set to N, offending programs will just segfault, citing addresses of the form 0xffffffffff600?00. This configuration is available from kernel 3.19. The configuration that was used to build kernel is available at `/boot/config-*`. To check the configuration value for `CONFIG_X86_VSYSCALL_EMULATION`, run the following command: `grep CONFIG_X86_VSYSCALL_EMULATION /boot/config-*` Configs with value 'n' are not explicitly set in the file, so either commented lines or no lines should be returned.
Warning: There is no remediation for this besides re-compiling the kernel with the appropriate value for the config.

Rationale: | The vsyscall table is no longer required and is a potential source of ROP gadgets.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_kernel_config_x86_vsyscall_emulation

References:

anssi | R15

Group Configure Syslog Group contains 3 groups and 12 rules

[ref] The syslog service has been the default Unix logging mechanism for many years. It has a number of downsides, including inconsistent log format, lack of authentication for received messages, and lack of authentication, encryption, or reliable transport for messages sent over a network. However, due to its long history, syslog is a de facto standard which is supported by almost all Unix applications.
In Debian 13, rsyslog has replaced ksyslogd as the syslog daemon of choice, and it includes some additional security features such as reliable, connection-oriented (i.e. TCP) transmission of logs, the option to log to database formats, and the encryption of log data en route to a central logging server. This section discusses how to configure rsyslog for best effect, and how to use tools provided with the system to maintain and monitor logs.

Group Ensure Proper Configuration of Log Files Group contains 3 rules

[ref] The file `/etc/rsyslog.conf` controls where log message are written. These are controlled by lines called rules, which consist of a selector and an action. These rules are often customized depending on the role of the system, the requirements of the environment, and whatever may enable the administrator to most effectively make use of log data. The default rules in Debian 13 are:

    *.info;mail.none;authpriv.none;cron.none                /var/log/messages
    authpriv.*                                              /var/log/secure
    mail.*                                                  -/var/log/maillog
    cron.*                                                  /var/log/cron
    *.emerg                                                 *
    uucp,news.crit                                          /var/log/spooler
    local7.*                                                /var/log/boot.log

See the man page `rsyslog.conf(5)` for more information. Note that the `rsyslog` daemon can be configured to use a timestamp format that some log processing programs may not understand. If this occurs, edit the file `/etc/rsyslog.conf` and add or edit the following line:

    $ ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

#### Rule Ensure Log Files Are Owned By Appropriate Group [ref]

The group-owner of all log files written by `rsyslog` should be `adm`. These log files are determined by the second part of each Rule line in `/etc/rsyslog.conf` and typically all appear in `/var/log`. For each log file LOGFILE referenced in `/etc/rsyslog.conf`, run the following command to inspect the file's group owner:

    $ ls -l LOGFILE

If the owner is not `adm`, run the following command to correct this:

    $ sudo chgrp adm LOGFILE

Rationale: | The log files generated by rsyslog contain valuable information regarding system configuration, user authentication, and other such information. Log files should be protected from unauthorized access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_files_groupownership

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-10.5.1, Req-10.5.2
anssi | R71
ism | 0988, 1405
pcidss4 | 10.3.2, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'rsyslog' 2>/dev/null | grep -q '^installed$'; then

    # List of log file paths to be inspected for correct permissions
    # * Primarily inspect log file paths listed in /etc/rsyslog.conf
    RSYSLOG_ETC_CONFIG="/etc/rsyslog.conf"
    # * And also the log file paths listed after rsyslog's $IncludeConfig directive
    #   (store the result into array for the case there's shell glob used as value of IncludeConfig)
    readarray -t OLD_INC < <(grep -e "\$IncludeConfig[[:space:]]\+[^[:space:];]\+" /etc/rsyslog.conf | cut -d ' ' -f 2)
    readarray -t RSYSLOG_INCLUDE_CONFIG < <(for INCPATH in "${OLD_INC[@]}"; do eval printf '%s\\n' "${INCPATH}"; done)
    readarray -t NEW_INC < <(sed -n '/^\s*include(/,/)/Ip' /etc/rsyslog.conf | sed -n 's@.*file\s*=\s*"\([/[:alnum:][:punct:]]*\)".*@\1@Ip')
    readarray -t RSYSLOG_INCLUDE < <(for INCPATH in "${NEW_INC[@]}"; do eval printf '%s\\n' "${INCPATH}"; done)

    # Declare an array to hold the final list of different log file paths
    declare -a LOG_FILE_PATHS

    # Array to hold all rsyslog config entries
    RSYSLOG_CONFIGS=()
    RSYSLOG_CONFIGS=("${RSYSLOG_ETC_CONFIG}" "${RSYSLOG_INCLUDE_CONFIG[@]}" "${RSYSLOG_INCLUDE[@]}")

    # Get full list of files to be checked
    # RSYSLOG_CONFIGS may contain globs such as
    # /etc/rsyslog.d/*.conf /etc/rsyslog.d/*.frule
    # So, loop over the entries in RSYSLOG_CONFIGS and use find to get the list of included files.
    RSYSLOG_CONFIG_FILES=()
    for ENTRY in "${RSYSLOG_CONFIGS[@]}"
    do
    	# If directory, rsyslog will search for config files in recursively.
    	# However, files in hidden sub-directories or hidden files will be ignored.
    	if [ -d "${ENTRY}" ]
    	then
    		readarray -t FINDOUT < <(find "${ENTRY}" -not -path '*/.*' -type f)
    		RSYSLOG_CONFIG_FILES+=("${FINDOUT[@]}")
    	elif [ -f "${ENTRY}" ]
    	then
    		RSYSLOG_CONFIG_FILES+=("${ENTRY}")
    	else
    		echo "Invalid include object: ${ENTRY}"
    	fi
    done

    # Browse each file selected above as containing paths of log files
    # ('/etc/rsyslog.conf' and '/etc/rsyslog.d/*.conf' in the default configuration)
    for LOG_FILE in "${RSYSLOG_CONFIG_FILES[@]}"
    do
    	# From each of these files extract just particular log file path(s), thus:
    	# * Ignore lines starting with space (' '), comment ('#"), or variable syntax ('$') characters,
    	# * Ignore empty lines,
    	# * Strip quotes and closing brackets from paths.
    	# * Ignore paths that match /dev|/etc.*\.conf, as those are paths, but likely not log files
    	# * From the remaining valid rows select only fields constituting a log file path
    	# Text file column is understood to represent a log file path if and only if all of the
    	# following are met:
    	# * it contains at least one slash '/' character,
    	# * it is preceded by space
    	# * it doesn't contain space (' '), colon (':'), and semicolon (';') characters
    	# Search log file for path(s) only in case it exists!
    	if [[ -f "${LOG_FILE}" ]]
    	then
    		NORMALIZED_CONFIG_FILE_LINES=$(sed -e "/^[#|$]/d" "${LOG_FILE}")
    		LINES_WITH_PATHS=$(grep '[^/]*\s\+\S*/\S\+$' <<< "${NORMALIZED_CONFIG_FILE_LINES}")
    		FILTERED_PATHS=$(awk '{if(NF>=2&&($NF~/^\//||$NF~/^-\//)){sub(/^-\//,"/",$NF);print $NF}}' <<< "${LINES_WITH_PATHS}")
    		CLEANED_PATHS=$(sed -e "s/[\"')]//g; /\\/etc.*\.conf/d; /\\/dev\\//d" <<< "${FILTERED_PATHS}")
    		MATCHED_ITEMS=$(sed -e "/^$/d" <<< "${CLEANED_PATHS}")
    		# Since above sed command might return more than one item (delimited by newline), split
    		# the particular matches entries into new array specific for this log file
    		readarray -t ARRAY_FOR_LOG_FILE <<< "$MATCHED_ITEMS"
    		# Concatenate the two arrays - previous content of $LOG_FILE_PATHS array with
    		# items from newly created array for this log file
    		LOG_FILE_PATHS+=("${ARRAY_FOR_LOG_FILE[@]}")
    		# Delete the temporary array
    		unset ARRAY_FOR_LOG_FILE
    	fi
    done

    # Check for RainerScript action log format which might be also multiline so grep regex is a bit
    # curly:
    # extract possibly multiline action omfile expressions
    # extract File="logfile" expression
    # match only "logfile" expression
    for LOG_FILE in "${RSYSLOG_CONFIG_FILES[@]}"
    do
    	ACTION_OMFILE_LINES=$(grep -iozP "action\s*\(\s*type\s*=\s*\"omfile\"[^\)]*\)" "${LOG_FILE}")
    	OMFILE_LINES=$(echo "${ACTION_OMFILE_LINES}"| grep -iaoP "\bFile\s*=\s*\"([/[:alnum:][:punct:]]*)\"\s*\)")
    	LOG_FILE_PATHS+=("$(echo "${OMFILE_LINES}"| grep -oE "\"([/[:alnum:][:punct:]]*)\""|tr -d "\"")")
    done

    # Ensure the correct attribute if file exists
    FILE_CMD="chgrp"
    for LOG_FILE_PATH in "${LOG_FILE_PATHS[@]}"
    do
    	# Sanity check - if particular $LOG_FILE_PATH is empty string, skip it from further processing
    	if [ -z "$LOG_FILE_PATH" ]
    	then
    		continue
    	fi
    	$FILE_CMD "adm" "$LOG_FILE_PATH"
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Set rsyslog logfile configuration
        facts
      ansible.builtin.set_fact:
        rsyslog_etc_config: /etc/rsyslog.conf
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Get IncludeConfig directive
      ansible.builtin.shell: |
        grep -e '$IncludeConfig' {{ rsyslog_etc_config }} | cut -d ' ' -f 2 || true
      register: rsyslog_old_inc
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Get include files directives
      ansible.builtin.shell: |
        awk '/)/{f=0} /include\(/{f=1} f{ nf=gensub("^(include\\(|\\s*)file=\"(\\S+)\".*","\\2",1); if($0!=nf){ print nf }}' {{ rsyslog_etc_config }} || true
      register: rsyslog_new_inc
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Aggregate rsyslog includes
      ansible.builtin.set_fact:
        include_config_output: '{{ rsyslog_old_inc.stdout_lines + rsyslog_new_inc.stdout_lines
          }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_old_inc is not skipped and rsyslog_new_inc is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - List all config files
      ansible.builtin.find:
        paths: '{{ item | dirname }}'
        patterns: '{{ item | basename }}'
        hidden: false
        follow: true
      loop: '{{ include_config_output | list + [rsyslog_etc_config] }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - include_config_output is defined
      register: rsyslog_config_files
      failed_when: false
      changed_when: false
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Extract log files old format
      ansible.builtin.shell: |
        grep -oP '^[^(\s|#|\$)]+[\s]+.*[\s]+-?(/+[^:;\s]+);*\.*$' {{ item.1.path }} | \
        awk '{print $NF}' | \
        sed -e 's/^-//' || true
      loop: '{{ rsyslog_config_files.results | default([]) | subelements(''files'') }}'
      register: log_files_old
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_config_files is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Extract log files new format
      ansible.builtin.shell: |
        grep -ozP "action\s*\(\s*type\s*=\s*\"omfile\"[^\)]*\)" {{ item.1.path }} | \
        grep -aoP "\bFile\s*=\s*\"([/[:alnum:][:punct:]]*)\"\s*\)" | \
        grep -oE "\"([/[:alnum:][:punct:]]*)\"" | \
        tr -d "\""|| true
      loop: '{{ rsyslog_config_files.results | default([]) | subelements(''files'') }}'
      register: log_files_new
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_config_files is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group - Sum all log files found
      ansible.builtin.set_fact:
        log_files: '{{ log_files_new.results | map(attribute=''stdout_lines'') | list
          | flatten | unique + log_files_old.results | map(attribute=''stdout_lines'')
          | list | flatten | unique }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

    - name: Ensure Log Files Are Owned By Appropriate Group -Setup log files attribute
      ansible.builtin.file:
        path: '{{ item }}'
        group: adm
        state: file
      loop: '{{ log_files | list | flatten | unique }}'
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_groupownership

#### Rule Ensure Log Files Are Owned By Appropriate User [ref]

The owner of all log files written by `rsyslog` should be `adm`. These log files are determined by the second part of each Rule line in `/etc/rsyslog.conf` and typically all appear in `/var/log`. For each log file LOGFILE referenced in `/etc/rsyslog.conf`, run the following command to inspect the file's owner:

    $ ls -l LOGFILE

If the owner is not `adm`, run the following command to correct this:

    $ sudo chown adm LOGFILE

Rationale: | The log files generated by rsyslog contain valuable information regarding system configuration, user authentication, and other such information. Log files should be protected from unauthorized access.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_files_ownership

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-10.5.1, Req-10.5.2
anssi | R71
ism | 0988, 1405
pcidss4 | 10.3.2, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'rsyslog' 2>/dev/null | grep -q '^installed$'; then

    # List of log file paths to be inspected for correct permissions
    # * Primarily inspect log file paths listed in /etc/rsyslog.conf
    RSYSLOG_ETC_CONFIG="/etc/rsyslog.conf"
    # * And also the log file paths listed after rsyslog's $IncludeConfig directive
    #   (store the result into array for the case there's shell glob used as value of IncludeConfig)
    readarray -t OLD_INC < <(grep -e "\$IncludeConfig[[:space:]]\+[^[:space:];]\+" /etc/rsyslog.conf | cut -d ' ' -f 2)
    readarray -t RSYSLOG_INCLUDE_CONFIG < <(for INCPATH in "${OLD_INC[@]}"; do eval printf '%s\\n' "${INCPATH}"; done)
    readarray -t NEW_INC < <(sed -n '/^\s*include(/,/)/Ip' /etc/rsyslog.conf | sed -n 's@.*file\s*=\s*"\([/[:alnum:][:punct:]]*\)".*@\1@Ip')
    readarray -t RSYSLOG_INCLUDE < <(for INCPATH in "${NEW_INC[@]}"; do eval printf '%s\\n' "${INCPATH}"; done)

    # Declare an array to hold the final list of different log file paths
    declare -a LOG_FILE_PATHS

    # Array to hold all rsyslog config entries
    RSYSLOG_CONFIGS=()
    RSYSLOG_CONFIGS=("${RSYSLOG_ETC_CONFIG}" "${RSYSLOG_INCLUDE_CONFIG[@]}" "${RSYSLOG_INCLUDE[@]}")

    # Get full list of files to be checked
    # RSYSLOG_CONFIGS may contain globs such as
    # /etc/rsyslog.d/*.conf /etc/rsyslog.d/*.frule
    # So, loop over the entries in RSYSLOG_CONFIGS and use find to get the list of included files.
    RSYSLOG_CONFIG_FILES=()
    for ENTRY in "${RSYSLOG_CONFIGS[@]}"
    do
    	# If directory, rsyslog will search for config files in recursively.
    	# However, files in hidden sub-directories or hidden files will be ignored.
    	if [ -d "${ENTRY}" ]
    	then
    		readarray -t FINDOUT < <(find "${ENTRY}" -not -path '*/.*' -type f)
    		RSYSLOG_CONFIG_FILES+=("${FINDOUT[@]}")
    	elif [ -f "${ENTRY}" ]
    	then
    		RSYSLOG_CONFIG_FILES+=("${ENTRY}")
    	else
    		echo "Invalid include object: ${ENTRY}"
    	fi
    done

    # Browse each file selected above as containing paths of log files
    # ('/etc/rsyslog.conf' and '/etc/rsyslog.d/*.conf' in the default configuration)
    for LOG_FILE in "${RSYSLOG_CONFIG_FILES[@]}"
    do
    	# From each of these files extract just particular log file path(s), thus:
    	# * Ignore lines starting with space (' '), comment ('#"), or variable syntax ('$') characters,
    	# * Ignore empty lines,
    	# * Strip quotes and closing brackets from paths.
    	# * Ignore paths that match /dev|/etc.*\.conf, as those are paths, but likely not log files
    	# * From the remaining valid rows select only fields constituting a log file path
    	# Text file column is understood to represent a log file path if and only if all of the
    	# following are met:
    	# * it contains at least one slash '/' character,
    	# * it is preceded by space
    	# * it doesn't contain space (' '), colon (':'), and semicolon (';') characters
    	# Search log file for path(s) only in case it exists!
    	if [[ -f "${LOG_FILE}" ]]
    	then
    		NORMALIZED_CONFIG_FILE_LINES=$(sed -e "/^[#|$]/d" "${LOG_FILE}")
    		LINES_WITH_PATHS=$(grep '[^/]*\s\+\S*/\S\+$' <<< "${NORMALIZED_CONFIG_FILE_LINES}")
    		FILTERED_PATHS=$(awk '{if(NF>=2&&($NF~/^\//||$NF~/^-\//)){sub(/^-\//,"/",$NF);print $NF}}' <<< "${LINES_WITH_PATHS}")
    		CLEANED_PATHS=$(sed -e "s/[\"')]//g; /\\/etc.*\.conf/d; /\\/dev\\//d" <<< "${FILTERED_PATHS}")
    		MATCHED_ITEMS=$(sed -e "/^$/d" <<< "${CLEANED_PATHS}")
    		# Since above sed command might return more than one item (delimited by newline), split
    		# the particular matches entries into new array specific for this log file
    		readarray -t ARRAY_FOR_LOG_FILE <<< "$MATCHED_ITEMS"
    		# Concatenate the two arrays - previous content of $LOG_FILE_PATHS array with
    		# items from newly created array for this log file
    		LOG_FILE_PATHS+=("${ARRAY_FOR_LOG_FILE[@]}")
    		# Delete the temporary array
    		unset ARRAY_FOR_LOG_FILE
    	fi
    done

    # Check for RainerScript action log format which might be also multiline so grep regex is a bit
    # curly:
    # extract possibly multiline action omfile expressions
    # extract File="logfile" expression
    # match only "logfile" expression
    for LOG_FILE in "${RSYSLOG_CONFIG_FILES[@]}"
    do
    	ACTION_OMFILE_LINES=$(grep -iozP "action\s*\(\s*type\s*=\s*\"omfile\"[^\)]*\)" "${LOG_FILE}")
    	OMFILE_LINES=$(echo "${ACTION_OMFILE_LINES}"| grep -iaoP "\bFile\s*=\s*\"([/[:alnum:][:punct:]]*)\"\s*\)")
    	LOG_FILE_PATHS+=("$(echo "${OMFILE_LINES}"| grep -oE "\"([/[:alnum:][:punct:]]*)\""|tr -d "\"")")
    done

    # Ensure the correct attribute if file exists
    FILE_CMD="chown"
    for LOG_FILE_PATH in "${LOG_FILE_PATHS[@]}"
    do
    	# Sanity check - if particular $LOG_FILE_PATH is empty string, skip it from further processing
    	if [ -z "$LOG_FILE_PATH" ]
    	then
    		continue
    	fi
    	$FILE_CMD "root" "$LOG_FILE_PATH"
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Set rsyslog logfile configuration
        facts
      ansible.builtin.set_fact:
        rsyslog_etc_config: /etc/rsyslog.conf
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Get IncludeConfig directive
      ansible.builtin.shell: |
        grep -e '$IncludeConfig' {{ rsyslog_etc_config }} | cut -d ' ' -f 2 || true
      register: rsyslog_old_inc
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Get include files directives
      ansible.builtin.shell: |
        awk '/)/{f=0} /include\(/{f=1} f{ nf=gensub("^(include\\(|\\s*)file=\"(\\S+)\".*","\\2",1); if($0!=nf){ print nf }}' {{ rsyslog_etc_config }} || true
      register: rsyslog_new_inc
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Aggregate rsyslog includes
      ansible.builtin.set_fact:
        include_config_output: '{{ rsyslog_old_inc.stdout_lines + rsyslog_new_inc.stdout_lines
          }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_old_inc is not skipped and rsyslog_new_inc is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - List all config files
      ansible.builtin.find:
        paths: '{{ item | dirname }}'
        patterns: '{{ item | basename }}'
        hidden: false
        follow: true
      loop: '{{ include_config_output | list + [rsyslog_etc_config] }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - include_config_output is defined
      register: rsyslog_config_files
      failed_when: false
      changed_when: false
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Extract log files old format
      ansible.builtin.shell: |
        grep -oP '^[^(\s|#|\$)]+[\s]+.*[\s]+-?(/+[^:;\s]+);*\.*$' {{ item.1.path }} | \
        awk '{print $NF}' | \
        sed -e 's/^-//' || true
      loop: '{{ rsyslog_config_files.results | default([]) | subelements(''files'') }}'
      register: log_files_old
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_config_files is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Extract log files new format
      ansible.builtin.shell: |
        grep -ozP "action\s*\(\s*type\s*=\s*\"omfile\"[^\)]*\)" {{ item.1.path }} | \
        grep -aoP "\bFile\s*=\s*\"([/[:alnum:][:punct:]]*)\"\s*\)" | \
        grep -oE "\"([/[:alnum:][:punct:]]*)\"" | \
        tr -d "\""|| true
      loop: '{{ rsyslog_config_files.results | default([]) | subelements(''files'') }}'
      register: log_files_new
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_config_files is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User - Sum all log files found
      ansible.builtin.set_fact:
        log_files: '{{ log_files_new.results | map(attribute=''stdout_lines'') | list
          | flatten | unique + log_files_old.results | map(attribute=''stdout_lines'')
          | list | flatten | unique }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

    - name: Ensure Log Files Are Owned By Appropriate User -Setup log files attribute
      ansible.builtin.file:
        path: '{{ item }}'
        owner: root
        state: file
      loop: '{{ log_files | list | flatten | unique }}'
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_ownership

#### Rule Ensure System Log Files Have Correct Permissions [ref]

The file permissions for all log files written by `rsyslog` should be set to 640, or more restrictive. These log files are determined by the second part of each Rule line in `/etc/rsyslog.conf` and typically all appear in `/var/log`. For each log file LOGFILE referenced in `/etc/rsyslog.conf`, run the following command to inspect the file's permissions:

    $ ls -l LOGFILE

If the permissions are not 640 or more restrictive, run the following command to correct this:

    $ sudo chmod 640 LOGFILE

"

Rationale: | Log files can contain valuable information regarding system configuration. If the system log files are not protected unauthorized users could change the logged data, eliminating their forensic value.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_files_permissions

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
pcidss | Req-10.5.1, Req-10.5.2
anssi | R71
ism | 0988, 1405
pcidss4 | 10.3.1, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'rsyslog' 2>/dev/null | grep -q '^installed$'; then

    # List of log file paths to be inspected for correct permissions
    # * Primarily inspect log file paths listed in /etc/rsyslog.conf
    RSYSLOG_ETC_CONFIG="/etc/rsyslog.conf"
    # * And also the log file paths listed after rsyslog's $IncludeConfig directive
    #   (store the result into array for the case there's shell glob used as value of IncludeConfig)
    readarray -t OLD_INC < <(grep -e "\$IncludeConfig[[:space:]]\+[^[:space:];]\+" /etc/rsyslog.conf | cut -d ' ' -f 2)
    readarray -t RSYSLOG_INCLUDE_CONFIG < <(for INCPATH in "${OLD_INC[@]}"; do eval printf '%s\\n' "${INCPATH}"; done)
    readarray -t NEW_INC < <(sed -n '/^\s*include(/,/)/Ip' /etc/rsyslog.conf | sed -n 's@.*file\s*=\s*"\([/[:alnum:][:punct:]]*\)".*@\1@Ip')
    readarray -t RSYSLOG_INCLUDE < <(for INCPATH in "${NEW_INC[@]}"; do eval printf '%s\\n' "${INCPATH}"; done)

    # Declare an array to hold the final list of different log file paths
    declare -a LOG_FILE_PATHS

    # Array to hold all rsyslog config entries
    RSYSLOG_CONFIGS=()
    RSYSLOG_CONFIGS=("${RSYSLOG_ETC_CONFIG}" "${RSYSLOG_INCLUDE_CONFIG[@]}" "${RSYSLOG_INCLUDE[@]}")

    # Get full list of files to be checked
    # RSYSLOG_CONFIGS may contain globs such as
    # /etc/rsyslog.d/*.conf /etc/rsyslog.d/*.frule
    # So, loop over the entries in RSYSLOG_CONFIGS and use find to get the list of included files.
    RSYSLOG_CONFIG_FILES=()
    for ENTRY in "${RSYSLOG_CONFIGS[@]}"
    do
    	# If directory, rsyslog will search for config files in recursively.
    	# However, files in hidden sub-directories or hidden files will be ignored.
    	if [ -d "${ENTRY}" ]
    	then
    		readarray -t FINDOUT < <(find "${ENTRY}" -not -path '*/.*' -type f)
    		RSYSLOG_CONFIG_FILES+=("${FINDOUT[@]}")
    	elif [ -f "${ENTRY}" ]
    	then
    		RSYSLOG_CONFIG_FILES+=("${ENTRY}")
    	else
    		echo "Invalid include object: ${ENTRY}"
    	fi
    done

    # Browse each file selected above as containing paths of log files
    # ('/etc/rsyslog.conf' and '/etc/rsyslog.d/*.conf' in the default configuration)
    for LOG_FILE in "${RSYSLOG_CONFIG_FILES[@]}"
    do
    	# From each of these files extract just particular log file path(s), thus:
    	# * Ignore lines starting with space (' '), comment ('#"), or variable syntax ('$') characters,
    	# * Ignore empty lines,
    	# * Strip quotes and closing brackets from paths.
    	# * Ignore paths that match /dev|/etc.*\.conf, as those are paths, but likely not log files
    	# * From the remaining valid rows select only fields constituting a log file path
    	# Text file column is understood to represent a log file path if and only if all of the
    	# following are met:
    	# * it contains at least one slash '/' character,
    	# * it is preceded by space
    	# * it doesn't contain space (' '), colon (':'), and semicolon (';') characters
    	# Search log file for path(s) only in case it exists!
    	if [[ -f "${LOG_FILE}" ]]
    	then
    		NORMALIZED_CONFIG_FILE_LINES=$(sed -e "/^[#|$]/d" "${LOG_FILE}")
    		LINES_WITH_PATHS=$(grep '[^/]*\s\+\S*/\S\+$' <<< "${NORMALIZED_CONFIG_FILE_LINES}")
    		FILTERED_PATHS=$(awk '{if(NF>=2&&($NF~/^\//||$NF~/^-\//)){sub(/^-\//,"/",$NF);print $NF}}' <<< "${LINES_WITH_PATHS}")
    		CLEANED_PATHS=$(sed -e "s/[\"')]//g; /\\/etc.*\.conf/d; /\\/dev\\//d" <<< "${FILTERED_PATHS}")
    		MATCHED_ITEMS=$(sed -e "/^$/d" <<< "${CLEANED_PATHS}")
    		# Since above sed command might return more than one item (delimited by newline), split
    		# the particular matches entries into new array specific for this log file
    		readarray -t ARRAY_FOR_LOG_FILE <<< "$MATCHED_ITEMS"
    		# Concatenate the two arrays - previous content of $LOG_FILE_PATHS array with
    		# items from newly created array for this log file
    		LOG_FILE_PATHS+=("${ARRAY_FOR_LOG_FILE[@]}")
    		# Delete the temporary array
    		unset ARRAY_FOR_LOG_FILE
    	fi
    done

    # Check for RainerScript action log format which might be also multiline so grep regex is a bit
    # curly:
    # extract possibly multiline action omfile expressions
    # extract File="logfile" expression
    # match only "logfile" expression
    for LOG_FILE in "${RSYSLOG_CONFIG_FILES[@]}"
    do
    	ACTION_OMFILE_LINES=$(grep -iozP "action\s*\(\s*type\s*=\s*\"omfile\"[^\)]*\)" "${LOG_FILE}")
    	OMFILE_LINES=$(echo "${ACTION_OMFILE_LINES}"| grep -iaoP "\bFile\s*=\s*\"([/[:alnum:][:punct:]]*)\"\s*\)")
    	LOG_FILE_PATHS+=("$(echo "${OMFILE_LINES}"| grep -oE "\"([/[:alnum:][:punct:]]*)\""|tr -d "\"")")
    done

    # Ensure the correct attribute if file exists
    FILE_CMD="chmod"
    for LOG_FILE_PATH in "${LOG_FILE_PATHS[@]}"
    do
    	# Sanity check - if particular $LOG_FILE_PATH is empty string, skip it from further processing
    	if [ -z "$LOG_FILE_PATH" ]
    	then
    		continue
    	fi
    	$FILE_CMD "0640" "$LOG_FILE_PATH"
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Set rsyslog logfile configuration
        facts
      ansible.builtin.set_fact:
        rsyslog_etc_config: /etc/rsyslog.conf
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Get IncludeConfig directive
      ansible.builtin.shell: |
        grep -e '$IncludeConfig' {{ rsyslog_etc_config }} | cut -d ' ' -f 2 || true
      register: rsyslog_old_inc
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Get include files directives
      ansible.builtin.shell: |
        awk '/)/{f=0} /include\(/{f=1} f{ nf=gensub("^(include\\(|\\s*)file=\"(\\S+)\".*","\\2",1); if($0!=nf){ print nf }}' {{ rsyslog_etc_config }} || true
      register: rsyslog_new_inc
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Aggregate rsyslog includes
      ansible.builtin.set_fact:
        include_config_output: '{{ rsyslog_old_inc.stdout_lines + rsyslog_new_inc.stdout_lines
          }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_old_inc is not skipped and rsyslog_new_inc is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - List all config files
      ansible.builtin.find:
        paths: '{{ item | dirname }}'
        patterns: '{{ item | basename }}'
        hidden: false
        follow: true
      loop: '{{ include_config_output | list + [rsyslog_etc_config] }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - include_config_output is defined
      register: rsyslog_config_files
      failed_when: false
      changed_when: false
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Extract log files old format
      ansible.builtin.shell: |
        grep -oP '^[^(\s|#|\$)]+[\s]+.*[\s]+-?(/+[^:;\s]+);*\.*$' {{ item.1.path }} | \
        awk '{print $NF}' | \
        sed -e 's/^-//' || true
      loop: '{{ rsyslog_config_files.results | default([]) | subelements(''files'') }}'
      register: log_files_old
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_config_files is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Extract log files new format
      ansible.builtin.shell: |
        grep -ozP "action\s*\(\s*type\s*=\s*\"omfile\"[^\)]*\)" {{ item.1.path }} | \
        grep -aoP "\bFile\s*=\s*\"([/[:alnum:][:punct:]]*)\"\s*\)" | \
        grep -oE "\"([/[:alnum:][:punct:]]*)\"" | \
        tr -d "\""|| true
      loop: '{{ rsyslog_config_files.results | default([]) | subelements(''files'') }}'
      register: log_files_new
      changed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      - rsyslog_config_files is not skipped
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions - Sum all log files found
      ansible.builtin.set_fact:
        log_files: '{{ log_files_new.results | map(attribute=''stdout_lines'') | list
          | flatten | unique + log_files_old.results | map(attribute=''stdout_lines'')
          | list | flatten | unique }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

    - name: Ensure System Log Files Have Correct Permissions -Setup log files attribute
      ansible.builtin.file:
        path: '{{ item }}'
        mode: '0640'
        state: file
      loop: '{{ log_files | list | flatten | unique }}'
      failed_when: false
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.1
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.1
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - rsyslog_files_permissions

Group Ensure All Logs are Rotated by logrotate Group contains 3 rules

[ref] Edit the file `/etc/logrotate.d/syslog`. Find the first line, which should look like this (wrapped for clarity):

    /var/log/messages /var/log/secure /var/log/maillog /var/log/spooler \
      /var/log/boot.log /var/log/cron {

Edit this line so that it contains a one-space-separated listing of each log file referenced in `/etc/rsyslog.conf`.
All logs in use on a system must be rotated regularly, or the log files will consume disk space over time, eventually interfering with system operation. The file `/etc/logrotate.d/syslog` is the configuration file used by the `logrotate` program to maintain all log files written by `syslog`. By default, it rotates logs weekly and stores four archival copies of each log. These settings can be modified by editing `/etc/logrotate.conf`, but the defaults are sufficient for purposes of this guide.
Note that `logrotate` is run nightly by the cron job `/etc/cron.daily/logrotate`. If particularly active logs need to be rotated more often than once a day, some other mechanism must be used.

#### Rule Ensure logrotate is Installed [ref]

logrotate is installed by default. The `logrotate` package can be installed with the following command:

     $ apt-get install logrotate

Rationale: | The logrotate package provides the logrotate services.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_logrotate_installed

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1
nist | CM-6(a)
nist-csf | PR.PT-1
pcidss | Req-10.7
anssi | R71
pcidss4 | 10.5.1, 10.5

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "logrotate"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_logrotate

    class install_logrotate {
      package { 'logrotate':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_logrotate_installed

    - name: Ensure logrotate is installed
      ansible.builtin.package:
        name: logrotate
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_logrotate_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "logrotate"
    version = "*"

#### Rule Ensure Logrotate Runs Periodically [ref]

The `logrotate` utility allows for the automatic rotation of log files. The frequency of rotation is specified in `/etc/logrotate.conf`, which triggers a cron task or a timer. To configure logrotate to run daily, add or correct the following line in `/etc/logrotate.conf`:

    # rotate log files frequency
    daily

Rationale: | Log files that are not properly rotated run the risk of growing so large that they fill up the /var/log partition. Valuable logging information could be lost if the /var/log partition becomes full.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_ensure_logrotate_activated

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1
nist | CM-6(a)
nist-csf | PR.PT-1
pcidss | Req-10.7
anssi | R71

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'logrotate' 2>/dev/null | grep -q '^installed$'; }; then

    LOGROTATE_CONF_FILE="/etc/logrotate.conf"

    DEBIAN_FRONTEND=noninteractive apt-get install -y "crontabs"
    CRON_DAILY_LOGROTATE_FILE="/etc/cron.daily/logrotate"

    # daily rotation is configured
    grep -q "^daily$" $LOGROTATE_CONF_FILE|| sed -i '1i daily' "$LOGROTATE_CONF_FILE"

    # remove any line configuring weekly, monthly or yearly rotation
    sed -i '/^\s*\(weekly\|monthly\|yearly\).*$/d' $LOGROTATE_CONF_FILE

    # configure cron.daily if not already
    if ! grep -q "^[[:space:]]*/usr/sbin/logrotate[[:alnum:][:blank:][:punct:]]*$LOGROTATE_CONF_FILE$" $CRON_DAILY_LOGROTATE_FILE; then
    	echo '#!/bin/sh' > $CRON_DAILY_LOGROTATE_FILE
    	echo "/usr/sbin/logrotate $LOGROTATE_CONF_FILE" >> $CRON_DAILY_LOGROTATE_FILE
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - configure_strategy
      - ensure_logrotate_activated
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure daily log rotation in /etc/logrotate.conf
      ansible.builtin.lineinfile:
        create: true
        dest: /etc/logrotate.conf
        regexp: ^\s*(weekly|monthly|yearly)$
        line: daily
        state: present
        insertbefore: BOF
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"logrotate" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - configure_strategy
      - ensure_logrotate_activated
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Make sure daily log rotation setting is not overridden in /etc/logrotate.conf
      ansible.builtin.lineinfile:
        create: false
        dest: /etc/logrotate.conf
        regexp: ^[\s]*(weekly|monthly|yearly)$
        state: absent
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"logrotate" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - configure_strategy
      - ensure_logrotate_activated
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure cron.daily if not already
      block:

      - name: Add shebang
        ansible.builtin.lineinfile:
          path: /etc/cron.daily/logrotate
          line: '#!/bin/sh'
          insertbefore: BOF
          create: true

      - name: Add logrotate call
        ansible.builtin.lineinfile:
          path: /etc/cron.daily/logrotate
          line: /usr/sbin/logrotate /etc/logrotate.conf
          regexp: ^[\s]*/usr/sbin/logrotate[\s\S]*/etc/logrotate.conf$
          create: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"logrotate" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - configure_strategy
      - ensure_logrotate_activated
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Enable logrotate Timer [ref]

The `logrotate` timer can be enabled with the following command:

    $ sudo systemctl enable logrotate.timer

Rationale: | Log files that are not properly rotated run the risk of growing so large that they fill up the /var/log partition. Valuable logging information could be lost if the /var/log partition becomes full.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_timer_logrotate_enabled

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1
nist | CM-6(a)
nist-csf | PR.PT-1
pcidss | Req-10.7
anssi | R71
pcidss4 | 10.5.1, 10.5

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'logrotate' 2>/dev/null | grep -q '^installed$'; }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'logrotate.timer'
    fi
    "$SYSTEMCTL_EXEC" enable 'logrotate.timer'

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - timer_logrotate_enabled

    - name: Enable timer logrotate
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable timer logrotate
        ansible.builtin.systemd:
          name: logrotate.timer
          enabled: 'yes'
          state: started
        when:
        - '"logrotate" in ansible_facts.packages'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"logrotate" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.7
      - PCI-DSSv4-10.5
      - PCI-DSSv4-10.5.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - timer_logrotate_enabled

Group Rsyslog Logs Sent To Remote Host Group contains 3 rules

[ref] If system logs are to be useful in detecting malicious activities, it is necessary to send logs to a remote server. An intruder who has compromised the root account on a system may delete the log entries which indicate that the system was attacked before they are seen by an administrator.
However, it is recommended that logs be stored on the local host in addition to being sent to the loghost, especially if `rsyslog` has been configured to use the UDP protocol to send messages over a network. UDP does not guarantee reliable delivery, and moderately busy sites will lose log messages occasionally, especially in periods of high traffic which may be the result of an attack. In addition, remote `rsyslog` messages are not authenticated in any way by default, so it is easy for an attacker to introduce spurious messages to the central log server. Also, some problems cause loss of network connectivity, which will prevent the sending of messages to the central server. For all of these reasons, it is better to store log messages both centrally and on each host, so that they can be correlated if necessary.

#### Rule Ensure Logs Sent To Remote Host [ref]

To configure rsyslog to send logs to a remote log server, open `/etc/rsyslog.conf` and read and understand the last section of the file, which describes the multiple directives necessary to activate remote logging. Along with these other directives, the system can be configured to forward its logs to a particular log server by adding or correcting one of the following lines, substituting `logcollector` appropriately. The choice of protocol depends on the environment of the system; although TCP and RELP provide more reliable message delivery, they may not be supported in all environments.
To use UDP for log message delivery:

    *.* @logcollector

Or in RainerScript:

    *.* action(type="omfwd" ... target="logcollector" protocol="udp")

To use TCP for log message delivery:

    *.* @@logcollector

Or in RainerScript:

    *.* action(type="omfwd" ... target="logcollector" protocol="tcp")

To use RELP for log message delivery:

    *.* :omrelp:logcollector

Or in RainerScript:

    *.* action(type="omfwd" ... target="logcollector" protocol="relp")

There must be a resolvable DNS CNAME or Alias record set to "logcollector" for logs to be sent correctly to the centralized logging utility.
Warning: It is important to configure queues in case the client is sending log messages to a remote server. If queues are not configured, the system will stop functioning when the connection to the remote server is not available. Please consult Rsyslog documentation for more information about configuration of queues. The example configuration which should go into `/etc/rsyslog.conf` can look like the following lines:

    $ActionQueueType LinkedList
    $ActionQueueFileName queuefilename
    $ActionQueueMaxDiskSpace 1g
    $ActionQueueSaveOnShutdown on
    $ActionResumeRetryCount -1

Or if using Rainer Script syntax, it could be:

    *.* action(type="omfwd" queue.type="linkedlist" queue.filename="example_fwd" action.resumeRetryCount="-1" queue.saveOnShutdown="on" target="example.com" port="30514" protocol="tcp")

Rationale: | A log server (loghost) receives syslog messages from one or more systems. This data can be used as an additional log source in the event a system is compromised and its local logs are suspect. Forwarding log messages to a remote loghost also provides system administrators with a centralized place to view the status of multiple hosts within the enterprise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_remote_loghost

References:

cis-csc | 1, 13, 14, 15, 16, 2, 3, 5, 6
cobit5 | APO11.04, APO13.01, BAI03.05, BAI04.04, DSS05.04, DSS05.07, MEA02.01
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(5)(ii)(B), 164.308(a)(5)(ii)(C), 164.308(a)(6)(ii), 164.308(a)(8), 164.310(d)(2)(iii), 164.312(b), 164.314(a)(2)(i)(C), 164.314(a)(2)(iii)
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 7.1, SR 7.2
iso27001-2013 | A.12.1.3, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.17.2.1
nerc-cip | CIP-003-8 R5.2, CIP-004-6 R3.3
nist | CM-6(a), AU-4(1), AU-9(2)
nist-csf | PR.DS-4, PR.PT-1
os-srg | SRG-OS-000479-GPOS-00224, SRG-OS-000480-GPOS-00227, SRG-OS-000342-GPOS-00133
anssi | R71
ism | 0988, 1405

#### Rule Configure TLS for rsyslog remote logging [ref]

Configure `rsyslog` to use Transport Layer Security (TLS) support for logging to remote server for the Forwarding Output Module in `/etc/rsyslog.conf` using action. You can use the following command:

    echo 'action(type="omfwd" protocol="tcp" Target="<remote system>" port="6514"
        StreamDriver="gtls" StreamDriverMode="1" StreamDriverAuthMode="x509/name" streamdriver.CheckExtendedKeyPurpose="on")' >> /etc/rsyslog.conf

Replace the `<remote system>` in the above command with an IP address or a host name of the remote logging server.

Rationale: | For protection of data being logged, the connection to the remote logging server needs to be authenticated and encrypted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_remote_tls

References:

nist | AU-9(3), CM-6(a)
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000120-GPOS-00061
anssi | R71
ism | 0988, 1405

#### Rule Configure CA certificate for rsyslog remote logging [ref]

Configure CA certificate for `rsyslog` logging to remote server using Transport Layer Security (TLS) using correct path for the `DefaultNetstreamDriverCAFile` global option in `/etc/rsyslog.conf`, for example with the following command:

    echo 'global(DefaultNetstreamDriverCAFile="/etc/pki/tls/cert.pem")' >> /etc/rsyslog.conf

Replace the `/etc/pki/tls/cert.pem` in the above command with the path to the file with CA certificate generated for the purpose of remote logging.
Warning: Automatic remediation is not available as each organization has unique requirements.

Rationale:

The CA certificate needs to be set or `rsyslog.service` fails to start with

    error: ca certificate is not set, cannot continue

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_rsyslog_remote_tls_cacert

References:

os-srg | SRG-OS-000480-GPOS-00227
anssi | R71
ism | 0988, 1405

#### Rule Ensure rsyslog-gnutls is installed [ref]

TLS protocol support for rsyslog is installed. The `rsyslog-gnutls` package can be installed with the following command:

    $ apt-get install rsyslog-gnutls

Rationale: | The rsyslog-gnutls package provides Transport Layer Security (TLS) support for the rsyslog daemon, which enables secure remote logging.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsyslog-gnutls_installed

References:

os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000120-GPOS-00061
anssi | R71

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "rsyslog-gnutls"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_rsyslog-gnutls

    class install_rsyslog-gnutls {
      package { 'rsyslog-gnutls':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsyslog-gnutls_installed

    - name: Ensure rsyslog-gnutls is installed
      ansible.builtin.package:
        name: rsyslog-gnutls
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsyslog-gnutls_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "rsyslog-gnutls"
    version = "*"

#### Rule Ensure rsyslog is Installed [ref]

Rsyslog is installed by default. The `rsyslog` package can be installed with the following command:

     $ apt-get install rsyslog

Rationale: | The rsyslog package provides the rsyslog daemon, which provides system logging services.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsyslog_installed

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1
nist | CM-6(a)
nist-csf | PR.PT-1
os-srg | SRG-OS-000479-GPOS-00224, SRG-OS-000051-GPOS-00024, SRG-OS-000480-GPOS-00227
ism | 1409

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "rsyslog"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_rsyslog

    class install_rsyslog {
      package { 'rsyslog':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsyslog_installed

    - name: Ensure rsyslog is installed
      ansible.builtin.package:
        name: rsyslog
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_rsyslog_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "rsyslog"
    version = "*"

#### Rule Enable rsyslog Service [ref]

The `rsyslog` service provides syslog-style logging by default on Debian 13. The `rsyslog` service can be enabled with the following command:

    $ sudo systemctl enable rsyslog.service

Rationale: | The `rsyslog` service must be running in order to provide logging services, which are essential to system administration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_rsyslog_enabled

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO13.01, BAI03.05, BAI04.04, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
hipaa | 164.312(a)(2)(ii)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2, SR 7.1, SR 7.2
iso27001-2013 | A.12.1.3, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2, A.17.2.1
nist | CM-6(a), AU-4(1)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.DS-4, PR.PT-1
os-srg | SRG-OS-000480-GPOS-00227
ism | 1409

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'rsyslog.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'rsyslog.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'rsyslog.service'

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include enable_rsyslog

    class enable_rsyslog {
      service {'rsyslog':
        enable => true,
        ensure => 'running',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AU-4(1)
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_rsyslog_enabled

    - name: Enable rsyslog Service - Enable service rsyslog
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable rsyslog Service - Enable Service rsyslog
        ansible.builtin.systemd:
          name: rsyslog
          enabled: true
          state: started
          masked: false
        when:
        - '"rsyslog" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-4(1)
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_rsyslog_enabled
      - special_service_block
      when: '"linux-base" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["rsyslog"]

Group Network Configuration and Firewalls Group contains 8 groups and 53 rules

[ref] Most systems must be connected to a network of some sort, and this brings with it the substantial risk of network attack. This section discusses the security impact of decisions about networking which must be made when configuring a system.
This section also discusses firewalls, network access controls, and other network security frameworks, which allow system-level rules to be written that can limit an attackers' ability to connect to your system. These rules can specify that network traffic should be allowed or denied from certain IP addresses, hosts, and networks. The rules can also specify which of the system's network services are available to particular hosts or networks.

Group IPSec Support Group contains 9 rules
[ref] Support for Internet Protocol Security (IPsec) is provided with Libreswan.

#### Rule Verify Group Who Owns /etc/ipsec.d Directory [ref]

To properly set the group owner of `/etc/ipsec.d`, run the command:

    $ sudo chgrp root /etc/ipsec.d

Rationale: | The ownership of the /etc/ipsec.d directory by the root group is important because this directory hosts Libreswan configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_groupowner_etc_ipsecd

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /etc/ipsec.d/ -maxdepth 0 -type d  ! -group root -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_groupowner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"libreswan" in ansible_facts.packages'
      - directory_groupowner_etc_ipsecd_newgroup is undefined
      tags:
      - configure_strategy
      - directory_groupowner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_etc_ipsecd_newgroup variable if root found
      ansible.builtin.set_fact:
        directory_groupowner_etc_ipsecd_newgroup: root
      when:
      - '"libreswan" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - directory_groupowner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ipsec.d/
      ansible.builtin.file:
        path: /etc/ipsec.d/
        follow: false
        state: directory
        group: '{{ directory_groupowner_etc_ipsecd_newgroup }}'
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_groupowner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/ipsec.d Directory [ref]

To properly set the owner of `/etc/ipsec.d`, run the command:

    $ sudo chown root /etc/ipsec.d

Rationale: | The ownership of the /etc/ipsec.d directory by the root user is important because this directory hosts Libreswan configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_owner_etc_ipsecd

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/ipsec.d/ -maxdepth 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_owner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_etc_ipsecd_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_etc_ipsecd_newown: '0'
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/ipsec.d/
      ansible.builtin.file:
        path: /etc/ipsec.d/
        follow: false
        state: directory
        owner: '{{ directory_owner_etc_ipsecd_newown }}'
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/ipsec.d Directory [ref]

To properly set the permissions of `/etc/ipsec.d`, run the command:

    $ sudo chmod 0700 /etc/ipsec.d

Rationale: | Setting correct permissions on the /etc/ipsec.d directory is important because this directory hosts Libreswan configuration. Protection of this directory is critical for system security. Restricting the permissions ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_etc_ipsecd

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    find -H /etc/ipsec.d/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt -type d -exec chmod u-s,g-xwrs,o-xwrt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_permissions_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ipsec.d/ file(s)
      ansible.builtin.command: 'find -P /etc/ipsec.d/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/ipsec.d/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_ipsecd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/ipsec.conf File [ref]

To properly set the group owner of `/etc/ipsec.conf`, run the command:

    $ sudo chgrp root /etc/ipsec.conf

Rationale: | The ownership of the /etc/ipsec.conf file by the root group is important because this file hosts Libreswan configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_ipsec_conf

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/ipsec.conf" | grep -E -w -q "root"; then
        chgrp --no-dereference "$newgroup" /etc/ipsec.conf
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_groupowner_etc_ipsec_conf_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_etc_ipsec_conf_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_etc_ipsec_conf_newgroup: root
      when:
      - '"libreswan" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ipsec.conf
      ansible.builtin.stat:
        path: /etc/ipsec.conf
      register: file_exists
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ipsec.conf
      ansible.builtin.file:
        path: /etc/ipsec.conf
        follow: false
        group: '{{ file_groupowner_etc_ipsec_conf_newgroup }}'
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/ipsec.secrets File [ref]

To properly set the group owner of `/etc/ipsec.secrets`, run the command:

    $ sudo chgrp root /etc/ipsec.secrets

Rationale: | The ownership of the /etc/ipsec.secrets file by the root group is important because this file hosts Libreswan configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_ipsec_secrets

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/ipsec.secrets" | grep -E -w -q "root"; then
        chgrp --no-dereference "$newgroup" /etc/ipsec.secrets
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_groupowner_etc_ipsec_secrets_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_etc_ipsec_secrets_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_etc_ipsec_secrets_newgroup: root
      when:
      - '"libreswan" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ipsec.secrets
      ansible.builtin.stat:
        path: /etc/ipsec.secrets
      register: file_exists
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ipsec.secrets
      ansible.builtin.file:
        path: /etc/ipsec.secrets
        follow: false
        group: '{{ file_groupowner_etc_ipsec_secrets_newgroup }}'
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/ipsec.conf File [ref]

To properly set the owner of `/etc/ipsec.conf`, run the command:

    $ sudo chown root /etc/ipsec.conf

Rationale: | The ownership of the /etc/ipsec.conf file by the root user is important because this file hosts Libreswan configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_ipsec_conf

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/ipsec.conf" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/ipsec.conf
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_etc_ipsec_conf_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_ipsec_conf_newown: '0'
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ipsec.conf
      ansible.builtin.stat:
        path: /etc/ipsec.conf
      register: file_exists
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/ipsec.conf
      ansible.builtin.file:
        path: /etc/ipsec.conf
        follow: false
        owner: '{{ file_owner_etc_ipsec_conf_newown }}'
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/ipsec.secrets File [ref]

To properly set the owner of `/etc/ipsec.secrets`, run the command:

    $ sudo chown root /etc/ipsec.secrets

Rationale: | The ownership of the /etc/ipsec.secrets file by the root user is important because this file hosts Libreswan configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_ipsec_secrets

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/ipsec.secrets" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/ipsec.secrets
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_etc_ipsec_secrets_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_ipsec_secrets_newown: '0'
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ipsec.secrets
      ansible.builtin.stat:
        path: /etc/ipsec.secrets
      register: file_exists
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/ipsec.secrets
      ansible.builtin.file:
        path: /etc/ipsec.secrets
        follow: false
        owner: '{{ file_owner_etc_ipsec_secrets_newown }}'
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/ipsec.conf File [ref]

To properly set the permissions of `/etc/ipsec.conf`, run the command:

    $ sudo chmod 0644 /etc/ipsec.conf

Rationale: | Setting correct permissions on the /etc/ipsec.conf file is important because this file hosts Libreswan configuration. Protection of this file is critical for system security. Restricting the permissions ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_ipsec_conf

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xs,g-xws,o-xwt /etc/ipsec.conf

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ipsec.conf
      ansible.builtin.stat:
        path: /etc/ipsec.conf
      register: file_exists
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/ipsec.conf
      ansible.builtin.file:
        path: /etc/ipsec.conf
        mode: u-xs,g-xws,o-xwt
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_ipsec_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/ipsec.secrets File [ref]

To properly set the permissions of `/etc/ipsec.secrets`, run the command:

    $ sudo chmod 0644 /etc/ipsec.secrets

Rationale: | Setting correct permissions on the /etc/ipsec.secrets file is important because this file hosts Libreswan configuration. Protection of this file is critical for system security. Restricting the permissions ensures exclusive control of the Libreswan configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_ipsec_secrets

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'libreswan' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xs,g-xws,o-xwt /etc/ipsec.secrets

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ipsec.secrets
      ansible.builtin.stat:
        path: /etc/ipsec.secrets
      register: file_exists
      when: '"libreswan" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/ipsec.secrets
      ansible.builtin.file:
        path: /etc/ipsec.secrets
        mode: u-xs,g-xws,o-xwt
      when:
      - '"libreswan" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_ipsec_secrets
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group iptables and ip6tables Group contains 3 rules

[ref] A host-based firewall called `netfilter` is included as part of the Linux kernel distributed with the system. It is activated by default. This firewall is controlled by the program `iptables`, and the entire capability is frequently referred to by this name. An analogous program called `ip6tables` handles filtering for IPv6.
Unlike TCP Wrappers, which depends on the network server program to support and respect the rules written, `netfilter` filtering occurs at the kernel level, before a program can even process the data from the network packet. As such, any program on the system is affected by the rules written.
This section provides basic information about strengthening the `iptables` and `ip6tables` configurations included with the system. For more complete information that may allow the construction of a sophisticated ruleset tailored to your environment, please consult the references at the end of this section.

#### Rule Verify Group Who Owns /etc/iptables Directory [ref]

To properly set the group owner of `/etc/iptables`, run the command:

    $ sudo chgrp root /etc/iptables

Rationale: | The ownership of the /etc/iptables directory by the root group is important because this directory hosts iptables configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the iptables configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_groupowner_etc_iptables

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'iptables' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /etc/iptables/ -maxdepth 0 -type d  ! -group root -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_groupowner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"iptables" in ansible_facts.packages'
      - directory_groupowner_etc_iptables_newgroup is undefined
      tags:
      - configure_strategy
      - directory_groupowner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_etc_iptables_newgroup variable if root found
      ansible.builtin.set_fact:
        directory_groupowner_etc_iptables_newgroup: root
      when:
      - '"iptables" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - directory_groupowner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/iptables/
      ansible.builtin.file:
        path: /etc/iptables/
        follow: false
        state: directory
        group: '{{ directory_groupowner_etc_iptables_newgroup }}'
      when: '"iptables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_groupowner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/iptables Directory [ref]

To properly set the owner of `/etc/iptables`, run the command:

    $ sudo chown root /etc/iptables

Rationale: | The ownership of the /etc/iptables directory by the root user is important because this directory hosts iptables configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the iptables configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_owner_etc_iptables

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'iptables' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/iptables/ -maxdepth 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_owner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_etc_iptables_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_etc_iptables_newown: '0'
      when: '"iptables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/iptables/
      ansible.builtin.file:
        path: /etc/iptables/
        follow: false
        state: directory
        owner: '{{ directory_owner_etc_iptables_newown }}'
      when: '"iptables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/iptables Directory [ref]

To properly set the permissions of `/etc/iptables`, run the command:

    $ sudo chmod 0700 /etc/iptables

Rationale: | Setting correct permissions on the /etc/iptables directory is important because this directory hosts iptables configuration. Protection of this directory is critical for system security. Restricting the permissions ensures exclusive control of the iptables configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_etc_iptables

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'iptables' 2>/dev/null | grep -q '^installed$'; then

    find -H /etc/iptables/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt -type d -exec chmod u-s,g-xwrs,o-xwrt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_permissions_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/iptables/ file(s)
      ansible.builtin.command: 'find -P /etc/iptables/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"iptables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/iptables/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"iptables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_iptables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group IPv6 Group contains 1 group and 16 rules
[ref] The system includes support for Internet Protocol version 6. A major and often-mentioned improvement over IPv4 is its enormous increase in the number of available addresses. Another important feature is its support for automatic configuration of many network settings.
Group Configure IPv6 Settings if Necessary Group contains 16 rules
[ref] A major feature of IPv6 is the extent to which systems implementing it can automatically configure their networking devices using information from the network. From a security perspective, manually configuring important configuration information is preferable to accepting it from the network in an unauthenticated fashion.

#### Rule Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.accept_ra_defrtr` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.accept_ra_defrtr=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.accept_ra_defrtr = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_accept_ra_defrtr

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.accept_ra_defrtr from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.accept_ra_defrtr.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.accept_ra_defrtr" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_accept_ra_defrtr_value='0'

    #
    # Set runtime for net.ipv6.conf.all.accept_ra_defrtr
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.accept_ra_defrtr="$sysctl_net_ipv6_conf_all_accept_ra_defrtr_value"
    fi

    #
    # If net.ipv6.conf.all.accept_ra_defrtr present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.accept_ra_defrtr = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.accept_ra_defrtr")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_accept_ra_defrtr_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 "^net.ipv6.conf.all.accept_ra_defrtr\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.accept_ra_defrtr\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_defrtr
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_all_accept_ra_defrtr_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_accept_ra_defrtr_value: !!str 0
      tags:
        - always

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        - Find all files that contain net.ipv6.conf.all.accept_ra_defrtr
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra_defrtr\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        - Find all files that set net.ipv6.conf.all.accept_ra_defrtr to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra_defrtr\s*=\s*{{ sysctl_net_ipv6_conf_all_accept_ra_defrtr_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        - Comment out any occurrences of net.ipv6.conf.all.accept_ra_defrtr from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.accept_ra_defrtr
        replace: '#net.ipv6.conf.all.accept_ra_defrtr'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        - Ensure sysctl net.ipv6.conf.all.accept_ra_defrtr is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.accept_ra_defrtr
        value: '{{ sysctl_net_ipv6_conf_all_accept_ra_defrtr_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_defrtr
      - unknown_severity

#### Rule Configure Accepting Prefix Information in Router Advertisements on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.accept_ra_pinfo` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.accept_ra_pinfo=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.accept_ra_pinfo = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_accept_ra_pinfo

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.accept_ra_pinfo from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.accept_ra_pinfo.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.accept_ra_pinfo" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_accept_ra_pinfo_value='0'

    #
    # Set runtime for net.ipv6.conf.all.accept_ra_pinfo
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.accept_ra_pinfo="$sysctl_net_ipv6_conf_all_accept_ra_pinfo_value"
    fi

    #
    # If net.ipv6.conf.all.accept_ra_pinfo present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.accept_ra_pinfo = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.accept_ra_pinfo")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_accept_ra_pinfo_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 "^net.ipv6.conf.all.accept_ra_pinfo\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.accept_ra_pinfo\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_pinfo
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_all_accept_ra_pinfo_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_accept_ra_pinfo_value: !!str 0
      tags:
        - always

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces - Find all files that contain net.ipv6.conf.all.accept_ra_pinfo
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra_pinfo\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces - Find all files that set net.ipv6.conf.all.accept_ra_pinfo to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra_pinfo\s*=\s*{{ sysctl_net_ipv6_conf_all_accept_ra_pinfo_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces - Comment out any occurrences of net.ipv6.conf.all.accept_ra_pinfo
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.accept_ra_pinfo
        replace: '#net.ipv6.conf.all.accept_ra_pinfo'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces - Ensure sysctl net.ipv6.conf.all.accept_ra_pinfo is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.accept_ra_pinfo
        value: '{{ sysctl_net_ipv6_conf_all_accept_ra_pinfo_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_pinfo
      - unknown_severity

#### Rule Configure Accepting Router Preference in Router Advertisements on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.accept_ra_rtr_pref` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.accept_ra_rtr_pref=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.accept_ra_rtr_pref = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_accept_ra_rtr_pref

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.accept_ra_rtr_pref from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.accept_ra_rtr_pref.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.accept_ra_rtr_pref" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_value='0'

    #
    # Set runtime for net.ipv6.conf.all.accept_ra_rtr_pref
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.accept_ra_rtr_pref="$sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_value"
    fi

    #
    # If net.ipv6.conf.all.accept_ra_rtr_pref present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.accept_ra_rtr_pref = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.accept_ra_rtr_pref")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_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 "^net.ipv6.conf.all.accept_ra_rtr_pref\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.accept_ra_rtr_pref\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_rtr_pref
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_value: !!str 0
      tags:
        - always

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces - Find all files that contain net.ipv6.conf.all.accept_ra_rtr_pref
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra_rtr_pref\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces - Find all files that set net.ipv6.conf.all.accept_ra_rtr_pref to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_ra_rtr_pref\s*=\s*{{ sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces - Comment out any occurrences of net.ipv6.conf.all.accept_ra_rtr_pref
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.accept_ra_rtr_pref
        replace: '#net.ipv6.conf.all.accept_ra_rtr_pref'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces - Ensure sysctl net.ipv6.conf.all.accept_ra_rtr_pref is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.accept_ra_rtr_pref
        value: '{{ sysctl_net_ipv6_conf_all_accept_ra_rtr_pref_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_ra_rtr_pref
      - unknown_severity

#### Rule Disable Accepting ICMP Redirects for All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.accept_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.accept_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.accept_redirects = 0

Rationale: | An illicit ICMP redirect message could result in a man-in-the-middle attack.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_accept_redirects

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a), CM-6(b), CM-6.1(iv)
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.accept_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.accept_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.accept_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_accept_redirects_value='0'

    #
    # Set runtime for net.ipv6.conf.all.accept_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.accept_redirects="$sysctl_net_ipv6_conf_all_accept_redirects_value"
    fi

    #
    # If net.ipv6.conf.all.accept_redirects present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.accept_redirects = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.accept_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_accept_redirects_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 "^net.ipv6.conf.all.accept_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.accept_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_redirects
    - name: XCCDF Value sysctl_net_ipv6_conf_all_accept_redirects_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_accept_redirects_value: !!str 0
      tags:
        - always

    - name: Disable Accepting ICMP Redirects for All IPv6 Interfaces - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv6 Interfaces - Find all files
        that contain net.ipv6.conf.all.accept_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv6 Interfaces - Find all files
        that set net.ipv6.conf.all.accept_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_redirects\s*=\s*{{ sysctl_net_ipv6_conf_all_accept_redirects_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv6 Interfaces - Comment out any
        occurrences of net.ipv6.conf.all.accept_redirects from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.accept_redirects
        replace: '#net.ipv6.conf.all.accept_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv6 Interfaces - Ensure sysctl net.ipv6.conf.all.accept_redirects
        is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.accept_redirects
        value: '{{ sysctl_net_ipv6_conf_all_accept_redirects_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_redirects

#### Rule Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.accept_source_route` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.accept_source_route=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.accept_source_route = 0

Rationale:

Source-routed packets allow the source of the packet to suggest routers forward the packet along a different path than configured on the router, which can be used to bypass network security measures. This requirement applies only to the forwarding of source-routerd traffic, such as when IPv6 forwarding is enabled and the system is functioning as a router.
Accepting source-routed packets in the IPv6 protocol has few legitimate uses. It should be disabled unless it is absolutely required.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_accept_source_route

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 4, 6, 8, 9
cobit5 | APO01.06, APO13.01, DSS01.05, DSS03.01, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | DE.AE-1, ID.AM-3, PR.AC-5, PR.DS-5, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.accept_source_route from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.accept_source_route.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.accept_source_route" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_accept_source_route_value='0'

    #
    # Set runtime for net.ipv6.conf.all.accept_source_route
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.accept_source_route="$sysctl_net_ipv6_conf_all_accept_source_route_value"
    fi

    #
    # If net.ipv6.conf.all.accept_source_route present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.accept_source_route = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.accept_source_route")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_accept_source_route_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 "^net.ipv6.conf.all.accept_source_route\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.accept_source_route\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_source_route
    - name: XCCDF Value sysctl_net_ipv6_conf_all_accept_source_route_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_accept_source_route_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv6 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv6 Interfaces
        - Find all files that contain net.ipv6.conf.all.accept_source_route
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_source_route\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv6 Interfaces
        - Find all files that set net.ipv6.conf.all.accept_source_route to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.accept_source_route\s*=\s*{{ sysctl_net_ipv6_conf_all_accept_source_route_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv6 Interfaces
        - Comment out any occurrences of net.ipv6.conf.all.accept_source_route from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.accept_source_route
        replace: '#net.ipv6.conf.all.accept_source_route'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv6 Interfaces
        - Ensure sysctl net.ipv6.conf.all.accept_source_route is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.accept_source_route
        value: '{{ sysctl_net_ipv6_conf_all_accept_source_route_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_all_accept_source_route

#### Rule Configure Auto Configuration on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.autoconf` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.autoconf=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.autoconf = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_autoconf

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.autoconf from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.autoconf.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.autoconf" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_autoconf_value='0'

    #
    # Set runtime for net.ipv6.conf.all.autoconf
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.autoconf="$sysctl_net_ipv6_conf_all_autoconf_value"
    fi

    #
    # If net.ipv6.conf.all.autoconf present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.autoconf = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.autoconf")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_autoconf_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 "^net.ipv6.conf.all.autoconf\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.autoconf\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_autoconf
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_all_autoconf_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_autoconf_value: !!str 0
      tags:
        - always

    - name: Configure Auto Configuration on All IPv6 Interfaces - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces - Find all files that
        contain net.ipv6.conf.all.autoconf
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.autoconf\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces - Find all files that
        set net.ipv6.conf.all.autoconf to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.autoconf\s*=\s*{{ sysctl_net_ipv6_conf_all_autoconf_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces - Comment out any occurrences
        of net.ipv6.conf.all.autoconf from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.autoconf
        replace: '#net.ipv6.conf.all.autoconf'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces - Ensure sysctl net.ipv6.conf.all.autoconf
        is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.autoconf
        value: '{{ sysctl_net_ipv6_conf_all_autoconf_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_autoconf
      - unknown_severity

#### Rule Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.max_addresses` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.max_addresses=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.max_addresses = 1

Rationale: | The number of global unicast IPv6 addresses for each interface should be limited exactly to the number of statically configured addresses.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_max_addresses

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.max_addresses from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.max_addresses.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.max_addresses" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_max_addresses_value='1'

    #
    # Set runtime for net.ipv6.conf.all.max_addresses
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.max_addresses="$sysctl_net_ipv6_conf_all_max_addresses_value"
    fi

    #
    # If net.ipv6.conf.all.max_addresses present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.max_addresses = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.max_addresses")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_max_addresses_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 "^net.ipv6.conf.all.max_addresses\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.max_addresses\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_max_addresses
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_all_max_addresses_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_max_addresses_value: !!str 1
      tags:
        - always

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        - Find all files that contain net.ipv6.conf.all.max_addresses
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.max_addresses\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        - Find all files that set net.ipv6.conf.all.max_addresses to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.max_addresses\s*=\s*{{ sysctl_net_ipv6_conf_all_max_addresses_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        - Comment out any occurrences of net.ipv6.conf.all.max_addresses from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.max_addresses
        replace: '#net.ipv6.conf.all.max_addresses'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        - Ensure sysctl net.ipv6.conf.all.max_addresses is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.max_addresses
        value: '{{ sysctl_net_ipv6_conf_all_max_addresses_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_max_addresses
      - unknown_severity

#### Rule Configure Denying Router Solicitations on All IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.all.router_solicitations` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.all.router_solicitations=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.all.router_solicitations = 0

Rationale: | To prevent discovery of the system by other systems, router solicitation requests should be denied.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_all_router_solicitations

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.all.router_solicitations from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.all.router_solicitations.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.all.router_solicitations" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_all_router_solicitations_value='0'

    #
    # Set runtime for net.ipv6.conf.all.router_solicitations
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.all.router_solicitations="$sysctl_net_ipv6_conf_all_router_solicitations_value"
    fi

    #
    # If net.ipv6.conf.all.router_solicitations present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.all.router_solicitations = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.all.router_solicitations")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_all_router_solicitations_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 "^net.ipv6.conf.all.router_solicitations\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.all.router_solicitations\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_router_solicitations
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_all_router_solicitations_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_all_router_solicitations_value: !!str 0
      tags:
        - always

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces - Set fact for
        sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces - Find all files
        that contain net.ipv6.conf.all.router_solicitations
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.router_solicitations\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces - Find all files
        that set net.ipv6.conf.all.router_solicitations to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.all.router_solicitations\s*=\s*{{ sysctl_net_ipv6_conf_all_router_solicitations_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces - Comment out
        any occurrences of net.ipv6.conf.all.router_solicitations from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.all.router_solicitations
        replace: '#net.ipv6.conf.all.router_solicitations'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces - Ensure sysctl
        net.ipv6.conf.all.router_solicitations is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.all.router_solicitations
        value: '{{ sysctl_net_ipv6_conf_all_router_solicitations_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_all_router_solicitations
      - unknown_severity

#### Rule Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces By Default [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_ra_defrtr` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_ra_defrtr=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.accept_ra_defrtr = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_accept_ra_defrtr

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.accept_ra_defrtr from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.accept_ra_defrtr.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.accept_ra_defrtr" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_accept_ra_defrtr_value='0'

    #
    # Set runtime for net.ipv6.conf.default.accept_ra_defrtr
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.accept_ra_defrtr="$sysctl_net_ipv6_conf_default_accept_ra_defrtr_value"
    fi

    #
    # If net.ipv6.conf.default.accept_ra_defrtr present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.accept_ra_defrtr = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.accept_ra_defrtr")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_accept_ra_defrtr_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 "^net.ipv6.conf.default.accept_ra_defrtr\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.accept_ra_defrtr\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_defrtr
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_default_accept_ra_defrtr_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_accept_ra_defrtr_value: !!str 0
      tags:
        - always

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        By Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        By Default - Find all files that contain net.ipv6.conf.default.accept_ra_defrtr
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra_defrtr\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        By Default - Find all files that set net.ipv6.conf.default.accept_ra_defrtr to
        correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra_defrtr\s*=\s*{{ sysctl_net_ipv6_conf_default_accept_ra_defrtr_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        By Default - Comment out any occurrences of net.ipv6.conf.default.accept_ra_defrtr
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.accept_ra_defrtr
        replace: '#net.ipv6.conf.default.accept_ra_defrtr'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_defrtr
      - unknown_severity

    - name: Configure Accepting Default Router in Router Advertisements on All IPv6 Interfaces
        By Default - Ensure sysctl net.ipv6.conf.default.accept_ra_defrtr is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.accept_ra_defrtr
        value: '{{ sysctl_net_ipv6_conf_default_accept_ra_defrtr_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_defrtr
      - unknown_severity

#### Rule Configure Accepting Prefix Information in Router Advertisements on All IPv6 Interfaces By Default [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_ra_pinfo` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_ra_pinfo=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.accept_ra_pinfo = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_accept_ra_pinfo

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.accept_ra_pinfo from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.accept_ra_pinfo.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.accept_ra_pinfo" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_accept_ra_pinfo_value='0'

    #
    # Set runtime for net.ipv6.conf.default.accept_ra_pinfo
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.accept_ra_pinfo="$sysctl_net_ipv6_conf_default_accept_ra_pinfo_value"
    fi

    #
    # If net.ipv6.conf.default.accept_ra_pinfo present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.accept_ra_pinfo = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.accept_ra_pinfo")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_accept_ra_pinfo_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 "^net.ipv6.conf.default.accept_ra_pinfo\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.accept_ra_pinfo\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_pinfo
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_default_accept_ra_pinfo_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_accept_ra_pinfo_value: !!str 0
      tags:
        - always

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces By Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces By Default - Find all files that contain net.ipv6.conf.default.accept_ra_pinfo
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra_pinfo\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces By Default - Find all files that set net.ipv6.conf.default.accept_ra_pinfo
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra_pinfo\s*=\s*{{ sysctl_net_ipv6_conf_default_accept_ra_pinfo_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces By Default - Comment out any occurrences of net.ipv6.conf.default.accept_ra_pinfo
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.accept_ra_pinfo
        replace: '#net.ipv6.conf.default.accept_ra_pinfo'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_pinfo
      - unknown_severity

    - name: Configure Accepting Prefix Information in Router Advertisements on All IPv6
        Interfaces By Default - Ensure sysctl net.ipv6.conf.default.accept_ra_pinfo is
        set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.accept_ra_pinfo
        value: '{{ sysctl_net_ipv6_conf_default_accept_ra_pinfo_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_pinfo
      - unknown_severity

#### Rule Configure Accepting Router Preference in Router Advertisements on All IPv6 Interfaces By Default [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_ra_rtr_pref` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_ra_rtr_pref=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.accept_ra_rtr_pref = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_accept_ra_rtr_pref

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.accept_ra_rtr_pref from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.accept_ra_rtr_pref.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.accept_ra_rtr_pref" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_value='0'

    #
    # Set runtime for net.ipv6.conf.default.accept_ra_rtr_pref
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.accept_ra_rtr_pref="$sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_value"
    fi

    #
    # If net.ipv6.conf.default.accept_ra_rtr_pref present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.accept_ra_rtr_pref = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.accept_ra_rtr_pref")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_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 "^net.ipv6.conf.default.accept_ra_rtr_pref\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.accept_ra_rtr_pref\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_rtr_pref
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_value: !!str 0
      tags:
        - always

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces By Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces By Default - Find all files that contain net.ipv6.conf.default.accept_ra_rtr_pref
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra_rtr_pref\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces By Default - Find all files that set net.ipv6.conf.default.accept_ra_rtr_pref
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_ra_rtr_pref\s*=\s*{{ sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces By Default - Comment out any occurrences of net.ipv6.conf.default.accept_ra_rtr_pref
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.accept_ra_rtr_pref
        replace: '#net.ipv6.conf.default.accept_ra_rtr_pref'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_rtr_pref
      - unknown_severity

    - name: Configure Accepting Router Preference in Router Advertisements on All IPv6
        Interfaces By Default - Ensure sysctl net.ipv6.conf.default.accept_ra_rtr_pref
        is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.accept_ra_rtr_pref
        value: '{{ sysctl_net_ipv6_conf_default_accept_ra_rtr_pref_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_ra_rtr_pref
      - unknown_severity

#### Rule Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv6 Interfaces [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.accept_redirects = 0

Rationale: | An illicit ICMP redirect message could result in a man-in-the-middle attack.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_accept_redirects

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.accept_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.accept_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.accept_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_accept_redirects_value='0'

    #
    # Set runtime for net.ipv6.conf.default.accept_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.accept_redirects="$sysctl_net_ipv6_conf_default_accept_redirects_value"
    fi

    #
    # If net.ipv6.conf.default.accept_redirects present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.accept_redirects = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.accept_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_accept_redirects_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 "^net.ipv6.conf.default.accept_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.accept_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_redirects
    - name: XCCDF Value sysctl_net_ipv6_conf_default_accept_redirects_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_accept_redirects_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv6 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv6 Interfaces
        - Find all files that contain net.ipv6.conf.default.accept_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv6 Interfaces
        - Find all files that set net.ipv6.conf.default.accept_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_redirects\s*=\s*{{ sysctl_net_ipv6_conf_default_accept_redirects_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv6 Interfaces
        - Comment out any occurrences of net.ipv6.conf.default.accept_redirects from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.accept_redirects
        replace: '#net.ipv6.conf.default.accept_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv6 Interfaces
        - Ensure sysctl net.ipv6.conf.default.accept_redirects is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.accept_redirects
        value: '{{ sysctl_net_ipv6_conf_default_accept_redirects_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_redirects

#### Rule Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces by Default [ref]

To set the runtime status of the `net.ipv6.conf.default.accept_source_route` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.accept_source_route=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.accept_source_route = 0

Rationale:

Source-routed packets allow the source of the packet to suggest routers forward the packet along a different path than configured on the router, which can be used to bypass network security measures. This requirement applies only to the forwarding of source-routerd traffic, such as when IPv6 forwarding is enabled and the system is functioning as a router. Accepting source-routed packets in the IPv6 protocol has few legitimate uses. It should be disabled unless it is absolutely required.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_accept_source_route

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 4, 6, 8, 9
cobit5 | APO01.06, APO13.01, DSS01.05, DSS03.01, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), CM-6(b), CM-6.1(iv)
nist-csf | DE.AE-1, ID.AM-3, PR.AC-5, PR.DS-5, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R13
pcidss4 | 1.4.2, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.accept_source_route from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.accept_source_route.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.accept_source_route" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_accept_source_route_value='0'

    #
    # Set runtime for net.ipv6.conf.default.accept_source_route
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.accept_source_route="$sysctl_net_ipv6_conf_default_accept_source_route_value"
    fi

    #
    # If net.ipv6.conf.default.accept_source_route present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.accept_source_route = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.accept_source_route")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_accept_source_route_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 "^net.ipv6.conf.default.accept_source_route\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.accept_source_route\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_source_route
    - name: XCCDF Value sysctl_net_ipv6_conf_default_accept_source_route_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_accept_source_route_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces
        by Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces
        by Default - Find all files that contain net.ipv6.conf.default.accept_source_route
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_source_route\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces
        by Default - Find all files that set net.ipv6.conf.default.accept_source_route
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.accept_source_route\s*=\s*{{ sysctl_net_ipv6_conf_default_accept_source_route_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces
        by Default - Comment out any occurrences of net.ipv6.conf.default.accept_source_route
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.accept_source_route
        replace: '#net.ipv6.conf.default.accept_source_route'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv6 Interfaces
        by Default - Ensure sysctl net.ipv6.conf.default.accept_source_route is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.accept_source_route
        value: '{{ sysctl_net_ipv6_conf_default_accept_source_route_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-6(b)
      - NIST-800-53-CM-6.1(iv)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv6_conf_default_accept_source_route

#### Rule Configure Auto Configuration on All IPv6 Interfaces By Default [ref]

To set the runtime status of the `net.ipv6.conf.default.autoconf` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.autoconf=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.autoconf = 0

Rationale: | An illicit router advertisement message could result in a man-in-the-middle attack.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_autoconf

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.autoconf from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.autoconf.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.autoconf" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_autoconf_value='0'

    #
    # Set runtime for net.ipv6.conf.default.autoconf
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.autoconf="$sysctl_net_ipv6_conf_default_autoconf_value"
    fi

    #
    # If net.ipv6.conf.default.autoconf present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.autoconf = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.autoconf")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_autoconf_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 "^net.ipv6.conf.default.autoconf\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.autoconf\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_autoconf
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_default_autoconf_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_autoconf_value: !!str 0
      tags:
        - always

    - name: Configure Auto Configuration on All IPv6 Interfaces By Default - Set fact
        for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces By Default - Find all
        files that contain net.ipv6.conf.default.autoconf
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.autoconf\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces By Default - Find all
        files that set net.ipv6.conf.default.autoconf to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.autoconf\s*=\s*{{ sysctl_net_ipv6_conf_default_autoconf_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces By Default - Comment out
        any occurrences of net.ipv6.conf.default.autoconf from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.autoconf
        replace: '#net.ipv6.conf.default.autoconf'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_autoconf
      - unknown_severity

    - name: Configure Auto Configuration on All IPv6 Interfaces By Default - Ensure sysctl
        net.ipv6.conf.default.autoconf is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.autoconf
        value: '{{ sysctl_net_ipv6_conf_default_autoconf_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_autoconf
      - unknown_severity

#### Rule Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces By Default [ref]

To set the runtime status of the `net.ipv6.conf.default.max_addresses` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.max_addresses=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.max_addresses = 1

Rationale: | The number of global unicast IPv6 addresses for each interface should be limited exactly to the number of statically configured addresses.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_max_addresses

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.max_addresses from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.max_addresses.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.max_addresses" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_max_addresses_value='1'

    #
    # Set runtime for net.ipv6.conf.default.max_addresses
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.max_addresses="$sysctl_net_ipv6_conf_default_max_addresses_value"
    fi

    #
    # If net.ipv6.conf.default.max_addresses present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.max_addresses = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.max_addresses")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_max_addresses_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 "^net.ipv6.conf.default.max_addresses\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.max_addresses\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_max_addresses
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_default_max_addresses_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_max_addresses_value: !!str 1
      tags:
        - always

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        By Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        By Default - Find all files that contain net.ipv6.conf.default.max_addresses
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.max_addresses\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        By Default - Find all files that set net.ipv6.conf.default.max_addresses to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.max_addresses\s*=\s*{{ sysctl_net_ipv6_conf_default_max_addresses_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        By Default - Comment out any occurrences of net.ipv6.conf.default.max_addresses
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.max_addresses
        replace: '#net.ipv6.conf.default.max_addresses'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_max_addresses
      - unknown_severity

    - name: Configure Maximum Number of Autoconfigured Addresses on All IPv6 Interfaces
        By Default - Ensure sysctl net.ipv6.conf.default.max_addresses is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.max_addresses
        value: '{{ sysctl_net_ipv6_conf_default_max_addresses_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_max_addresses
      - unknown_severity

#### Rule Configure Denying Router Solicitations on All IPv6 Interfaces By Default [ref]

To set the runtime status of the `net.ipv6.conf.default.router_solicitations` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv6.conf.default.router_solicitations=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv6.conf.default.router_solicitations = 0

Rationale: | To prevent discovery of the system by other systems, router solicitation requests should be denied.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv6_conf_default_router_solicitations

References:

anssi | R13

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv6.conf.default.router_solicitations from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv6.conf.default.router_solicitations.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv6.conf.default.router_solicitations" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv6_conf_default_router_solicitations_value='0'

    #
    # Set runtime for net.ipv6.conf.default.router_solicitations
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv6.conf.default.router_solicitations="$sysctl_net_ipv6_conf_default_router_solicitations_value"
    fi

    #
    # If net.ipv6.conf.default.router_solicitations present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv6.conf.default.router_solicitations = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv6.conf.default.router_solicitations")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv6_conf_default_router_solicitations_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 "^net.ipv6.conf.default.router_solicitations\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv6.conf.default.router_solicitations\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_router_solicitations
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv6_conf_default_router_solicitations_value # promote to variable
      set_fact:
        sysctl_net_ipv6_conf_default_router_solicitations_value: !!str 0
      tags:
        - always

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces By Default -
        Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces By Default -
        Find all files that contain net.ipv6.conf.default.router_solicitations
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.router_solicitations\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces By Default -
        Find all files that set net.ipv6.conf.default.router_solicitations to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv6.conf.default.router_solicitations\s*=\s*{{ sysctl_net_ipv6_conf_default_router_solicitations_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces By Default -
        Comment out any occurrences of net.ipv6.conf.default.router_solicitations from
        config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv6.conf.default.router_solicitations
        replace: '#net.ipv6.conf.default.router_solicitations'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_router_solicitations
      - unknown_severity

    - name: Configure Denying Router Solicitations on All IPv6 Interfaces By Default -
        Ensure sysctl net.ipv6.conf.default.router_solicitations is set
      ansible.posix.sysctl:
        name: net.ipv6.conf.default.router_solicitations
        value: '{{ sysctl_net_ipv6_conf_default_router_solicitations_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv6_conf_default_router_solicitations
      - unknown_severity

Group Kernel Parameters Which Affect Networking Group contains 2 groups and 22 rules
[ref] The `sysctl` utility is used to set parameters which affect the operation of the Linux kernel. Kernel parameters which affect networking and have security implications are described here.
Group Network Related Kernel Runtime Parameters for Hosts and Routers Group contains 19 rules
[ref] Certain kernel parameters should be set for systems which are acting as either hosts or routers to improve the system's ability defend against certain types of IPv4 protocol attacks.

#### Rule Disable Accepting Packets Routed Between Local Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.accept_local` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.accept_local=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.accept_local = 0

Rationale: | Configure `net.ipv4.conf.all.accept_local=0` to consider as invalid the packets received from outside whose source is the 127.0.0.0/8 address block. In combination with suitable routing, this can be used to direct packets between two local interfaces over the wire and have them accepted properly.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_accept_local

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.accept_local from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.accept_local.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.accept_local" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.conf.all.accept_local
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.accept_local="0"
    fi

    #
    # If net.ipv4.conf.all.accept_local present in /etc/sysctl.conf, change value to "0"
    #	else, add "net.ipv4.conf.all.accept_local = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.accept_local")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^net.ipv4.conf.all.accept_local\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.accept_local\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_local

    - name: Disable Accepting Packets Routed Between Local Interfaces - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_local

    - name: Disable Accepting Packets Routed Between Local Interfaces - Find all files
        that contain net.ipv4.conf.all.accept_local
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.accept_local\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_local

    - name: Disable Accepting Packets Routed Between Local Interfaces - Find all files
        that set net.ipv4.conf.all.accept_local to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.accept_local\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_local

    - name: Disable Accepting Packets Routed Between Local Interfaces - Comment out any
        occurrences of net.ipv4.conf.all.accept_local from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.accept_local
        replace: '#net.ipv4.conf.all.accept_local'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_local

    - name: Disable Accepting Packets Routed Between Local Interfaces - Ensure sysctl
        net.ipv4.conf.all.accept_local is set to 0
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.accept_local
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_local

#### Rule Disable Accepting ICMP Redirects for All IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.accept_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.accept_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.accept_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages modify the host's route table and are unauthenticated. An illicit ICMP redirect message could result in a man-in-the-middle attack. This feature of the IPv4 protocol has few legitimate uses. It should be disabled unless absolutely required."
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_accept_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS05.02, DSS05.05, DSS05.07, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.CM-1, PR.DS-4, PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.accept_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.accept_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.accept_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_accept_redirects_value='0'

    #
    # Set runtime for net.ipv4.conf.all.accept_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.accept_redirects="$sysctl_net_ipv4_conf_all_accept_redirects_value"
    fi

    #
    # If net.ipv4.conf.all.accept_redirects present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.accept_redirects = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.accept_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_accept_redirects_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 "^net.ipv4.conf.all.accept_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.accept_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_redirects
    - name: XCCDF Value sysctl_net_ipv4_conf_all_accept_redirects_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_accept_redirects_value: !!str 0
      tags:
        - always

    - name: Disable Accepting ICMP Redirects for All IPv4 Interfaces - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv4 Interfaces - Find all files
        that contain net.ipv4.conf.all.accept_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.accept_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv4 Interfaces - Find all files
        that set net.ipv4.conf.all.accept_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.accept_redirects\s*=\s*{{ sysctl_net_ipv4_conf_all_accept_redirects_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv4 Interfaces - Comment out any
        occurrences of net.ipv4.conf.all.accept_redirects from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.accept_redirects
        replace: '#net.ipv4.conf.all.accept_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_redirects

    - name: Disable Accepting ICMP Redirects for All IPv4 Interfaces - Ensure sysctl net.ipv4.conf.all.accept_redirects
        is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.accept_redirects
        value: '{{ sysctl_net_ipv4_conf_all_accept_redirects_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_redirects

#### Rule Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.accept_source_route` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.accept_source_route=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.accept_source_route = 0

Rationale:

Source-routed packets allow the source of the packet to suggest routers forward the packet along a different path than configured on the router, which can be used to bypass network security measures. This requirement applies only to the forwarding of source-routerd traffic, such as when IPv4 forwarding is enabled and the system is functioning as a router.
Accepting source-routed packets in the IPv4 protocol has few legitimate uses. It should be disabled unless it is absolutely required.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_accept_source_route

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.accept_source_route from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.accept_source_route.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.accept_source_route" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_accept_source_route_value='0'

    #
    # Set runtime for net.ipv4.conf.all.accept_source_route
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.accept_source_route="$sysctl_net_ipv4_conf_all_accept_source_route_value"
    fi

    #
    # If net.ipv4.conf.all.accept_source_route present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.accept_source_route = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.accept_source_route")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_accept_source_route_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 "^net.ipv4.conf.all.accept_source_route\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.accept_source_route\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_source_route
    - name: XCCDF Value sysctl_net_ipv4_conf_all_accept_source_route_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_accept_source_route_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.all.accept_source_route
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.accept_source_route\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv4 Interfaces
        - Find all files that set net.ipv4.conf.all.accept_source_route to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.accept_source_route\s*=\s*{{ sysctl_net_ipv4_conf_all_accept_source_route_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.all.accept_source_route from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.accept_source_route
        replace: '#net.ipv4.conf.all.accept_source_route'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on all IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.all.accept_source_route is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.accept_source_route
        value: '{{ sysctl_net_ipv4_conf_all_accept_source_route_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_accept_source_route

#### Rule Configure ARP filtering for All IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.arp_filter` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.arp_filter=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.arp_filter = 0

Warning: This behaviour may cause problems to system on a high availability or load balancing configuration.

Rationale: | Prevents the Linux Kernel from handling the ARP table globally. By default, the kernel may respond to an ARP request from a certain interface with information from another interface.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_arp_filter

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.arp_filter from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.arp_filter.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.arp_filter" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_arp_filter_value='0'

    #
    # Set runtime for net.ipv4.conf.all.arp_filter
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.arp_filter="$sysctl_net_ipv4_conf_all_arp_filter_value"
    fi

    #
    # If net.ipv4.conf.all.arp_filter present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.arp_filter = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.arp_filter")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_arp_filter_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 "^net.ipv4.conf.all.arp_filter\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.arp_filter\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_filter
    - name: XCCDF Value sysctl_net_ipv4_conf_all_arp_filter_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_arp_filter_value: !!str 0
      tags:
        - always

    - name: Configure ARP filtering for All IPv4 Interfaces - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_filter

    - name: Configure ARP filtering for All IPv4 Interfaces - Find all files that contain
        net.ipv4.conf.all.arp_filter
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.arp_filter\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_filter

    - name: Configure ARP filtering for All IPv4 Interfaces - Find all files that set
        net.ipv4.conf.all.arp_filter to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.arp_filter\s*=\s*{{ sysctl_net_ipv4_conf_all_arp_filter_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_filter

    - name: Configure ARP filtering for All IPv4 Interfaces - Comment out any occurrences
        of net.ipv4.conf.all.arp_filter from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.arp_filter
        replace: '#net.ipv4.conf.all.arp_filter'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_filter

    - name: Configure ARP filtering for All IPv4 Interfaces - Ensure sysctl net.ipv4.conf.all.arp_filter
        is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.arp_filter
        value: '{{ sysctl_net_ipv4_conf_all_arp_filter_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_filter

#### Rule Configure Response Mode of ARP Requests for All IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.arp_ignore` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.arp_ignore=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.arp_ignore = 2

Warning: The ARP response mode may impact behaviour of workloads and firewalls on the system.

Rationale: | Avoids ARP Flux on system that have more than one interface on the same subnet.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_arp_ignore

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.arp_ignore from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.arp_ignore.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.arp_ignore" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_arp_ignore_value='2'

    #
    # Set runtime for net.ipv4.conf.all.arp_ignore
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.arp_ignore="$sysctl_net_ipv4_conf_all_arp_ignore_value"
    fi

    #
    # If net.ipv4.conf.all.arp_ignore present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.arp_ignore = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.arp_ignore")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_arp_ignore_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 "^net.ipv4.conf.all.arp_ignore\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.arp_ignore\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_ignore
    - name: XCCDF Value sysctl_net_ipv4_conf_all_arp_ignore_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_arp_ignore_value: !!str 2
      tags:
        - always

    - name: Configure Response Mode of ARP Requests for All IPv4 Interfaces - Set fact
        for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_ignore

    - name: Configure Response Mode of ARP Requests for All IPv4 Interfaces - Find all
        files that contain net.ipv4.conf.all.arp_ignore
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.arp_ignore\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_ignore

    - name: Configure Response Mode of ARP Requests for All IPv4 Interfaces - Find all
        files that set net.ipv4.conf.all.arp_ignore to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.arp_ignore\s*=\s*{{ sysctl_net_ipv4_conf_all_arp_ignore_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_ignore

    - name: Configure Response Mode of ARP Requests for All IPv4 Interfaces - Comment
        out any occurrences of net.ipv4.conf.all.arp_ignore from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.arp_ignore
        replace: '#net.ipv4.conf.all.arp_ignore'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_ignore

    - name: Configure Response Mode of ARP Requests for All IPv4 Interfaces - Ensure sysctl
        net.ipv4.conf.all.arp_ignore is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.arp_ignore
        value: '{{ sysctl_net_ipv4_conf_all_arp_ignore_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_arp_ignore

#### Rule Drop Gratuitous ARP frames on All IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.drop_gratuitous_arp` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.drop_gratuitous_arp=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.drop_gratuitous_arp = 1

Warning: This can cause problems if ARP proxies are used in the network.

Rationale: | Drop Gratuitous ARP frames to prevent ARP poisoning.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_drop_gratuitous_arp

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.drop_gratuitous_arp from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.drop_gratuitous_arp.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.drop_gratuitous_arp" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.conf.all.drop_gratuitous_arp
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.drop_gratuitous_arp="1"
    fi

    #
    # If net.ipv4.conf.all.drop_gratuitous_arp present in /etc/sysctl.conf, change value to "1"
    #	else, add "net.ipv4.conf.all.drop_gratuitous_arp = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.drop_gratuitous_arp")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^net.ipv4.conf.all.drop_gratuitous_arp\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.drop_gratuitous_arp\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_drop_gratuitous_arp

    - name: Drop Gratuitous ARP frames on All IPv4 Interfaces - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_drop_gratuitous_arp

    - name: Drop Gratuitous ARP frames on All IPv4 Interfaces - Find all files that contain
        net.ipv4.conf.all.drop_gratuitous_arp
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.drop_gratuitous_arp\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_drop_gratuitous_arp

    - name: Drop Gratuitous ARP frames on All IPv4 Interfaces - Find all files that set
        net.ipv4.conf.all.drop_gratuitous_arp to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.drop_gratuitous_arp\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_drop_gratuitous_arp

    - name: Drop Gratuitous ARP frames on All IPv4 Interfaces - Comment out any occurrences
        of net.ipv4.conf.all.drop_gratuitous_arp from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.drop_gratuitous_arp
        replace: '#net.ipv4.conf.all.drop_gratuitous_arp'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_drop_gratuitous_arp

    - name: Drop Gratuitous ARP frames on All IPv4 Interfaces - Ensure sysctl net.ipv4.conf.all.drop_gratuitous_arp
        is set to 1
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.drop_gratuitous_arp
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_drop_gratuitous_arp

#### Rule Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.route_localnet` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.route_localnet=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.route_localnet = 0

Rationale: | Refuse the routing of packets whose source or destination address is the local loopback. This prohibits the use of network 127/8 for local routing purposes. Enabling `route_localnet` can expose applications listening on localhost to external traffic.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_route_localnet

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.route_localnet from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.route_localnet.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.route_localnet" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.conf.all.route_localnet
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.route_localnet="0"
    fi

    #
    # If net.ipv4.conf.all.route_localnet present in /etc/sysctl.conf, change value to "0"
    #	else, add "net.ipv4.conf.all.route_localnet = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.route_localnet")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^net.ipv4.conf.all.route_localnet\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.route_localnet\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_route_localnet

    - name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_route_localnet

    - name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.all.route_localnet
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.route_localnet\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_route_localnet

    - name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces
        - Find all files that set net.ipv4.conf.all.route_localnet to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.route_localnet\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_route_localnet

    - name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.all.route_localnet from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.route_localnet
        replace: '#net.ipv4.conf.all.route_localnet'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_route_localnet

    - name: Prevent Routing External Traffic to Local Loopback on All IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.all.route_localnet is set to 0
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.route_localnet
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_route_localnet

#### Rule Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.rp_filter` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.rp_filter=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.rp_filter = 1

Rationale: | Enabling reverse path filtering drops packets with source addresses that should not have been able to be received on the interface they were received on. It should not be used on systems which are routers for complicated networks, but is helpful for end hosts and routers serving small networks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_rp_filter

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 2, 4, 6, 7, 8, 9
cobit5 | APO01.06, APO13.01, BAI04.04, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.3, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.rp_filter from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.rp_filter.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.rp_filter" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_rp_filter_value='1'

    #
    # Set runtime for net.ipv4.conf.all.rp_filter
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.rp_filter="$sysctl_net_ipv4_conf_all_rp_filter_value"
    fi

    #
    # If net.ipv4.conf.all.rp_filter present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.rp_filter = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.rp_filter")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_rp_filter_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 "^net.ipv4.conf.all.rp_filter\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.rp_filter\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_rp_filter
    - name: XCCDF Value sysctl_net_ipv4_conf_all_rp_filter_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_rp_filter_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.all.rp_filter
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.rp_filter\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        - Find all files that set net.ipv4.conf.all.rp_filter to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.rp_filter\s*=\s*{{ sysctl_net_ipv4_conf_all_rp_filter_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.all.rp_filter from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.rp_filter
        replace: '#net.ipv4.conf.all.rp_filter'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.all.rp_filter is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.rp_filter
        value: '{{ sysctl_net_ipv4_conf_all_rp_filter_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_rp_filter

#### Rule Disable Kernel Parameter for Accepting Secure ICMP Redirects on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.secure_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.secure_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.secure_redirects = 0

Rationale: | Accepting "secure" ICMP redirects (from those gateways listed as default gateways) has few legitimate uses. It should be disabled unless it is absolutely required.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_secure_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.3, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.secure_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.secure_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.secure_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_secure_redirects_value='0'

    #
    # Set runtime for net.ipv4.conf.all.secure_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.secure_redirects="$sysctl_net_ipv4_conf_all_secure_redirects_value"
    fi

    #
    # If net.ipv4.conf.all.secure_redirects present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.secure_redirects = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.secure_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_secure_redirects_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 "^net.ipv4.conf.all.secure_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.secure_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_secure_redirects
    - name: XCCDF Value sysctl_net_ipv4_conf_all_secure_redirects_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_secure_redirects_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting Secure ICMP Redirects on all IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_secure_redirects

    - name: Disable Kernel Parameter for Accepting Secure ICMP Redirects on all IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.all.secure_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.secure_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_secure_redirects

    - name: Disable Kernel Parameter for Accepting Secure ICMP Redirects on all IPv4 Interfaces
        - Find all files that set net.ipv4.conf.all.secure_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.secure_redirects\s*=\s*{{ sysctl_net_ipv4_conf_all_secure_redirects_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_secure_redirects

    - name: Disable Kernel Parameter for Accepting Secure ICMP Redirects on all IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.all.secure_redirects from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.secure_redirects
        replace: '#net.ipv4.conf.all.secure_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_secure_redirects

    - name: Disable Kernel Parameter for Accepting Secure ICMP Redirects on all IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.all.secure_redirects is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.secure_redirects
        value: '{{ sysctl_net_ipv4_conf_all_secure_redirects_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_secure_redirects

#### Rule Configure Sending and Accepting Shared Media Redirects for All IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.shared_media` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.shared_media=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.shared_media = 0

Rationale: | This setting should be aligned with `net.ipv4.conf.all.secure_redirects` because it overrides it. If `shared_media` is enabled for an interface `secure_redirects` will be enabled too.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_shared_media

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.shared_media from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.shared_media.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.shared_media" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_all_shared_media_value='0'

    #
    # Set runtime for net.ipv4.conf.all.shared_media
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.shared_media="$sysctl_net_ipv4_conf_all_shared_media_value"
    fi

    #
    # If net.ipv4.conf.all.shared_media present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.all.shared_media = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.shared_media")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_all_shared_media_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 "^net.ipv4.conf.all.shared_media\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.shared_media\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_shared_media
    - name: XCCDF Value sysctl_net_ipv4_conf_all_shared_media_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_all_shared_media_value: !!str 0
      tags:
        - always

    - name: Configure Sending and Accepting Shared Media Redirects for All IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects for All IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.all.shared_media
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.shared_media\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects for All IPv4 Interfaces
        - Find all files that set net.ipv4.conf.all.shared_media to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.shared_media\s*=\s*{{ sysctl_net_ipv4_conf_all_shared_media_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects for All IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.all.shared_media from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.shared_media
        replace: '#net.ipv4.conf.all.shared_media'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects for All IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.all.shared_media is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.shared_media
        value: '{{ sysctl_net_ipv4_conf_all_shared_media_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_shared_media

#### Rule Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.default.accept_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.accept_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.accept_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages modify the host's route table and are unauthenticated. An illicit ICMP redirect message could result in a man-in-the-middle attack. This feature of the IPv4 protocol has few legitimate uses. It should be disabled unless absolutely required.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_accept_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.3, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.default.accept_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.default.accept_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.default.accept_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_default_accept_redirects_value='0'

    #
    # Set runtime for net.ipv4.conf.default.accept_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.accept_redirects="$sysctl_net_ipv4_conf_default_accept_redirects_value"
    fi

    #
    # If net.ipv4.conf.default.accept_redirects present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.default.accept_redirects = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.default.accept_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_default_accept_redirects_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 "^net.ipv4.conf.default.accept_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.accept_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_redirects
    - name: XCCDF Value sysctl_net_ipv4_conf_default_accept_redirects_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_default_accept_redirects_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.default.accept_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.accept_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces
        - Find all files that set net.ipv4.conf.default.accept_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.accept_redirects\s*=\s*{{ sysctl_net_ipv4_conf_default_accept_redirects_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.default.accept_redirects from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.accept_redirects
        replace: '#net.ipv4.conf.default.accept_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_redirects

    - name: Disable Kernel Parameter for Accepting ICMP Redirects by Default on IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.default.accept_redirects is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.accept_redirects
        value: '{{ sysctl_net_ipv4_conf_default_accept_redirects_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_redirects

#### Rule Disable Kernel Parameter for Accepting Source-Routed Packets on IPv4 Interfaces by Default [ref]

To set the runtime status of the `net.ipv4.conf.default.accept_source_route` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.accept_source_route=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.accept_source_route = 0

Rationale:

Source-routed packets allow the source of the packet to suggest routers forward the packet along a different path than configured on the router, which can be used to bypass network security measures.
Accepting source-routed packets in the IPv4 protocol has few legitimate uses. It should be disabled unless it is absolutely required, such as when IPv4 forwarding is enabled and the system is legitimately functioning as a router.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_accept_source_route

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.default.accept_source_route from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.default.accept_source_route.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.default.accept_source_route" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_default_accept_source_route_value='0'

    #
    # Set runtime for net.ipv4.conf.default.accept_source_route
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.accept_source_route="$sysctl_net_ipv4_conf_default_accept_source_route_value"
    fi

    #
    # If net.ipv4.conf.default.accept_source_route present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.default.accept_source_route = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.default.accept_source_route")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_default_accept_source_route_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 "^net.ipv4.conf.default.accept_source_route\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.accept_source_route\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_source_route
    - name: XCCDF Value sysctl_net_ipv4_conf_default_accept_source_route_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_default_accept_source_route_value: !!str 0
      tags:
        - always

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv4 Interfaces
        by Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv4 Interfaces
        by Default - Find all files that contain net.ipv4.conf.default.accept_source_route
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.accept_source_route\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv4 Interfaces
        by Default - Find all files that set net.ipv4.conf.default.accept_source_route
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.accept_source_route\s*=\s*{{ sysctl_net_ipv4_conf_default_accept_source_route_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv4 Interfaces
        by Default - Comment out any occurrences of net.ipv4.conf.default.accept_source_route
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.accept_source_route
        replace: '#net.ipv4.conf.default.accept_source_route'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_source_route

    - name: Disable Kernel Parameter for Accepting Source-Routed Packets on IPv4 Interfaces
        by Default - Ensure sysctl net.ipv4.conf.default.accept_source_route is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.accept_source_route
        value: '{{ sysctl_net_ipv4_conf_default_accept_source_route_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_accept_source_route

#### Rule Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces by Default [ref]

To set the runtime status of the `net.ipv4.conf.default.rp_filter` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.rp_filter=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.rp_filter = 1

Rationale: | Enabling reverse path filtering drops packets with source addresses that should not have been able to be received on the interface they were received on. It should not be used on systems which are routers for complicated networks, but is helpful for end hosts and routers serving small networks.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_rp_filter

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 2, 4, 6, 7, 8, 9
cobit5 | APO01.06, APO13.01, BAI04.04, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.default.rp_filter from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.default.rp_filter.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.default.rp_filter" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_default_rp_filter_value='1'

    #
    # Set runtime for net.ipv4.conf.default.rp_filter
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.rp_filter="$sysctl_net_ipv4_conf_default_rp_filter_value"
    fi

    #
    # If net.ipv4.conf.default.rp_filter present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.default.rp_filter = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.default.rp_filter")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_default_rp_filter_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 "^net.ipv4.conf.default.rp_filter\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.rp_filter\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_rp_filter
    - name: XCCDF Value sysctl_net_ipv4_conf_default_rp_filter_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_default_rp_filter_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        by Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        by Default - Find all files that contain net.ipv4.conf.default.rp_filter
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.rp_filter\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        by Default - Find all files that set net.ipv4.conf.default.rp_filter to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.rp_filter\s*=\s*{{ sysctl_net_ipv4_conf_default_rp_filter_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        by Default - Comment out any occurrences of net.ipv4.conf.default.rp_filter from
        config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.rp_filter
        replace: '#net.ipv4.conf.default.rp_filter'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_rp_filter

    - name: Enable Kernel Parameter to Use Reverse Path Filtering on all IPv4 Interfaces
        by Default - Ensure sysctl net.ipv4.conf.default.rp_filter is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.rp_filter
        value: '{{ sysctl_net_ipv4_conf_default_rp_filter_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_rp_filter

#### Rule Configure Kernel Parameter for Accepting Secure Redirects By Default [ref]

To set the runtime status of the `net.ipv4.conf.default.secure_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.secure_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.secure_redirects = 0

Rationale: | Accepting "secure" ICMP redirects (from those gateways listed as default gateways) has few legitimate uses. It should be disabled unless it is absolutely required.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_secure_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.default.secure_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.default.secure_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.default.secure_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_default_secure_redirects_value='0'

    #
    # Set runtime for net.ipv4.conf.default.secure_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.secure_redirects="$sysctl_net_ipv4_conf_default_secure_redirects_value"
    fi

    #
    # If net.ipv4.conf.default.secure_redirects present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.default.secure_redirects = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.default.secure_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_default_secure_redirects_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 "^net.ipv4.conf.default.secure_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.secure_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_secure_redirects
    - name: XCCDF Value sysctl_net_ipv4_conf_default_secure_redirects_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_default_secure_redirects_value: !!str 0
      tags:
        - always

    - name: Configure Kernel Parameter for Accepting Secure Redirects By Default - Set
        fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_secure_redirects

    - name: Configure Kernel Parameter for Accepting Secure Redirects By Default - Find
        all files that contain net.ipv4.conf.default.secure_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.secure_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_secure_redirects

    - name: Configure Kernel Parameter for Accepting Secure Redirects By Default - Find
        all files that set net.ipv4.conf.default.secure_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.secure_redirects\s*=\s*{{ sysctl_net_ipv4_conf_default_secure_redirects_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_secure_redirects

    - name: Configure Kernel Parameter for Accepting Secure Redirects By Default - Comment
        out any occurrences of net.ipv4.conf.default.secure_redirects from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.secure_redirects
        replace: '#net.ipv4.conf.default.secure_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_secure_redirects

    - name: Configure Kernel Parameter for Accepting Secure Redirects By Default - Ensure
        sysctl net.ipv4.conf.default.secure_redirects is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.secure_redirects
        value: '{{ sysctl_net_ipv4_conf_default_secure_redirects_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_secure_redirects

#### Rule Configure Sending and Accepting Shared Media Redirects by Default [ref]

To set the runtime status of the `net.ipv4.conf.default.shared_media` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.shared_media=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.shared_media = 0

Rationale: | This setting should be aligned with `net.ipv4.conf.default.secure_redirects` because it overrides it. If `shared_media` is enabled for an interface `secure_redirects` will be enabled too.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_shared_media

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.default.shared_media from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.default.shared_media.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.default.shared_media" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_conf_default_shared_media_value='0'

    #
    # Set runtime for net.ipv4.conf.default.shared_media
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.shared_media="$sysctl_net_ipv4_conf_default_shared_media_value"
    fi

    #
    # If net.ipv4.conf.default.shared_media present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.conf.default.shared_media = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.default.shared_media")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_conf_default_shared_media_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 "^net.ipv4.conf.default.shared_media\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.shared_media\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_shared_media
    - name: XCCDF Value sysctl_net_ipv4_conf_default_shared_media_value # promote to variable
      set_fact:
        sysctl_net_ipv4_conf_default_shared_media_value: !!str 0
      tags:
        - always

    - name: Configure Sending and Accepting Shared Media Redirects by Default - Set fact
        for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects by Default - Find all
        files that contain net.ipv4.conf.default.shared_media
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.shared_media\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects by Default - Find all
        files that set net.ipv4.conf.default.shared_media to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.shared_media\s*=\s*{{ sysctl_net_ipv4_conf_default_shared_media_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects by Default - Comment
        out any occurrences of net.ipv4.conf.default.shared_media from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.shared_media
        replace: '#net.ipv4.conf.default.shared_media'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_shared_media

    - name: Configure Sending and Accepting Shared Media Redirects by Default - Ensure
        sysctl net.ipv4.conf.default.shared_media is set
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.shared_media
        value: '{{ sysctl_net_ipv4_conf_default_shared_media_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_shared_media

#### Rule Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.icmp_ignore_bogus_error_responses` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.icmp_ignore_bogus_error_responses=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.icmp_ignore_bogus_error_responses = 1

Rationale: | Ignoring bogus ICMP error responses reduces log size, although some activity would not be logged.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_icmp_ignore_bogus_error_responses

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 7, 8, 9
cobit5 | APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS05.02, DSS05.05, DSS05.07, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.9.1.2
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5
nist-csf | DE.CM-1, PR.DS-4, PR.IP-1, PR.PT-3
pcidss | Req-1.4.3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.2, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.icmp_ignore_bogus_error_responses from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.icmp_ignore_bogus_error_responses.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.icmp_ignore_bogus_error_responses" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_icmp_ignore_bogus_error_responses_value='1'

    #
    # Set runtime for net.ipv4.icmp_ignore_bogus_error_responses
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.icmp_ignore_bogus_error_responses="$sysctl_net_ipv4_icmp_ignore_bogus_error_responses_value"
    fi

    #
    # If net.ipv4.icmp_ignore_bogus_error_responses present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.icmp_ignore_bogus_error_responses = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.icmp_ignore_bogus_error_responses")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_icmp_ignore_bogus_error_responses_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 "^net.ipv4.icmp_ignore_bogus_error_responses\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.icmp_ignore_bogus_error_responses\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_icmp_ignore_bogus_error_responses
      - unknown_severity
    - name: XCCDF Value sysctl_net_ipv4_icmp_ignore_bogus_error_responses_value # promote to variable
      set_fact:
        sysctl_net_ipv4_icmp_ignore_bogus_error_responses_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_icmp_ignore_bogus_error_responses
      - unknown_severity

    - name: Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces
        - Find all files that contain net.ipv4.icmp_ignore_bogus_error_responses
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.icmp_ignore_bogus_error_responses\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_icmp_ignore_bogus_error_responses
      - unknown_severity

    - name: Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces
        - Find all files that set net.ipv4.icmp_ignore_bogus_error_responses to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.icmp_ignore_bogus_error_responses\s*=\s*{{ sysctl_net_ipv4_icmp_ignore_bogus_error_responses_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_icmp_ignore_bogus_error_responses
      - unknown_severity

    - name: Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.icmp_ignore_bogus_error_responses from
        config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.icmp_ignore_bogus_error_responses
        replace: '#net.ipv4.icmp_ignore_bogus_error_responses'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_icmp_ignore_bogus_error_responses
      - unknown_severity

    - name: Enable Kernel Parameter to Ignore Bogus ICMP Error Responses on IPv4 Interfaces
        - Ensure sysctl net.ipv4.icmp_ignore_bogus_error_responses is set
      ansible.posix.sysctl:
        name: net.ipv4.icmp_ignore_bogus_error_responses
        value: '{{ sysctl_net_ipv4_icmp_ignore_bogus_error_responses_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - PCI-DSS-Req-1.4.3
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.2
      - disable_strategy
      - low_complexity
      - medium_disruption
      - reboot_required
      - sysctl_net_ipv4_icmp_ignore_bogus_error_responses
      - unknown_severity

#### Rule Set Kernel Parameter to Increase Local Port Range [ref]

To set the runtime status of the `net.ipv4.ip_local_port_range` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.ip_local_port_range=32768 65535

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.ip_local_port_range = 32768 65535

Rationale: | This setting defines the local port range that is used by TCP and UDP to choose the local port. The first number is the first, the second the last local port number.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_ip_local_port_range

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.ip_local_port_range from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.ip_local_port_range.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.ip_local_port_range" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.ip_local_port_range
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.ip_local_port_range="32768 65535"
    fi

    #
    # If net.ipv4.ip_local_port_range present in /etc/sysctl.conf, change value to "32768 65535"
    #	else, add "net.ipv4.ip_local_port_range = 32768 65535" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.ip_local_port_range")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "32768 65535"

    # 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 "^net.ipv4.ip_local_port_range\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.ip_local_port_range\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_local_port_range

    - name: Set Kernel Parameter to Increase Local Port Range - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_local_port_range

    - name: Set Kernel Parameter to Increase Local Port Range - Find all files that contain
        net.ipv4.ip_local_port_range
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.ip_local_port_range\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_local_port_range

    - name: Set Kernel Parameter to Increase Local Port Range - Find all files that set
        net.ipv4.ip_local_port_range to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.ip_local_port_range\s*=\s*32768 65535$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_local_port_range

    - name: Set Kernel Parameter to Increase Local Port Range - Comment out any occurrences
        of net.ipv4.ip_local_port_range from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.ip_local_port_range
        replace: '#net.ipv4.ip_local_port_range'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_local_port_range

    - name: Set Kernel Parameter to Increase Local Port Range - Ensure sysctl net.ipv4.ip_local_port_range
        is set to 32768 65535
      ansible.posix.sysctl:
        name: net.ipv4.ip_local_port_range
        value: 32768 65535
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_local_port_range

#### Rule Enable Kernel Parameter to Use TCP RFC 1337 on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.tcp_rfc1337` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.tcp_rfc1337=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.tcp_rfc1337 = 1

Rationale: | Enable TCP behavior conformant with RFC 1337. When disabled, if a RST is received in TIME_WAIT state, we close the socket immediately without waiting for the end of the TIME_WAIT period.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_tcp_rfc1337

References:

anssi | R12

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.tcp_rfc1337 from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.tcp_rfc1337.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.tcp_rfc1337" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_tcp_rfc1337_value='1'

    #
    # Set runtime for net.ipv4.tcp_rfc1337
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.tcp_rfc1337="$sysctl_net_ipv4_tcp_rfc1337_value"
    fi

    #
    # If net.ipv4.tcp_rfc1337 present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.tcp_rfc1337 = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.tcp_rfc1337")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_tcp_rfc1337_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 "^net.ipv4.tcp_rfc1337\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.tcp_rfc1337\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_rfc1337
    - name: XCCDF Value sysctl_net_ipv4_tcp_rfc1337_value # promote to variable
      set_fact:
        sysctl_net_ipv4_tcp_rfc1337_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Use TCP RFC 1337 on IPv4 Interfaces - Set fact
        for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_rfc1337

    - name: Enable Kernel Parameter to Use TCP RFC 1337 on IPv4 Interfaces - Find all
        files that contain net.ipv4.tcp_rfc1337
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.tcp_rfc1337\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_rfc1337

    - name: Enable Kernel Parameter to Use TCP RFC 1337 on IPv4 Interfaces - Find all
        files that set net.ipv4.tcp_rfc1337 to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.tcp_rfc1337\s*=\s*{{ sysctl_net_ipv4_tcp_rfc1337_value }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_rfc1337

    - name: Enable Kernel Parameter to Use TCP RFC 1337 on IPv4 Interfaces - Comment out
        any occurrences of net.ipv4.tcp_rfc1337 from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.tcp_rfc1337
        replace: '#net.ipv4.tcp_rfc1337'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_rfc1337

    - name: Enable Kernel Parameter to Use TCP RFC 1337 on IPv4 Interfaces - Ensure sysctl
        net.ipv4.tcp_rfc1337 is set
      ansible.posix.sysctl:
        name: net.ipv4.tcp_rfc1337
        value: '{{ sysctl_net_ipv4_tcp_rfc1337_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_rfc1337

#### Rule Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces [ref]

To set the runtime status of the `net.ipv4.tcp_syncookies` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.tcp_syncookies=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.tcp_syncookies = 1

Rationale:

A TCP SYN flood attack can cause a denial of service by filling a system's TCP connection table with connections in the SYN_RCVD state. Syncookies can be used to track a connection when a subsequent ACK is received, verifying the initiator is attempting a valid connection and is not a flood source. This feature is activated when a flood condition is detected, and enables the system to continue servicing valid connection requests.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_tcp_syncookies

References:

cis-csc | 1, 12, 13, 14, 15, 16, 18, 2, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.4.3.3
isa-62443-2013 | SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-7(a), CM-7(b), SC-5(1), SC-5(2), SC-5(3)(a), CM-6(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.PT-4
pcidss | Req-1.4.1
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000420-GPOS-00186, SRG-OS-000142-GPOS-00071
anssi | R12
pcidss4 | 1.4.3, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.tcp_syncookies from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.tcp_syncookies.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.tcp_syncookies" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_net_ipv4_tcp_syncookies_value='1'

    #
    # Set runtime for net.ipv4.tcp_syncookies
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.tcp_syncookies="$sysctl_net_ipv4_tcp_syncookies_value"
    fi

    #
    # If net.ipv4.tcp_syncookies present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "net.ipv4.tcp_syncookies = value" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.tcp_syncookies")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_net_ipv4_tcp_syncookies_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 "^net.ipv4.tcp_syncookies\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.tcp_syncookies\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(1)
      - NIST-800-53-SC-5(2)
      - NIST-800-53-SC-5(3)(a)
      - PCI-DSS-Req-1.4.1
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_syncookies
    - name: XCCDF Value sysctl_net_ipv4_tcp_syncookies_value # promote to variable
      set_fact:
        sysctl_net_ipv4_tcp_syncookies_value: !!str 1
      tags:
        - always

    - name: Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces - Set
        fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(1)
      - NIST-800-53-SC-5(2)
      - NIST-800-53-SC-5(3)(a)
      - PCI-DSS-Req-1.4.1
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_syncookies

    - name: Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces - Find
        all files that contain net.ipv4.tcp_syncookies
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.tcp_syncookies\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(1)
      - NIST-800-53-SC-5(2)
      - NIST-800-53-SC-5(3)(a)
      - PCI-DSS-Req-1.4.1
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_syncookies

    - name: Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces - Find
        all files that set net.ipv4.tcp_syncookies to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.tcp_syncookies\s*=\s*{{ sysctl_net_ipv4_tcp_syncookies_value
          }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(1)
      - NIST-800-53-SC-5(2)
      - NIST-800-53-SC-5(3)(a)
      - PCI-DSS-Req-1.4.1
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_syncookies

    - name: Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces - Comment
        out any occurrences of net.ipv4.tcp_syncookies from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.tcp_syncookies
        replace: '#net.ipv4.tcp_syncookies'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(1)
      - NIST-800-53-SC-5(2)
      - NIST-800-53-SC-5(3)(a)
      - PCI-DSS-Req-1.4.1
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_syncookies

    - name: Enable Kernel Parameter to Use TCP Syncookies on Network Interfaces - Ensure
        sysctl net.ipv4.tcp_syncookies is set
      ansible.posix.sysctl:
        name: net.ipv4.tcp_syncookies
        value: '{{ sysctl_net_ipv4_tcp_syncookies_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5(1)
      - NIST-800-53-SC-5(2)
      - NIST-800-53-SC-5(3)(a)
      - PCI-DSS-Req-1.4.1
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_tcp_syncookies

Group Network Parameters for Hosts Only Group contains 3 rules
[ref] If the system is not going to be used as a router, then setting certain kernel parameters ensure that the host will not perform routing of network traffic.

#### Rule Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.conf.all.send_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.all.send_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.all.send_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages contain information from the system's route table possibly revealing portions of the network topology. The ability to send ICMP redirects is only appropriate for systems acting as routers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_all_send_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.5, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.all.send_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.all.send_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.all.send_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.conf.all.send_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.all.send_redirects="0"
    fi

    #
    # If net.ipv4.conf.all.send_redirects present in /etc/sysctl.conf, change value to "0"
    #	else, add "net.ipv4.conf.all.send_redirects = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.all.send_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^net.ipv4.conf.all.send_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.all.send_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        - Find all files that contain net.ipv4.conf.all.send_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.send_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        - Find all files that set net.ipv4.conf.all.send_redirects to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.all.send_redirects\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        - Comment out any occurrences of net.ipv4.conf.all.send_redirects from config
        files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.all.send_redirects
        replace: '#net.ipv4.conf.all.send_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        - Ensure sysctl net.ipv4.conf.all.send_redirects is set to 0
      ansible.posix.sysctl:
        name: net.ipv4.conf.all.send_redirects
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_all_send_redirects

#### Rule Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces by Default [ref]

To set the runtime status of the `net.ipv4.conf.default.send_redirects` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.conf.default.send_redirects=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.conf.default.send_redirects = 0

Rationale: | ICMP redirect messages are used by routers to inform hosts that a more direct route exists for a particular destination. These messages contain information from the system's route table possibly revealing portions of the network topology. The ability to send ICMP redirects is only appropriate for systems acting as routers.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_conf_default_send_redirects

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 2, 3, 4, 6, 7, 8, 9
cjis | 5.10.1.1
cobit5 | APO01.06, APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS01.05, DSS03.01, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.2.3.4, 4.3.3.4, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3, 4.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.1, A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.2, A.13.1.3, A.13.2.1, A.13.2.2, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, CM-6(a), SC-7(a)
nist-csf | DE.AE-1, DE.CM-1, ID.AM-3, PR.AC-5, PR.DS-4, PR.DS-5, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.5, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.conf.default.send_redirects from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.conf.default.send_redirects.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.conf.default.send_redirects" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.conf.default.send_redirects
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.conf.default.send_redirects="0"
    fi

    #
    # If net.ipv4.conf.default.send_redirects present in /etc/sysctl.conf, change value to "0"
    #	else, add "net.ipv4.conf.default.send_redirects = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.conf.default.send_redirects")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^net.ipv4.conf.default.send_redirects\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.conf.default.send_redirects\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        by Default - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        by Default - Find all files that contain net.ipv4.conf.default.send_redirects
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.send_redirects\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        by Default - Find all files that set net.ipv4.conf.default.send_redirects to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.conf.default.send_redirects\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        by Default - Comment out any occurrences of net.ipv4.conf.default.send_redirects
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.conf.default.send_redirects
        replace: '#net.ipv4.conf.default.send_redirects'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_send_redirects

    - name: Disable Kernel Parameter for Sending ICMP Redirects on all IPv4 Interfaces
        by Default - Ensure sysctl net.ipv4.conf.default.send_redirects is set to 0
      ansible.posix.sysctl:
        name: net.ipv4.conf.default.send_redirects
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.10.1.1
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.5
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_conf_default_send_redirects

#### Rule Disable Kernel Parameter for IP Forwarding on IPv4 Interfaces [ref]

To set the runtime status of the `net.ipv4.ip_forward` kernel parameter, run the following command:

    $ sudo sysctl -w net.ipv4.ip_forward=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.ipv4.ip_forward = 0

Warning: Certain technologies such as virtual machines, containers, etc. rely on IPv4 forwarding to enable and use networking. Disabling IPv4 forwarding would cause those technologies to stop working. Therefore, this rule should not be used in profiles or benchmarks that target usage of IPv4 forwarding.

Rationale: | Routing protocol daemons are typically used on routers to exchange network topology information with other routers. If this capability is used when not required, system network information may be unnecessarily transmitted across the network.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_ipv4_ip_forward

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 2, 3, 7, 8, 9
cobit5 | APO13.01, BAI04.04, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.03, DSS03.05, DSS05.02, DSS05.05, DSS05.07, DSS06.06
cui | 3.1.20
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.2, SR 7.1, SR 7.2, SR 7.6
iso27001-2013 | A.12.1.2, A.12.1.3, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.17.2.1, A.9.1.2
nerc-cip | CIP-007-3 R4, CIP-007-3 R4.1, CIP-007-3 R4.2, CIP-007-3 R5.1
nist | CM-7(a), CM-7(b), SC-5, CM-6(a), SC-7(a)
nist-csf | DE.CM-1, PR.DS-4, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-1.3.1, Req-1.3.2
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
pcidss4 | 1.4.3, 1.4

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.ipv4.ip_forward from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.ipv4.ip_forward.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.ipv4.ip_forward" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.ipv4.ip_forward
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.ipv4.ip_forward="0"
    fi

    #
    # If net.ipv4.ip_forward present in /etc/sysctl.conf, change value to "0"
    #	else, add "net.ipv4.ip_forward = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^net.ipv4.ip_forward")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^net.ipv4.ip_forward\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.ipv4.ip_forward\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.3.1
      - PCI-DSS-Req-1.3.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_forward

    - name: Disable Kernel Parameter for IP Forwarding on IPv4 Interfaces - Set fact for
        sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.3.1
      - PCI-DSS-Req-1.3.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_forward

    - name: Disable Kernel Parameter for IP Forwarding on IPv4 Interfaces - Find all files
        that contain net.ipv4.ip_forward
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.ip_forward\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.3.1
      - PCI-DSS-Req-1.3.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_forward

    - name: Disable Kernel Parameter for IP Forwarding on IPv4 Interfaces - Find all files
        that set net.ipv4.ip_forward to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.ipv4.ip_forward\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.3.1
      - PCI-DSS-Req-1.3.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_forward

    - name: Disable Kernel Parameter for IP Forwarding on IPv4 Interfaces - Comment out
        any occurrences of net.ipv4.ip_forward from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.ipv4.ip_forward
        replace: '#net.ipv4.ip_forward'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.3.1
      - PCI-DSS-Req-1.3.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_forward

    - name: Disable Kernel Parameter for IP Forwarding on IPv4 Interfaces - Ensure sysctl
        net.ipv4.ip_forward is set to 0
      ansible.posix.sysctl:
        name: net.ipv4.ip_forward
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.20
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-SC-5
      - NIST-800-53-SC-7(a)
      - PCI-DSS-Req-1.3.1
      - PCI-DSS-Req-1.3.2
      - PCI-DSSv4-1.4
      - PCI-DSSv4-1.4.3
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_ipv4_ip_forward

Group nftables Group contains 3 rules

[ref] `If firewalld or iptables are being used in your environment, please follow the guidance in their respective section and pass-over the guidance in this section.`
nftables is a subsystem of the Linux kernel providing filtering and classification of network packets/datagrams/frames and is the successor to iptables. The biggest change with the successor nftables is its simplicity. With iptables, we have to configure every single rule and use the syntax which can be compared with normal commands. With nftables, the simpler syntax, much like BPF (Berkely Packet Filter) means shorter lines and less repetition. Support for nftables should also be compiled into the kernel, together with the related nftables modules.
It is available in Linux kernels >= 3.13. Please ensure that your kernel supports nftables before choosing this option.

#### Rule Verify Group Who Owns /etc/nftables Directory [ref]

To properly set the group owner of `/etc/nftables`, run the command:

    $ sudo chgrp root /etc/nftables

Rationale: | The ownership of the /etc/nftables directory by the root group is important because this directory hosts nftables configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the nftables configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_groupowner_etc_nftables

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'nftables' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /etc/nftables/ -maxdepth 0 -type d  ! -group root -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_groupowner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"nftables" in ansible_facts.packages'
      - directory_groupowner_etc_nftables_newgroup is undefined
      tags:
      - configure_strategy
      - directory_groupowner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_etc_nftables_newgroup variable if root found
      ansible.builtin.set_fact:
        directory_groupowner_etc_nftables_newgroup: root
      when:
      - '"nftables" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - directory_groupowner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/nftables/
      ansible.builtin.file:
        path: /etc/nftables/
        follow: false
        state: directory
        group: '{{ directory_groupowner_etc_nftables_newgroup }}'
      when: '"nftables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_groupowner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/nftables Directory [ref]

To properly set the owner of `/etc/nftables`, run the command:

    $ sudo chown root /etc/nftables

Rationale: | The ownership of the /etc/nftables directory by the root user is important because this directory hosts nftables configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the nftables configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_owner_etc_nftables

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'nftables' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/nftables/ -maxdepth 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_owner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_etc_nftables_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_etc_nftables_newown: '0'
      when: '"nftables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/nftables/
      ansible.builtin.file:
        path: /etc/nftables/
        follow: false
        state: directory
        owner: '{{ directory_owner_etc_nftables_newown }}'
      when: '"nftables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/nftables Directory [ref]

To properly set the permissions of `/etc/nftables`, run the command:

    $ sudo chmod 0700 /etc/nftables

Rationale: | Setting correct permissions on the /etc/nftables directory is important because this directory hosts nftables configuration. Protection of this directory is critical for system security. Restricting the permissions ensures exclusive control of the nftables configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_etc_nftables

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'nftables' 2>/dev/null | grep -q '^installed$'; then

    find -H /etc/nftables/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt -type d -exec chmod u-s,g-xwrs,o-xwrt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_permissions_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/nftables/ file(s)
      ansible.builtin.command: 'find -P /etc/nftables/ -maxdepth 0 -perm /u+s,g+xwrs,o+xwrt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"nftables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/nftables/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-xwrs,o-xwrt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"nftables" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_nftables
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group File Permissions and Masks Group contains 9 groups and 71 rules

[ref] Traditional Unix security relies heavily on file and directory permissions to prevent unauthorized users from reading or modifying files to which they should not have access.
Several of the commands in this section search filesystems for files or directories with certain characteristics, and are intended to be run on every local partition on a given system. When the variable PART appears in one of the commands below, it means that the command is intended to be run repeatedly, with the name of each local partition substituted for PART in turn.
The following command prints a list of all xfs partitions on the local system, which is the default filesystem for Debian 13 installations:

    $ mount -t xfs | awk '{print $3}'

For any systems that use a different local filesystem type, modify this command as appropriate.

Group Verify Permissions on Important Files and Directories Group contains 2 groups and 38 rules
[ref] Permissions for many files on a system must be set restrictively to ensure sensitive information is properly protected. This section discusses important permission restrictions which can be verified to ensure that no harmful discrepancies have arisen.
Group Verify Permissions on Files with Local Account Information and Credentials Group contains 15 rules
[ref] The default restrictive permissions for files which act as important security databases such as `passwd`, `shadow`, `group`, and `gshadow` files must be maintained. Many utilities need read access to the `passwd` file in order to function properly, but read access to the `shadow` file allows malicious attacks against system passwords, and should never be enabled.

#### Rule Verify Group Who Owns group File [ref]

To properly set the group owner of `/etc/group`, run the command:

    $ sudo chgrp root /etc/group

Rationale: | The `/etc/group` file contains information regarding groups that are configured on the system. Protection of this file is important for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_group

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/group" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/group
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_groupowner_etc_group_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_group_newgroup: '0'
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/group
      ansible.builtin.stat:
        path: /etc/group
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/group
      ansible.builtin.file:
        path: /etc/group
        follow: false
        group: '{{ file_groupowner_etc_group_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns gshadow File [ref]

To properly set the group owner of `/etc/gshadow`, run the command:

    $ sudo chgrp shadow /etc/gshadow

Rationale: | The `/etc/gshadow` file contains group password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_gshadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newgroup=""
    if getent group "42" >/dev/null 2>&1; then
      newgroup="42"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "42 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/gshadow" | grep -E -w -q "42"; then
        chgrp --no-dereference "$newgroup" /etc/gshadow
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_groupowner_etc_gshadow_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_gshadow_newgroup: '42'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/gshadow
      ansible.builtin.stat:
        path: /etc/gshadow
      register: file_exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/gshadow
      ansible.builtin.file:
        path: /etc/gshadow
        follow: false
        group: '{{ file_groupowner_etc_gshadow_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns passwd File [ref]

To properly set the group owner of `/etc/passwd`, run the command:

    $ sudo chgrp root /etc/passwd

Rationale: | The `/etc/passwd` file contains information about the users that are configured on the system. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_passwd

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/passwd" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/passwd
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_groupowner_etc_passwd_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_passwd_newgroup: '0'
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/passwd
      ansible.builtin.stat:
        path: /etc/passwd
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/passwd
      ansible.builtin.file:
        path: /etc/passwd
        follow: false
        group: '{{ file_groupowner_etc_passwd_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns shadow File [ref]

To properly set the group owner of `/etc/shadow`, run the command:

    $ sudo chgrp shadow /etc/shadow

Rationale: | The `/etc/shadow` file stores password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_shadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newgroup=""
    if getent group "42" >/dev/null 2>&1; then
      newgroup="42"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "42 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/shadow" | grep -E -w -q "42"; then
        chgrp --no-dereference "$newgroup" /etc/shadow
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_groupowner_etc_shadow_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_shadow_newgroup: '42'
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/shadow
      ansible.builtin.stat:
        path: /etc/shadow
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/shadow
      ansible.builtin.file:
        path: /etc/shadow
        follow: false
        group: '{{ file_groupowner_etc_shadow_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_groupowner_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/shells File [ref]

To properly set the group owner of `/etc/shells`, run the command:

    $ sudo chgrp root /etc/shells

Rationale: | The `/etc/shells` file contains the list of full pathnames to shells on the system. Since this file is used by many system programs this file should be protected.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_shells

References:

nist | AC-3, MP-2
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/shells" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/shells
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_groupowner_etc_shells_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_etc_shells_newgroup: '0'
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_groupowner_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/shells
      ansible.builtin.stat:
        path: /etc/shells
      register: file_exists
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_groupowner_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/shells
      ansible.builtin.file:
        path: /etc/shells
        follow: false
        group: '{{ file_groupowner_etc_shells_newgroup }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_groupowner_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns group File [ref]

To properly set the owner of `/etc/group`, run the command:

    $ sudo chown root /etc/group

Rationale: | The `/etc/group` file contains information regarding groups that are configured on the system. Protection of this file is important for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_group

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/group" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/group
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_owner_etc_group_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_group_newown: '0'
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/group
      ansible.builtin.stat:
        path: /etc/group
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/group
      ansible.builtin.file:
        path: /etc/group
        follow: false
        owner: '{{ file_owner_etc_group_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns gshadow File [ref]

To properly set the owner of `/etc/gshadow`, run the command:

    $ sudo chown root /etc/gshadow

Rationale: | The `/etc/gshadow` file contains group password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_gshadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/gshadow" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/gshadow
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_owner_etc_gshadow_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_gshadow_newown: '0'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/gshadow
      ansible.builtin.stat:
        path: /etc/gshadow
      register: file_exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/gshadow
      ansible.builtin.file:
        path: /etc/gshadow
        follow: false
        owner: '{{ file_owner_etc_gshadow_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns passwd File [ref]

To properly set the owner of `/etc/passwd`, run the command:

    $ sudo chown root /etc/passwd

Rationale: | The `/etc/passwd` file contains information about the users that are configured on the system. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_passwd

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/passwd" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/passwd
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_owner_etc_passwd_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_passwd_newown: '0'
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/passwd
      ansible.builtin.stat:
        path: /etc/passwd
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/passwd
      ansible.builtin.file:
        path: /etc/passwd
        follow: false
        owner: '{{ file_owner_etc_passwd_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns shadow File [ref]

To properly set the owner of `/etc/shadow`, run the command:

    $ sudo chown root /etc/shadow

Rationale: | The `/etc/shadow` file contains the list of local system accounts and stores password hashes. Protection of this file is critical for system security. Failure to give ownership of this file to root provides the designated owner with access to sensitive information which could weaken the system security posture.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_shadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/shadow" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/shadow
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_owner_etc_shadow_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_shadow_newown: '0'
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/shadow
      ansible.builtin.stat:
        path: /etc/shadow
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/shadow
      ansible.builtin.file:
        path: /etc/shadow
        follow: false
        owner: '{{ file_owner_etc_shadow_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_owner_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Who Owns /etc/shells File [ref]

To properly set the owner of `/etc/shells`, run the command:

    $ sudo chown root /etc/shells

Rationale: | The `/etc/shells` file contains the list of full pathnames to shells on the system. Since this file is used by many system programs this file should be protected.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_shells

References:

nist | AC-3, MP-2
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/shells" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/shells
    fi

    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Set the file_owner_etc_shells_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_shells_newown: '0'
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_owner_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/shells
      ansible.builtin.stat:
        path: /etc/shells
      register: file_exists
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_owner_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/shells
      ansible.builtin.file:
        path: /etc/shells
        follow: false
        owner: '{{ file_owner_etc_shells_newown }}'
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_owner_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on group File [ref]

To properly set the permissions of `/etc/group`, run the command:

    $ sudo chmod 0644 /etc/group

Rationale: | The `/etc/group` file contains information regarding groups that are configured on the system. Protection of this file is important for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_group

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    chmod u-xs,g-xws,o-xwt /etc/group

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Test for existence /etc/group
      ansible.builtin.stat:
        path: /etc/group
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/group
      ansible.builtin.file:
        path: /etc/group
        mode: u-xs,g-xws,o-xwt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on gshadow File [ref]

To properly set the permissions of `/etc/gshadow`, run the command:

    $ sudo chmod 0640 /etc/gshadow

Rationale: | The `/etc/gshadow` file contains group password hashes. Protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_gshadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    chmod u-xs,g-xws,o-xwrt /etc/gshadow

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Test for existence /etc/gshadow
      ansible.builtin.stat:
        path: /etc/gshadow
      register: file_exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/gshadow
      ansible.builtin.file:
        path: /etc/gshadow
        mode: u-xs,g-xws,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_permissions_etc_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on passwd File [ref]

To properly set the permissions of `/etc/passwd`, run the command:

    $ sudo chmod 0644 /etc/passwd

Rationale: | If the `/etc/passwd` file is writable by a group-owner or the world the risk of its compromise is increased. The file contains the list of accounts on the system and associated information, and protection of this file is critical for system security.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_passwd

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    chmod u-xs,g-xws,o-xwt /etc/passwd

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Test for existence /etc/passwd
      ansible.builtin.stat:
        path: /etc/passwd
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/passwd
      ansible.builtin.file:
        path: /etc/passwd
        mode: u-xs,g-xws,o-xwt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on shadow File [ref]

To properly set the permissions of `/etc/shadow`, run the command:

    $ sudo chmod 0640 /etc/shadow

Rationale: | The `/etc/shadow` file contains the list of local system accounts and stores password hashes. Protection of this file is critical for system security. Failure to give ownership of this file to root provides the designated owner with access to sensitive information which could weaken the system security posture.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_shadow

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.2.2
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-8.7.c
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    chmod u-xs,g-xws,o-xwrt /etc/shadow

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Test for existence /etc/shadow
      ansible.builtin.stat:
        path: /etc/shadow
      register: file_exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/shadow
      ansible.builtin.file:
        path: /etc/shadow
        mode: u-xs,g-xws,o-xwrt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - CJIS-5.5.2.2
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-8.7.c
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_etc_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on /etc/shells File [ref]

To properly set the permissions of `/etc/shells`, run the command:

    $ sudo chmod 0644 /etc/shells

Rationale: | The `/etc/shells` file contains the list of full pathnames to shells on the system. Since this file is used by many system programs this file should be protected.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_shells

References:

nist | AC-3, MP-2
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    chmod u-xs,g-xws,o-xwt /etc/shells

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Test for existence /etc/shells
      ansible.builtin.stat:
        path: /etc/shells
      register: file_exists
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_permissions_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/shells
      ansible.builtin.file:
        path: /etc/shells
        mode: u-xs,g-xws,o-xwt
      when: file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-3
      - NIST-800-53-MP-2
      - configure_strategy
      - file_permissions_etc_shells
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Verify File Permissions Within Some Important Directories Group contains 6 rules
[ref] Some directories contain files whose confidentiality or integrity is notably important and may also be susceptible to misconfiguration over time, particularly if unpackaged software is installed. As such, an argument exists to verify that files' permissions within these directories remain configured correctly and restrictively.

#### Rule Verify Group Who Owns /etc/sysctl.d Directory [ref]

To properly set the group owner of `/etc/sysctl.d`, run the command:

    $ sudo chgrp root /etc/sysctl.d

Rationale: | The ownership of the /etc/sysctl.d directory by the root group is important because this directory hosts kernel configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the kernel configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_groupowner_etc_sysctld

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /etc/sysctl.d/ -maxdepth 0 -type d  ! -group root -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_groupowner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - directory_groupowner_etc_sysctld_newgroup is undefined
      tags:
      - configure_strategy
      - directory_groupowner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_etc_sysctld_newgroup variable if root found
      ansible.builtin.set_fact:
        directory_groupowner_etc_sysctld_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - directory_groupowner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/sysctl.d/
      ansible.builtin.file:
        path: /etc/sysctl.d/
        follow: false
        state: directory
        group: '{{ directory_groupowner_etc_sysctld_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_groupowner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/sysctl.d Directory [ref]

To properly set the owner of `/etc/sysctl.d`, run the command:

    $ sudo chown root /etc/sysctl.d

Rationale: | The ownership of the /etc/sysctl.d directory by the root user is important because this directory hosts kernel configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the kernel configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_owner_etc_sysctld

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/sysctl.d/ -maxdepth 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_owner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_etc_sysctld_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_etc_sysctld_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/sysctl.d/
      ansible.builtin.file:
        path: /etc/sysctl.d/
        follow: false
        state: directory
        owner: '{{ directory_owner_etc_sysctld_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/sysctl.d Directory [ref]

To properly set the permissions of `/etc/sysctl.d`, run the command:

    $ sudo chmod 0755 /etc/sysctl.d

Rationale: | Setting correct permissions on the /etc/sysctl.d directory is important because this directory hosts kernel configuration. Protection of this directory is critical for system security. Restricting the permissions ensures exclusive control of the kernel configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_etc_sysctld

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    find -H /etc/sysctl.d/ -maxdepth 0 -perm /u+s,g+ws,o+wt -type d -exec chmod u-s,g-ws,o-wt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_permissions_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/sysctl.d/ file(s)
      ansible.builtin.command: 'find -P /etc/sysctl.d/ -maxdepth 0 -perm /u+s,g+ws,o+wt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/sysctl.d/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-ws,o-wt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_sysctld
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify that system commands files are group owned by root or a system account [ref]

System commands files are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/sbin
    /usr/local/bin
    /usr/local/sbin

All files in these directories should be owned by the `root` group, or a system account. If the directory, or any file in these directories, is found to be owned by a group other than root or a a system account correct its ownership with the following command:

    $ sudo chgrp root FILE

Rationale:

If the operating system allows any user to make changes to software libraries, then those changes might be implemented without undergoing the appropriate testing and approvals that are part of a robust change management process. This requirement applies to operating systems with software libraries that are accessible and configurable, as in the case of interpreted languages. Software libraries also include privileged programs which execute with escalated privileges. Only qualified and authorized individuals must be allowed to obtain access to information system components for purposes of initiating changes, including upgrades and modifications.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownership_system_commands_dirs

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50

#### Rule Verify that System Executables Have Root Ownership [ref]

System executables are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/libexec
    /usr/local/bin
    /usr/local/sbin
    /usr/sbin

All files in these directories should be owned by the `root` user. If any file FILE in these directories is found to be owned by a user other than root, correct its ownership with the following command:

    $ sudo chown root FILE

Rationale: | System binaries are executed by privileged users as well as system services, and restrictive permissions are necessary to ensure that their execution of these programs cannot be co-opted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_binary_dirs

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-5(6), CM-5(6).1, CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50
ism | 1409

#### Rule Verify that System Executables Have Restrictive Permissions [ref]

System executables are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/libexec
    /usr/local/bin
    /usr/local/sbin
    /usr/sbin

All files in these directories should not be group-writable or world-writable. If any file FILE in these directories is found to be group-writable or world-writable, correct its permission with the following command:

    $ sudo chmod go-w FILE

Rationale: | System binaries are executed by privileged users, as well as system services, and restrictive permissions are necessary to ensure execution of these programs cannot be co-opted.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_binary_dirs

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-5(6), CM-5(6).1, CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50
ism | 1409

#### Rule Ensure All World-Writable Directories Are Owned by root User [ref]

All directories in local partitions which are world-writable should be owned by root. If any world-writable directories are not owned by root, this should be investigated. Following this, the files should be deleted or assigned to root user.
Rationale: | Allowing a user account to own a world-writable directory is undesirable because it allows the owner of that directory to remove or replace any files that may be placed in the directory by other users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_perms_world_writable_root_owned

References:

os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000138-GPOS-00069
anssi | R54

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | restrict

    # At least under containerized env /proc can have files w/o possilibity to
    # modify even as root. And touching /proc is not good idea anyways.
    find / -path /proc -prune -o \
        -not -fstype afs -not -fstype autofs -not -fstype ceph -not -fstype cifs -not -fstype smb3 \
        -not -fstype smbfs -not -fstype sshfs -not -fstype ncpfs -not -fstype ncp -not -fstype nfs \
        -not -fstype nfs4 -not -fstype gfs -not -fstype gfs2 -not -fstype glusterfs -not -fstype gpfs \
        -not -fstype pvfs2 -not -fstype ocfs2 -not -fstype lustre -not -fstype davfs \
        -not -fstype fuse.sshfs -type d -perm -0002 -uid +0 -exec chown root {} \;

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | restrict

    - name: Ensure All World-Writable Directories Are Owned by root User - Define Excluded
        (Non-Local) File Systems and Paths
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - 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
        search_paths: []
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - 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
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Include Relevant
        Root Directories in a List of Paths to be Searched
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.path]) }}'
      loop: '{{ result_relevant_root_dirs.files }}'
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Increment Search
        Paths List with Local Partitions Mount Points
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.mount]) }}'
      loop: '{{ ansible_mounts }}'
      when:
      - item.fstype not in excluded_fstypes
      - item.mount != '/'
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Increment Search
        Paths List with Local NFS File System Targets
      ansible.builtin.set_fact:
        search_paths: '{{ search_paths | union([item.device.split('':'')[1]]) }}'
      loop: '{{ ansible_mounts }}'
      when: item.device is search("localhost:")
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Define Rule
        Specific Facts
      ansible.builtin.set_fact:
        world_writable_dirs: []
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Find All Uncompliant
        Directories in Local File Systems
      ansible.builtin.command:
        cmd: find {{ item }} -xdev -type d -perm -0002 -uid +0
      loop: '{{ search_paths }}'
      changed_when: false
      register: result_found_dirs
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Create List
        of World Writable Directories Not Owned by root
      ansible.builtin.set_fact:
        world_writable_dirs: '{{ world_writable_dirs | union(item.stdout_lines) | list
          }}'
      loop: '{{ result_found_dirs.results }}'
      when: item is not skipped
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure All World-Writable Directories Are Owned by root User - Ensure root
        Ownership on Local World Writable Directories
      ansible.builtin.file:
        path: '{{ item }}'
        owner: root
      loop: '{{ world_writable_dirs }}'
      tags:
      - dir_perms_world_writable_root_owned
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify that All World-Writable Directories Have Sticky Bits Set [ref]

When the so-called 'sticky bit' is set on a directory, only the owner of a given file may remove that file from the directory. Without the sticky bit, any user with write access to a directory may remove any file in the directory. Setting the sticky bit prevents users from removing each other's files. In cases where there is no reason for a directory to be world-writable, a better solution is to remove that permission rather than to set the sticky bit. However, if a directory is used by a particular application, consult that application's documentation instead of blindly changing modes.
To set the sticky bit on a world-writable directory DIR, run the following command:

    $ sudo chmod +t DIR

Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of directories present on the system. It is not a problem in most cases, but especially systems with a large number of directories can be affected. See `https://access.redhat.com/articles/6999111`.
Warning: Please note that there might be cases where the rule remediation cannot fix directory permissions. This can happen for example when running on a system with some immutable parts. These immutable parts cannot be remediated because they are read-only. Example of such directories can be OStree deployments located at `/sysroot/ostree/deploy`. In such case, it is needed to make modifications to the underlying ostree snapshot and this is out of scope of regular rule remediation.

Rationale:

Failing to set the sticky bit on public directories allows unauthorized users to delete files in the directory structure.
The only authorized public directories are those temporary directories supplied with the system, or those designed to be temporary file repositories. The setting is normally reserved for directories used by the system, by users for temporary file storage (such as `/tmp`), and for directories requiring global read/write access.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_perms_world_writable_sticky_bits

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000138-GPOS-00069
anssi | R54
ism | 1409
pcidss4 | 2.2.6, 2.2

#### Rule Verify that system commands directories have root as a group owner [ref]

System commands are stored in the following directories: by default:

    /bin
    /sbin
    /usr/bin
    /usr/sbin
    /usr/local/bin
    /usr/local/sbin

All these directories should have `root` user as a group owner. If any system command directory is not group owned by a user other than root correct its ownership with the following command:

    $ sudo chgrp root DIR

Rationale:

If the operating system were to allow any user to make changes to software libraries, then those changes might be implemented without undergoing the appropriate testing and approvals that are part of a robust change management process. This requirement applies to operating systems with software libraries that are accessible and configurable, as in the case of interpreted languages. Software libraries also include privileged programs which execute with escalated privileges. Only qualified and authorized individuals must be allowed to obtain access to information system components for purposes of initiating changes, including upgrades and modifications.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_system_commands_group_root_owned

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50

Remediation Shell script ⇲

    for SYSCMDDIRS in /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin
    do
         find -L $SYSCMDDIRS ! -group root -type d -exec chgrp root '{}' \;
    done

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | medium
Reboot: | false
Strategy: | restrict

    - name: Verify that system commands directories have root as a group owner - Set group
        ownership of directories that contain system commands to root
      ansible.builtin.file:
        path: '{{ item }}'
        group: root
        recurse: 'yes'
        state: directory
        follow: 'yes'
      with_items:
      - /bin
      - /sbin
      - /usr/bin
      - /usr/sbin
      - /usr/local/bin
      - /usr/local/sbin
      tags:
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - dir_system_commands_group_root_owned
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify that system commands directories have root ownership [ref]

System commands are stored in the following directories by default:

    /bin
    /sbin
    /usr/bin
    /usr/sbin
    /usr/local/bin
    /usr/local/sbin

All these directories should be owned by the `root` user. If any system command directory is not owned by a user other than root correct its ownership with the following command:

    $ sudo chown root DIR

Rationale:

If the operating system were to allow any user to make changes to software libraries, then those changes might be implemented without undergoing the appropriate testing and approvals that are part of a robust change management process. This requirement applies to operating systems with software libraries that are accessible and configurable, as in the case of interpreted languages. Software libraries also include privileged programs which execute with escalated privileges. Only qualified and authorized individuals must be allowed to obtain access to information system components for purposes of initiating changes, including upgrades and modifications.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_dir_system_commands_root_owned

References:

nist | CM-5(6), CM-5(6).1
os-srg | SRG-OS-000259-GPOS-00100
anssi | R50

Remediation Shell script ⇲

    for SYSCMDDIRS in /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin
    do
       find -L $SYSCMDDIRS \! -user root -type d -exec chown root {} \;
    done

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | medium
Reboot: | false
Strategy: | restrict

    - name: Verify that system commands directories have root ownership - Set ownership
        of directories that contain system commands to root
      ansible.builtin.file:
        path: '{{ item }}'
        owner: root
        recurse: 'yes'
        state: directory
        follow: 'yes'
      with_items:
      - /bin
      - /sbin
      - /usr/bin
      - /usr/sbin
      - /usr/local/bin
      - /usr/local/sbin
      tags:
      - NIST-800-53-CM-5(6)
      - NIST-800-53-CM-5(6).1
      - dir_system_commands_root_owned
      - medium_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Verify Group Who Owns /etc/crypttab File [ref]

To properly set the group owner of `/etc/crypttab`, run the command:

    $ sudo chgrp root /etc/crypttab

Rationale: | The ownership of the /etc/crypttab file by the root group is important because this file hosts encrypted block devices configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the encrypted block devices configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_crypttab

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/crypttab" | grep -E -w -q "root"; then
        chgrp --no-dereference "$newgroup" /etc/crypttab
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_groupowner_etc_crypttab_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_etc_crypttab_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_etc_crypttab_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/crypttab
      ansible.builtin.stat:
        path: /etc/crypttab
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/crypttab
      ansible.builtin.file:
        path: /etc/crypttab
        follow: false
        group: '{{ file_groupowner_etc_crypttab_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns System.map Files [ref]

The System.map files are symbol map files generated during the compilation of the Linux kernel. They contain the mapping between kernel symbols and their corresponding memory addresses. These files must be group-owned by root. To properly set the group owner of `/boot/System.map*`, run the command:

    $ sudo chgrp root /boot/System.map*

Rationale: | The purpose of `System.map` files is primarily for debugging and profiling the kernel. Unrestricted access to these files might disclose information useful to attackers and malicious software leading to more sophisticated exploitation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_systemmap

References:

anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /boot/ -maxdepth 1 -type f  ! -group root -regextype posix-extended -regex '^.*System\.map.*$' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_groupowner_systemmap_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Set the file_groupowner_systemmap_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_systemmap_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Find /boot/ file(s) matching ^.*System\.map.*$
      ansible.builtin.command: find -P /boot/ -maxdepth 1 -type f  ! -group root -regextype
        posix-extended -regex "^.*System\.map.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Ensure group owner on /boot/ file(s) matching ^.*System\.map.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupowner_systemmap_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/crypttab File [ref]

To properly set the owner of `/etc/crypttab`, run the command:

    $ sudo chown root /etc/crypttab

Rationale: | The ownership of the /etc/crypttab file by the root user is important because this file hosts encrypted block devices configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the encrypted block devices configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_crypttab

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/crypttab" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/crypttab
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_etc_crypttab_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_crypttab_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/crypttab
      ansible.builtin.stat:
        path: /etc/crypttab
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/crypttab
      ansible.builtin.file:
        path: /etc/crypttab
        follow: false
        owner: '{{ file_owner_etc_crypttab_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns System.map Files [ref]

The System.map files are symbol map files generated during the compilation of the Linux kernel. They contain the mapping between kernel symbols and their corresponding memory addresses. These files must be owned by root. To properly set the owner of `/boot/System.map*`, run the command:

    $ sudo chown root /boot/System.map*

Rationale: | The purpose of `System.map` files is primarily for debugging and profiling the kernel. Unrestricted access to these files might disclose information useful to attackers and malicious software leading to more sophisticated exploitation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_systemmap

References:

anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else

    find -P /boot/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*System\.map.*$' -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Set the file_owner_systemmap_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_systemmap_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Find /boot/ file(s) matching ^.*System\.map.*$
      ansible.builtin.command: find -P /boot/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex "^.*System\.map.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Ensure owner on /boot/ file(s) matching ^.*System\.map.*$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_owner_systemmap_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/crypttab File [ref]

To properly set the permissions of `/etc/crypttab`, run the command:

    $ sudo chmod 0600 /etc/crypttab

Rationale: | Setting correct permissions on the /etc/crypttab file is important because this file hosts encrypted block devices configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the encrypted block devices configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_crypttab

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xs,g-xwrs,o-xwrt /etc/crypttab

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/crypttab
      ansible.builtin.stat:
        path: /etc/crypttab
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /etc/crypttab
      ansible.builtin.file:
        path: /etc/crypttab
        mode: u-xs,g-xwrs,o-xwrt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_crypttab
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on System.map Files [ref]

The System.map files are symbol map files generated during the compilation of the Linux kernel. They contain the mapping between kernel symbols and their corresponding memory addresses. In general, there is no need for non-root users to read these files. To properly set the permissions of `/boot/System.map*`, run the command:

    $ sudo chmod 0600 /boot/System.map*

Rationale: | The purpose of `System.map` files is primarily for debugging and profiling the kernel. Unrestricted access to these files might disclose information useful to attackers and malicious software leading to more sophisticated exploitation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_systemmap

References:

anssi | R29

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    find -P /boot/ -maxdepth 1 -perm /u+xs,g+xwrs,o+xwrt  -type f -regextype posix-extended -regex '^.*System\.map.*$' -exec chmod u-xs,g-xwrs,o-xwrt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Find /boot/ file(s)
      ansible.builtin.command: find -P /boot/ -maxdepth 1 -perm /u+xs,g+xwrs,o+xwrt  -type
        f -regextype posix-extended -regex "^.*System\.map.*$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

    - name: Set permissions for /boot/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xwrs,o-xwrt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_systemmap
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed

#### Rule Ensure No World-Writable Files Exist [ref]

It is generally a good idea to remove global (other) write access to a file when it is discovered. However, check with documentation for specific applications before making changes. Also, monitor for recurring world-writable files, as these may be symptoms of a misconfigured application or user account. Finally, this applies to real files and not virtual files that are a part of pseudo file systems such as `sysfs` or `procfs`.
Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of files present on the system. It is not a problem in most cases, but especially systems with a large number of files can be affected. See `https://access.redhat.com/articles/6999111`.

Rationale: | Data in world-writable files can be modified by any user on the system. In almost all circumstances, files can be configured using a combination of user and group permissions to support whatever legitimate access is needed without the risk caused by world-writable files.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_unauthorized_world_writable

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
anssi | R54
ism | 1409
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    FILTER_NODEV=$(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,)

    # Do not consider /sysroot partition because it contains only the physical
    # read-only root on bootable containers.
    PARTITIONS=$(findmnt -n -l -k -it $FILTER_NODEV | awk '{ print $1 }' | grep -v "/sysroot")

    for PARTITION in $PARTITIONS; do
      find "${PARTITION}" -xdev -type f -perm -002 -exec chmod o-w {} \; 2>/dev/null
    done

    # Ensure /tmp is also fixed when tmpfs is used.
    if grep "^tmpfs /tmp" /proc/mounts; then
      find /tmp -xdev -type f -perm -002 -exec chmod o-w {} \; 2>/dev/null
    fi

#### Rule Ensure All Files Are Owned by a Group [ref]

If any file is not group-owned by a valid defined group, the cause of the lack of group-ownership must be investigated. Following this, those files should be deleted or assigned to an appropriate group. The groups need to be defined in `/etc/group` or in `/usr/lib/group` if `nss-altfiles` are configured to be used in `/etc/nsswitch.conf`. Locate the mount points related to local devices by the following command:

    $ findmnt -n -l -k -it $(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,)

For all mount points listed by the previous command, it is necessary to search for files which do not belong to a valid group using the following command:

    $ sudo find MOUNTPOINT -xdev -nogroup 2>/dev/null

Warning: This rule only considers local groups as valid groups. If you have your groups defined outside `/etc/group` or `/usr/lib/group`, the rule won't consider those.
Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of files present on the system. It is not a problem in most cases, but especially systems with a large number of files can be affected. See `https://access.redhat.com/articles/6999111`.

Rationale:

Unowned files do not directly imply a security problem, but they are generally a sign that something is amiss. They may be caused by an intruder, by incorrect software installation or draft software removal, or by failure to remove all files belonging to a deleted account, or other similar cases. The files should be repaired so they will not cause problems when accounts are created in the future, and the cause should be discovered and addressed.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_ungroupowned

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.02, DSS06.03, DSS06.06, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.18.1.4, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.DS-5, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R53
pcidss4 | 2.2.6, 2.2

#### Rule Ensure All Files Are Owned by a User [ref]

If any files are not owned by a user, then the cause of their lack of ownership should be investigated. Following this, the files should be deleted or assigned to an appropriate user. Locate the mount points related to local devices by the following command:

    $ findmnt -n -l -k -it $(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,)

For all mount points listed by the previous command, it is necessary to search for files which do not belong to a valid user using the following command:

    $ sudo find MOUNTPOINT -xdev -nouser 2>/dev/null

Warning: For this rule to evaluate centralized user accounts, `getent` must be working properly so that running the command

    getent passwd

returns a list of all users in your organization. If using the System Security Services Daemon (SSSD),

    enumerate = true

must be configured in your organization's domain to return a complete list of users
Warning: This rule can take a long time to perform the check and might consume a considerable amount of resources depending on the number of files present on the system. It is not a problem in most cases, but especially systems with a large number of files can be affected. See `https://access.redhat.com/articles/6999111`.

Rationale:

Unowned files do not directly imply a security problem, but they are generally a sign that something is amiss. They may be caused by an intruder, by incorrect software installation or draft software removal, or by failure to remove all files belonging to a deleted account, or other similar cases. The files should be repaired so they will not cause problems when accounts are created in the future, and the cause should be discovered and addressed.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_no_files_unowned_by_user

References:

cis-csc | 11, 12, 13, 14, 15, 16, 18, 3, 5, 9
cobit5 | APO01.06, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS06.02, DSS06.03, DSS06.06
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 5.2, SR 7.6
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.1, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.AC-6, PR.DS-5, PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227
anssi | R53
pcidss4 | 2.2.6, 2.2

#### Rule Enable Kernel Parameter to Enforce DAC on FIFOs [ref]

To set the runtime status of the `fs.protected_fifos` kernel parameter, run the following command:

    $ sudo sysctl -w fs.protected_fifos=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.protected_fifos = 2

Rationale: | This parameter is available since Linux Kernel 4.19 and allows to prohibit opening FIFOs that are not owned by the user in world and group writeable sticky directories. It avoids unintentional writes to an attacker-controlled FIFO where a program expects to create the regular file.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_fs_protected_fifos

References:

nist | CM-6(a), AC-6(1)
anssi | R14

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of fs.protected_fifos from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*fs.protected_fifos.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "fs.protected_fifos" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.protected_fifos
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w fs.protected_fifos="2"
    fi

    #
    # If fs.protected_fifos present in /etc/sysctl.conf, change value to "2"
    #	else, add "fs.protected_fifos = 2" to /etc/sysctl.conf
    #

    # 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' <<< "^fs.protected_fifos")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "2"

    # 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 "^fs.protected_fifos\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.protected_fifos\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_fifos

    - name: Enable Kernel Parameter to Enforce DAC on FIFOs - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_fifos

    - name: Enable Kernel Parameter to Enforce DAC on FIFOs - Find all files that contain
        fs.protected_fifos
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_fifos\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_fifos

    - name: Enable Kernel Parameter to Enforce DAC on FIFOs - Find all files that set
        fs.protected_fifos to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_fifos\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_fifos

    - name: Enable Kernel Parameter to Enforce DAC on FIFOs - Comment out any occurrences
        of fs.protected_fifos from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.protected_fifos
        replace: '#fs.protected_fifos'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_fifos

    - name: Enable Kernel Parameter to Enforce DAC on FIFOs - Ensure sysctl fs.protected_fifos
        is set to 2
      ansible.posix.sysctl:
        name: fs.protected_fifos
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_fifos

#### Rule Enable Kernel Parameter to Enforce DAC on Hardlinks [ref]

To set the runtime status of the `fs.protected_hardlinks` kernel parameter, run the following command:

    $ sudo sysctl -w fs.protected_hardlinks=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.protected_hardlinks = 1

Rationale: | By enabling this kernel parameter, users can no longer create soft or hard links to files which they do not own. Disallowing such hardlinks mitigate vulnerabilities based on insecure file system accessed by privileged programs, avoiding an exploitation vector exploiting unsafe use of `open()` or `creat()`.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_fs_protected_hardlinks

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
os-srg | SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000324-GPOS-00125
anssi | R14

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of fs.protected_hardlinks from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*fs.protected_hardlinks.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "fs.protected_hardlinks" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.protected_hardlinks
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w fs.protected_hardlinks="1"
    fi

    #
    # If fs.protected_hardlinks present in /etc/sysctl.conf, change value to "1"
    #	else, add "fs.protected_hardlinks = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^fs.protected_hardlinks")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^fs.protected_hardlinks\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.protected_hardlinks\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Find all files that
        contain fs.protected_hardlinks
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_hardlinks\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Find all files that
        set fs.protected_hardlinks to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_hardlinks\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Comment out any occurrences
        of fs.protected_hardlinks from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.protected_hardlinks
        replace: '#fs.protected_hardlinks'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

    - name: Enable Kernel Parameter to Enforce DAC on Hardlinks - Ensure sysctl fs.protected_hardlinks
        is set to 1
      ansible.posix.sysctl:
        name: fs.protected_hardlinks
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_hardlinks

#### Rule Enable Kernel Parameter to Enforce DAC on Regular files [ref]

To set the runtime status of the `fs.protected_regular` kernel parameter, run the following command:

    $ sudo sysctl -w fs.protected_regular=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.protected_regular = 2

Rationale: | This parameter is available since Linux Kernel 4.19 and allows to prohibit opening "regular" files that are not owned by the user in world and group writeable sticky directories. It avoids writes to an attacker-controlled regular file, for example, when a program expects to create the regular file.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_fs_protected_regular

References:

nist | CM-6(a), AC-6(1)
anssi | R14

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of fs.protected_regular from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*fs.protected_regular.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "fs.protected_regular" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.protected_regular
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w fs.protected_regular="2"
    fi

    #
    # If fs.protected_regular present in /etc/sysctl.conf, change value to "2"
    #	else, add "fs.protected_regular = 2" to /etc/sysctl.conf
    #

    # 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' <<< "^fs.protected_regular")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "2"

    # 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 "^fs.protected_regular\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.protected_regular\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_regular

    - name: Enable Kernel Parameter to Enforce DAC on Regular files - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_regular

    - name: Enable Kernel Parameter to Enforce DAC on Regular files - Find all files that
        contain fs.protected_regular
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_regular\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_regular

    - name: Enable Kernel Parameter to Enforce DAC on Regular files - Find all files that
        set fs.protected_regular to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_regular\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_regular

    - name: Enable Kernel Parameter to Enforce DAC on Regular files - Comment out any
        occurrences of fs.protected_regular from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.protected_regular
        replace: '#fs.protected_regular'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_regular

    - name: Enable Kernel Parameter to Enforce DAC on Regular files - Ensure sysctl fs.protected_regular
        is set to 2
      ansible.posix.sysctl:
        name: fs.protected_regular
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_regular

#### Rule Enable Kernel Parameter to Enforce DAC on Symlinks [ref]

To set the runtime status of the `fs.protected_symlinks` kernel parameter, run the following command:

    $ sudo sysctl -w fs.protected_symlinks=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.protected_symlinks = 1

Rationale:

By enabling this kernel parameter, symbolic links are permitted to be followed only when outside a sticky world-writable directory, or when the UID of the link and follower match, or when the directory owner matches the symlink's owner. Disallowing such symlinks helps mitigate vulnerabilities based on insecure file system accessed by privileged programs, avoiding an exploitation vector exploiting unsafe use of `open()` or `creat()`.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_fs_protected_symlinks

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-6(a), AC-6(1)
os-srg | SRG-OS-000312-GPOS-00122, SRG-OS-000312-GPOS-00123, SRG-OS-000324-GPOS-00125
anssi | R14

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of fs.protected_symlinks from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*fs.protected_symlinks.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "fs.protected_symlinks" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.protected_symlinks
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w fs.protected_symlinks="1"
    fi

    #
    # If fs.protected_symlinks present in /etc/sysctl.conf, change value to "1"
    #	else, add "fs.protected_symlinks = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^fs.protected_symlinks")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^fs.protected_symlinks\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.protected_symlinks\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Find all files that contain
        fs.protected_symlinks
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_symlinks\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Find all files that set
        fs.protected_symlinks to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.protected_symlinks\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Comment out any occurrences
        of fs.protected_symlinks from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.protected_symlinks
        replace: '#fs.protected_symlinks'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

    - name: Enable Kernel Parameter to Enforce DAC on Symlinks - Ensure sysctl fs.protected_symlinks
        is set to 1
      ansible.posix.sysctl:
        name: fs.protected_symlinks
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_protected_symlinks

Group Restrict Partition Mount Options Group contains 15 rules
[ref] System partitions can be mounted with certain options that limit what files on those partitions can do. These options are set in the `/etc/fstab` configuration file, and can be used to make certain types of malicious behavior more difficult.

#### Rule Add noexec Option to /boot [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/boot`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/boot`.
Rationale: | The `/boot` partition contains the kernel and the bootloader. No binaries should be executed from this partition after the booting process finishes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_boot_noexec

References:

anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    function perform_remediation {

            # the mount point /boot has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/boot")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/boot' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /boot in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /boot)"

        # 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|noexec)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /boot  defaults,${previous_mount_opts}noexec 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 "noexec"; 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,noexec|" /etc/fstab
        fi

        if mkdir -p "/boot"; then
            if mountpoint -q "/boot"; then
                mount -o remount --target "/boot"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /boot: Check information associated to mountpoint'
      command: findmnt --fstab '/boot'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when: ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /boot: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /boot: If /boot not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /boot
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /boot: Make sure noexec option is part of the to /boot
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined and "noexec" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /boot: Ensure /boot is mounted with noexec option'
      mount:
        path: /boot
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /boot [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/boot`. The SUID and SGID permissions should not be required on the boot partition. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/boot`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from boot partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_boot_nosuid

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00227
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    function perform_remediation {

            # the mount point /boot has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/boot")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/boot' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /boot in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /boot)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /boot  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/boot"; then
            if mountpoint -q "/boot"; then
                mount -o remount --target "/boot"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Check information associated to mountpoint'
      command: findmnt --fstab '/boot'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when: ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: If /boot not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /boot
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Make sure nosuid option is part of the to /boot
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /boot: Ensure /boot is mounted with nosuid option'
      mount:
        path: /boot
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_boot_nosuid
      - no_reboot_needed

#### Rule Add noexec Option to /home [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/home`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/home`.
Rationale: | The `/home` directory contains data of individual users. Binaries in this directory should not be considered as trusted and users should not be able to execute them.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_home_noexec

References:

nist | CM-6(b)
os-srg | SRG-OS-000480-GPOS-00227
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    function perform_remediation {

            # the mount point /home has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/home")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/home' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /home in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /home)"

        # 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|noexec)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /home  defaults,${previous_mount_opts}noexec 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 "noexec"; 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,noexec|" /etc/fstab
        fi

        if mkdir -p "/home"; then
            if mountpoint -q "/home"; then
                mount -o remount --target "/home"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Check information associated to mountpoint'
      command: findmnt --fstab '/home'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when: ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      tags:
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: If /home not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /home
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Make sure noexec option is part of the to /home
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined and "noexec" not in mount_info.options
      tags:
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /home: Ensure /home is mounted with noexec option'
      mount:
        path: /home
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-CM-6(b)
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /home [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/home`. The SUID and SGID permissions should not be required in these user data directories. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/home`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from user home directory partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_home_nosuid

References:

cis-csc | 11, 13, 14, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS05.06, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.11.2.9, A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.3, A.9.1.2
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00227
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/home" > /dev/null || findmnt --fstab "/home" > /dev/null; }; then

    function perform_remediation {

            # the mount point /home has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/home")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/home' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /home in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /home)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /home  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/home"; then
            if mountpoint -q "/home"; then
                mount -o remount --target "/home"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /home: Check information associated to mountpoint'
      command: findmnt --fstab '/home'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/home" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /home: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/home" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /home: If /home not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /home
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/home" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /home: Make sure nosuid option is part of the to /home
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/home" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /home: Ensure /home is mounted with nosuid option'
      mount:
        path: /home
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/home" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_home_nosuid
      - no_reboot_needed

#### Rule Add nodev Option to Non-Root Local Partitions [ref]

The `nodev` mount option prevents files from being interpreted as character or block devices. Legitimate character and block devices should exist only in the `/dev` directory on the root partition or within chroot jails built for system services. Add the `nodev` option to the fourth column of `/etc/fstab` for the line which controls mounting of any non-root local partitions.
Rationale: | The `nodev` mount option prevents files from being interpreted as character or block devices. The only legitimate location for device files is the `/dev` directory located on the root partition. The only exception to this is chroot jails, for which it is not advised to set `nodev` on these filesystems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_nodev_nonroot_local_partitions

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154, SRG-OS-000480-GPOS-00227
anssi | R28

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ); then

    MOUNT_OPTION="nodev"
    # Create array of local non-root partitions
    readarray -t partitions_records < <(findmnt --mtab --raw --evaluate | grep "^/\w" | grep -v "^/proc" | grep "\s/dev/\w")

    # Create array of polyinstantiated directories, in case one of them is found in mtab
    readarray -t polyinstantiated_dirs < \
        <(grep -oP "^\s*[^#\s]+\s+\S+" /etc/security/namespace.conf | grep -oP "(?<=\s)\S+?(?=/?\$)")

    # Define excluded non-local file systems
    excluded_fstypes=(
        afs
        autofs
        ceph
        cifs
        smb3
        smbfs
        sshfs
        ncpfs
        ncp
        nfs
        nfs4
        gfs
        gfs2
        glusterfs
        gpfs
        pvfs2
        ocfs2
        lustre
        davfs
        fuse.sshfs
    )

    for partition_record in "${partitions_records[@]}"; do
        # Get all important information for fstab
        mount_point="$(echo "${partition_record}" | cut -d " " -f1)"
        device="$(echo "${partition_record}" | cut -d " " -f2)"
        device_type="$(echo "${partition_record}" | cut -d " " -f3)"

        # Skip polyinstantiated directories
        if printf '%s\0' "${polyinstantiated_dirs[@]}" | grep -qxzF "$mount_point"; then
            continue
        fi

        # Skip any non-local filesystem
        for excluded_fstype in "${excluded_fstypes[@]}"; do
            if [[ "$device_type" == "$excluded_fstype" ]]; then
                # jump out of both loops and move to next partition_record
                continue 2
            fi
        done

        # If we reach here, it's a local, non-root partition that isn't excluded.
        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_OPTION)(,|$)//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="$device_type"
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo "$device $mount_point $device_type defaults,${previous_mount_opts}$MOUNT_OPTION 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_OPTION"; 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_OPTION|" /etc/fstab
        fi
        if mkdir -p "$mount_point"; then
            if mountpoint -q "$mount_point"; then
                mount -o remount --target "$mount_point"
            fi
        fi
    done

    # Remediate unmounted /etc/fstab entries
    sed -i -E '/nodev/! s;^\s*(/dev/\S+|UUID=\S+)\s+(/\w\S*)\s+(\S+)\s+(\S+)(.*)$;\1 \2 \3 \4,nodev \5;' /etc/fstab

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Refresh facts'
      ansible.builtin.setup:
        gather_subset: mounts
      when: ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Define excluded (non-local)
        file systems'
      ansible.builtin.set_fact:
        excluded_fstypes:
        - afs
        - autofs
        - ceph
        - cifs
        - smb3
        - smbfs
        - sshfs
        - ncpfs
        - ncp
        - nfs
        - nfs4
        - gfs
        - gfs2
        - glusterfs
        - gpfs
        - pvfs2
        - ocfs2
        - lustre
        - davfs
        - fuse.sshfs
      when: ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Ensure non-root local partitions
        are mounted with nodev option'
      ansible.posix.mount:
        path: '{{ item.mount }}'
        src: '{{ item.device }}'
        opts: '{{ item.options }},nodev'
        state: mounted
        fstype: '{{ item.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - item.mount is match('/\w')
      - item.options is not search('nodev')
      - item.fstype not in excluded_fstypes
      with_items:
      - '{{ ansible_facts.mounts }}'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

    - name: 'Add nodev Option to Non-Root Local Partitions: Ensure non-root local partitions
        are present with nodev option in /etc/fstab'
      ansible.builtin.replace:
        path: /etc/fstab
        regexp: ^\s*(?!#)(/dev/\S+|UUID=\S+)\s+(/\w\S*)\s+(\S+)\s+(?!.*\bnodev\b)(\S+)(.*)$
        replace: \1 \2 \3 \4,nodev \5
      when: ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_nodev_nonroot_local_partitions
      - no_reboot_needed

#### Rule Add nosuid Option to /opt [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/opt`. The SUID and SGID permissions should not be required in this directory. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/opt`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. The `/opt` directory contains additional software packages. Users should not be able to execute SUID or SGID binaries from this directory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_opt_nosuid

References:

anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/opt" > /dev/null || findmnt --fstab "/opt" > /dev/null; }; then

    function perform_remediation {

            # the mount point /opt has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/opt")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/opt' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /opt in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /opt)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /opt  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/opt"; then
            if mountpoint -q "/opt"; then
                mount -o remount --target "/opt"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_opt_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /opt: Check information associated to mountpoint'
      command: findmnt --fstab '/opt'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/opt" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_opt_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /opt: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/opt" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_opt_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /opt: If /opt not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /opt
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/opt" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_opt_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /opt: Make sure nosuid option is part of the to /opt
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/opt" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_opt_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /opt: Ensure /opt is mounted with nosuid option'
      mount:
        path: /opt
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/opt" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_opt_nosuid
      - no_reboot_needed

#### Rule Add nosuid Option to /srv [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/srv`. The SUID and SGID permissions should not be required in this directory. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/srv`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. The `/srv` directory contains files served by various network services such as FTP. Users should not be able to execute SUID or SGID binaries from this directory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_srv_nosuid

References:

anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/srv" > /dev/null || findmnt --fstab "/srv" > /dev/null; }; then

    function perform_remediation {

            # the mount point /srv has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/srv")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/srv' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /srv in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /srv)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /srv  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/srv"; then
            if mountpoint -q "/srv"; then
                mount -o remount --target "/srv"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_srv_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /srv: Check information associated to mountpoint'
      command: findmnt --fstab '/srv'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/srv" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_srv_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /srv: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/srv" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_srv_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /srv: If /srv not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /srv
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/srv" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_srv_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /srv: Make sure nosuid option is part of the to /srv
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/srv" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_srv_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /srv: Ensure /srv is mounted with nosuid option'
      mount:
        path: /srv
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/srv" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_srv_nosuid
      - no_reboot_needed

#### Rule Add noexec Option to /tmp [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/tmp`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/tmp`.
Rationale: | Allowing users to execute binaries from world-writable directories such as `/tmp` should never be necessary in normal operation and can expose the system to potential compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_tmp_noexec

References:

cis-csc | 11, 13, 14, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS05.06, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.11.2.9, A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.3, A.9.1.2
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154
anssi | R28

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/tmp" > /dev/null || findmnt --fstab "/tmp" > /dev/null; }; then

    unit=tmp.mount
    mount_option=noexec

    # check whether unit is in use
    unit_check=$(systemctl -q list-units $unit | grep active)

    if [ "x$unit_check" == "x" ]; then
        exit 0
    fi

    # check whether mount option is present
    current_options=$(systemctl show $unit -P Options)
    option_check=$(echo $current_options | grep $mount_option | wc -l)

    # add systemd drop in to add missing option
    if [ $option_check == "0" ]; then
        mkdir -p /etc/systemd/system/$unit.d
        cat > /etc/systemd/system/$unit.d/mount_options.conf <<EOF
    [Mount]
    Options=$current_options,$mount_option
    EOF

        # unit changed on disk. reload.
        systemctl daemon-reload

        # note: mount point is probably in use, so we cannot restart
        # the unit without getting an error, but we may be able to
        # remount the filesystem with the new option
        mount_point=$(systemctl show $unit -P Where)
        mount $mount_point -o remount,$mount_option
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /tmp: Check information associated to mountpoint'
      command: findmnt --fstab '/tmp'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /tmp: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /tmp: If /tmp not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /tmp
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /tmp: Make sure noexec option is part of the to /tmp
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "noexec" not in mount_info.options
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /tmp: Ensure /tmp is mounted with noexec option'
      mount:
        path: /tmp
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /tmp [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/tmp`. The SUID and SGID permissions should not be required in these world-writable directories. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/tmp`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from temporary storage partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_tmp_nosuid

References:

cis-csc | 11, 13, 14, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS05.06, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.11.2.9, A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.8.2.1, A.8.2.2, A.8.2.3, A.8.3.1, A.8.3.3, A.9.1.2
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/tmp" > /dev/null || findmnt --fstab "/tmp" > /dev/null; }; then

    function perform_remediation {

            # the mount point /tmp has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/tmp")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/tmp' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /tmp in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /tmp)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /tmp  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/tmp"; then
            if mountpoint -q "/tmp"; then
                mount -o remount --target "/tmp"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /tmp: Check information associated to mountpoint'
      command: findmnt --fstab '/tmp'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /tmp: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /tmp: If /tmp not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /tmp
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /tmp: Make sure nosuid option is part of the to /tmp
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /tmp: Ensure /tmp is mounted with nosuid option'
      mount:
        path: /tmp
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_tmp_nosuid
      - no_reboot_needed

#### Rule Add noexec Option to /var/log [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/var/log`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/log`.
Rationale: | Allowing users to execute binaries from directories containing log files such as `/var/log` should never be necessary in normal operation and can expose the system to potential compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_log_noexec

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/var/log" > /dev/null || findmnt --fstab "/var/log" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/log has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/var/log")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/log' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /var/log in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/log)"

        # 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|noexec)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /var/log  defaults,${previous_mount_opts}noexec 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 "noexec"; 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,noexec|" /etc/fstab
        fi

        if mkdir -p "/var/log"; then
            if mountpoint -q "/var/log"; then
                mount -o remount --target "/var/log"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log: Check information associated to mountpoint'
      command: findmnt --fstab '/var/log'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log: If /var/log not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /var/log
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log: Make sure noexec option is part of the to
        /var/log options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "noexec" not in mount_info.options
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/log: Ensure /var/log is mounted with noexec option'
      mount:
        path: /var/log
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /var/log [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/var/log`. The SUID and SGID permissions should not be required in directories containing log files. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/log`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from partitions designated for log files.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_log_nosuid

References:

nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | CM-7(a), CM-7(b), CM-6(a), AC-6, AC-6(1), MP-7
nist-csf | PR.IP-1, PR.PT-2, PR.PT-3
os-srg | SRG-OS-000368-GPOS-00154
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/var/log" > /dev/null || findmnt --fstab "/var/log" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/log has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/var/log")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/log' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /var/log in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/log)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /var/log  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/var/log"; then
            if mountpoint -q "/var/log"; then
                mount -o remount --target "/var/log"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log: Check information associated to mountpoint'
      command: findmnt --fstab '/var/log'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log: If /var/log not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /var/log
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log: Make sure nosuid option is part of the to
        /var/log options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/log: Ensure /var/log is mounted with nosuid option'
      mount:
        path: /var/log
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/log" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-MP-7
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_log_nosuid
      - no_reboot_needed

#### Rule Add noexec Option to /var [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/var`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var`.
Rationale: | The `/var` directory contains variable system data such as logs, mails and caches. No binaries should be executed from this directory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_noexec

References:

anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/var" > /dev/null || findmnt --fstab "/var" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/var")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /var in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var)"

        # 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|noexec)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /var  defaults,${previous_mount_opts}noexec 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 "noexec"; 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,noexec|" /etc/fstab
        fi

        if mkdir -p "/var"; then
            if mountpoint -q "/var"; then
                mount -o remount --target "/var"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var: Check information associated to mountpoint'
      command: findmnt --fstab '/var'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var: If /var not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /var
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var: Make sure noexec option is part of the to /var
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "noexec" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var: Ensure /var is mounted with noexec option'
      mount:
        path: /var
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /var [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/var`. The SUID and SGID permissions should not be required for this directory. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_nosuid

References:

anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/var" > /dev/null || findmnt --fstab "/var" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/var")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /var in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /var  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/var"; then
            if mountpoint -q "/var"; then
                mount -o remount --target "/var"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var: Check information associated to mountpoint'
      command: findmnt --fstab '/var'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var: If /var not mounted, craft mount_info manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /var
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var: Make sure nosuid option is part of the to /var
        options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var: Ensure /var is mounted with nosuid option'
      mount:
        path: /var
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_nosuid
      - no_reboot_needed

#### Rule Add noexec Option to /var/tmp [ref]

The `noexec` mount option can be used to prevent binaries from being executed out of `/var/tmp`. Add the `noexec` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/tmp`.
Rationale: | Allowing users to execute binaries from world-writable directories such as `/var/tmp` should never be necessary in normal operation and can expose the system to potential compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_tmp_noexec

References:

os-srg | SRG-OS-000368-GPOS-00154
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/var/tmp" > /dev/null || findmnt --fstab "/var/tmp" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/tmp has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/var/tmp")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/tmp' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /var/tmp in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/tmp)"

        # 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|noexec)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /var/tmp  defaults,${previous_mount_opts}noexec 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 "noexec"; 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,noexec|" /etc/fstab
        fi

        if mkdir -p "/var/tmp"; then
            if mountpoint -q "/var/tmp"; then
                mount -o remount --target "/var/tmp"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/tmp: Check information associated to mountpoint'
      command: findmnt --fstab '/var/tmp'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/tmp: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/tmp: If /var/tmp not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /var/tmp
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/tmp: Make sure noexec option is part of the to
        /var/tmp options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',noexec''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "noexec" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_noexec
      - no_reboot_needed

    - name: 'Add noexec Option to /var/tmp: Ensure /var/tmp is mounted with noexec option'
      mount:
        path: /var/tmp
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_noexec
      - no_reboot_needed

#### Rule Add nosuid Option to /var/tmp [ref]

The `nosuid` mount option can be used to prevent execution of setuid programs in `/var/tmp`. The SUID and SGID permissions should not be required in these world-writable directories. Add the `nosuid` option to the fourth column of `/etc/fstab` for the line which controls mounting of `/var/tmp`.
Rationale: | The presence of SUID and SGID executables should be tightly controlled. Users should not be able to execute SUID or SGID binaries from temporary storage partitions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_mount_option_var_tmp_nosuid

References:

os-srg | SRG-OS-000368-GPOS-00154
anssi | R28

Remediation Shell script ⇲

Reboot: | false

    # Remediation is applicable only in certain platforms
    if ( ! ( { rpm --quiet -q kernel ;} && { rpm --quiet -q rpm-ostree ;} && { rpm --quiet -q bootc ;} && { ! rpm --quiet -q openshift-kubelet ;} && ([ -f /run/ostree-booted ] || [ -L /ostree ]) ) && ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ) ) && { findmnt --kernel "/var/tmp" > /dev/null || findmnt --fstab "/var/tmp" > /dev/null; }; then

    function perform_remediation {

            # the mount point /var/tmp has to be defined in /etc/fstab
            # before this remediation can be executed. In case it is not defined, the
            # remediation aborts and no changes regarding the mount point are done.
            mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" "/var/tmp")"

        grep "$mount_point_match_regexp" -q /etc/fstab \
            || { echo "The mount point '/var/tmp' is not even in /etc/fstab, so we can't set up mount options" >&2;
                    echo "Not remediating, because there is no record of /var/tmp in /etc/fstab" >&2; return 1; }

        mount_point_match_regexp="$(printf "^[[:space:]]*[^#].*[[:space:]]%s[[:space:]]" /var/tmp)"

        # 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|nosuid)(,|$)//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=""
            if [  "$fs_type" == "iso9660" ] ; then
                previous_mount_opts=$(sed 's/blocksize=/block=/' <<< "$previous_mount_opts")
            fi
            echo " /var/tmp  defaults,${previous_mount_opts}nosuid 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 "nosuid"; 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,nosuid|" /etc/fstab
        fi

        if mkdir -p "/var/tmp"; then
            if mountpoint -q "/var/tmp"; then
                mount -o remount --target "/var/tmp"
            fi
        fi
    }

    perform_remediation

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | high
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/tmp: Check information associated to mountpoint'
      command: findmnt --fstab '/var/tmp'
      register: device_name
      failed_when: device_name.rc > 1
      changed_when: false
      check_mode: false
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/tmp: Create mount_info dictionary variable'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - '{{ device_name.stdout_lines[0].split() | list | lower }}'
      - '{{ device_name.stdout_lines[1].split() | list }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length > 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/tmp: If /var/tmp not mounted, craft mount_info
        manually'
      set_fact:
        mount_info: '{{ mount_info|default({})|combine({item.0: item.1}) }}'
      with_together:
      - - target
        - source
        - fstype
        - options
      - - /var/tmp
        - ''
        - ''
        - defaults
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - ("--fstab" | length == 0)
      - device_name.stdout is defined and device_name.stdout_lines is defined
      - (device_name.stdout | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/tmp: Make sure nosuid option is part of the to
        /var/tmp options'
      set_fact:
        mount_info: '{{ mount_info | combine( {''options'':''''~mount_info.options~'',nosuid''
          }) }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined and "nosuid" not in mount_info.options
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nosuid
      - no_reboot_needed

    - name: 'Add nosuid Option to /var/tmp: Ensure /var/tmp is mounted with nosuid option'
      mount:
        path: /var/tmp
        src: '{{ mount_info.source }}'
        opts: '{{ mount_info.options }}'
        state: mounted
        fstype: '{{ mount_info.fstype }}'
      when:
      - ( not ( "kernel" in ansible_facts.packages and "rpm-ostree" in ansible_facts.packages
        and "bootc" in ansible_facts.packages and not "openshift-kubelet" in ansible_facts.packages
        and "ostree" in ansible_proc_cmdline ) and not ( ansible_virtualization_type in
        ["docker", "lxc", "openvz", "podman", "container"] ) )
      - '"/var/tmp" in ansible_mounts | map(attribute="mount") | list'
      - mount_info is defined
      - (device_name.stdout is defined and (device_name.stdout | length > 0)) or ("--fstab"
        | length == 0)
      tags:
      - configure_strategy
      - high_disruption
      - low_complexity
      - medium_severity
      - mount_option_var_tmp_nosuid
      - no_reboot_needed

Group Restrict Programs from Dangerous Execution Patterns Group contains 4 groups and 18 rules
[ref] The recommendations in this section are designed to ensure that the system's features to protect against potentially dangerous program execution are activated. These protections are applied at the system initialization or kernel level, and defend against certain types of badly-configured or compromised programs.
Group Disable Core Dumps Group contains 1 rule

[ref] A core dump file is the memory image of an executable program when it was terminated by the operating system due to errant behavior. In most cases, only software developers legitimately need to access these files. The core dump files may also contain sensitive information, or unnecessarily occupy large amounts of disk space.
Once a hard limit is set in `/etc/security/limits.conf`, or to a file within the `/etc/security/limits.d/` directory, a user cannot increase that limit within his or her own session. If access to core dumps is required, consider restricting them to only certain users or groups. See the `limits.conf` man page for more information.
The core dumps of setuid programs are further protected. The `sysctl` variable `fs.suid_dumpable` controls whether the kernel allows core dumps from these programs at all. The default value of 0 is recommended.

#### Rule Disable Core Dumps for SUID programs [ref]

To set the runtime status of the `fs.suid_dumpable` kernel parameter, run the following command:

    $ sudo sysctl -w fs.suid_dumpable=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    fs.suid_dumpable = 0

Rationale: | The core dump of a setuid program is more likely to contain sensitive data, as the program itself runs with greater privileges than the user who initiated execution of the program. Disabling the ability for any setuid program to write a core file decreases the risk of unauthorized access of such data.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_fs_suid_dumpable

References:

hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3), 164.308(a)(4), 164.310(b), 164.310(c), 164.312(a), 164.312(e)
nist | SI-11(a), SI-11(b)
anssi | R14
pcidss4 | 3.3.1.1, 3.3.1, 3.3

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of fs.suid_dumpable from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*fs.suid_dumpable.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "fs.suid_dumpable" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for fs.suid_dumpable
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w fs.suid_dumpable="0"
    fi

    #
    # If fs.suid_dumpable present in /etc/sysctl.conf, change value to "0"
    #	else, add "fs.suid_dumpable = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^fs.suid_dumpable")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^fs.suid_dumpable\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^fs.suid_dumpable\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_suid_dumpable

    - name: Disable Core Dumps for SUID programs - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_suid_dumpable

    - name: Disable Core Dumps for SUID programs - Find all files that contain fs.suid_dumpable
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.suid_dumpable\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_suid_dumpable

    - name: Disable Core Dumps for SUID programs - Find all files that set fs.suid_dumpable
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*fs.suid_dumpable\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_suid_dumpable

    - name: Disable Core Dumps for SUID programs - Comment out any occurrences of fs.suid_dumpable
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*fs.suid_dumpable
        replace: '#fs.suid_dumpable'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_suid_dumpable

    - name: Disable Core Dumps for SUID programs - Ensure sysctl fs.suid_dumpable is set
        to 0
      ansible.posix.sysctl:
        name: fs.suid_dumpable
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_fs_suid_dumpable

Group Enable ExecShield Group contains 2 rules

[ref] ExecShield describes kernel features that provide protection against exploitation of memory corruption errors such as buffer overflows. These features include random placement of the stack and other memory regions, prevention of execution in memory that should only hold data, and special handling of text buffers. These protections are enabled by default on 32-bit systems and controlled through `sysctl` variables `kernel.exec-shield` and `kernel.randomize_va_space`. On the latest 64-bit systems, `kernel.exec-shield` cannot be enabled or disabled with `sysctl`.

#### Rule Restrict Exposed Kernel Pointer Addresses Access [ref]

To set the runtime status of the `kernel.kptr_restrict` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.kptr_restrict=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.kptr_restrict = 2

Rationale:

Exposing kernel pointers (through procfs or `seq_printf()`) exposes kernel writeable structures which may contain functions pointers. If a write vulnerability occurs in the kernel, allowing write access to any of this structure, the kernel can be compromised. This option disallow any program without the CAP_SYSLOG capability to get the addresses of kernel pointers by replacing them with 0.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_kptr_restrict

References:

nerc-cip | CIP-002-5 R1.1, CIP-002-5 R1.2, CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 4.1, CIP-004-6 4.2, CIP-004-6 R2.2.3, CIP-004-6 R2.2.4, CIP-004-6 R2.3, CIP-004-6 R4, CIP-005-6 R1, CIP-005-6 R1.1, CIP-005-6 R1.2, CIP-007-3 R3, CIP-007-3 R3.1, CIP-007-3 R5.1, CIP-007-3 R5.1.2, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3, CIP-007-3 R8.4, CIP-009-6 R.1.1, CIP-009-6 R4
nist | SC-30, SC-30(2), SC-30(5), CM-6(a)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000433-GPOS-00192, SRG-OS-000480-GPOS-00227
anssi | R9
ism | 1409

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.kptr_restrict from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.kptr_restrict.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.kptr_restrict" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    sysctl_kernel_kptr_restrict_value='2'

    #
    # Set runtime for kernel.kptr_restrict
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.kptr_restrict="$sysctl_kernel_kptr_restrict_value"
    fi

    #
    # If kernel.kptr_restrict present in /etc/sysctl.conf, change value to appropriate value
    #	else, add "kernel.kptr_restrict = value" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.kptr_restrict")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "$sysctl_kernel_kptr_restrict_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 "^kernel.kptr_restrict\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.kptr_restrict\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict
    - name: XCCDF Value sysctl_kernel_kptr_restrict_value # promote to variable
      set_fact:
        sysctl_kernel_kptr_restrict_value: !!str 2
      tags:
        - always

    - name: Restrict Exposed Kernel Pointer Addresses Access - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Find all files that contain
        kernel.kptr_restrict
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.kptr_restrict\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Find all files that set
        kernel.kptr_restrict to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.kptr_restrict\s*=\s*{{ sysctl_kernel_kptr_restrict_value }}$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Comment out any occurrences
        of kernel.kptr_restrict from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.kptr_restrict
        replace: '#kernel.kptr_restrict'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

    - name: Restrict Exposed Kernel Pointer Addresses Access - Ensure sysctl kernel.kptr_restrict
        is set
      ansible.posix.sysctl:
        name: kernel.kptr_restrict
        value: '{{ sysctl_kernel_kptr_restrict_value }}'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - NIST-800-53-SC-30(5)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_kptr_restrict

#### Rule Enable Randomized Layout of Virtual Address Space [ref]

To set the runtime status of the `kernel.randomize_va_space` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.randomize_va_space=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.randomize_va_space = 2

Rationale: | Address space layout randomization (ASLR) makes it more difficult for an attacker to predict the location of attack code they have introduced into a process's address space during an attempt at exploitation. Additionally, ASLR makes it more difficult for an attacker to know the location of existing code in order to re-purpose it using return oriented programming (ROP) techniques.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_randomize_va_space

References:

cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3), 164.308(a)(4), 164.310(b), 164.310(c), 164.312(a), 164.312(e)
nerc-cip | CIP-002-5 R1.1, CIP-002-5 R1.2, CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 4.1, CIP-004-6 4.2, CIP-004-6 R2.2.3, CIP-004-6 R2.2.4, CIP-004-6 R2.3, CIP-004-6 R4, CIP-005-6 R1, CIP-005-6 R1.1, CIP-005-6 R1.2, CIP-007-3 R3, CIP-007-3 R3.1, CIP-007-3 R5.1, CIP-007-3 R5.1.2, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3, CIP-007-3 R8.4, CIP-009-6 R.1.1, CIP-009-6 R4
nist | SC-30, SC-30(2), CM-6(a)
pcidss | Req-2.2.1
os-srg | SRG-OS-000433-GPOS-00193, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000450-CTR-001105
anssi | R9
ism | 1409
pcidss4 | 3.3.1.1, 3.3.1, 3.3

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.randomize_va_space from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.randomize_va_space.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.randomize_va_space" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.randomize_va_space
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.randomize_va_space="2"
    fi

    #
    # If kernel.randomize_va_space present in /etc/sysctl.conf, change value to "2"
    #	else, add "kernel.randomize_va_space = 2" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.randomize_va_space")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "2"

    # 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 "^kernel.randomize_va_space\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.randomize_va_space\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - PCI-DSS-Req-2.2.1
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_randomize_va_space

    - name: Enable Randomized Layout of Virtual Address Space - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - PCI-DSS-Req-2.2.1
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_randomize_va_space

    - name: Enable Randomized Layout of Virtual Address Space - Find all files that contain
        kernel.randomize_va_space
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.randomize_va_space\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - PCI-DSS-Req-2.2.1
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_randomize_va_space

    - name: Enable Randomized Layout of Virtual Address Space - Find all files that set
        kernel.randomize_va_space to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.randomize_va_space\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - PCI-DSS-Req-2.2.1
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_randomize_va_space

    - name: Enable Randomized Layout of Virtual Address Space - Comment out any occurrences
        of kernel.randomize_va_space from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.randomize_va_space
        replace: '#kernel.randomize_va_space'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - PCI-DSS-Req-2.2.1
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_randomize_va_space

    - name: Enable Randomized Layout of Virtual Address Space - Ensure sysctl kernel.randomize_va_space
        is set to 2
      ansible.posix.sysctl:
        name: kernel.randomize_va_space
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SC-30
      - NIST-800-53-SC-30(2)
      - PCI-DSS-Req-2.2.1
      - PCI-DSSv4-3.3
      - PCI-DSSv4-3.3.1
      - PCI-DSSv4-3.3.1.1
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_randomize_va_space

Group Enable Execute Disable (XD) or No Execute (NX) Support on x86 Systems Group contains 1 rule

[ref] Recent processors in the x86 family support the ability to prevent code execution on a per memory page basis. Generically and on AMD processors, this ability is called No Execute (NX), while on Intel processors it is called Execute Disable (XD). This ability can help prevent exploitation of buffer overflow vulnerabilities and should be activated whenever possible. Extra steps must be taken to ensure that this protection is enabled, particularly on 32-bit x86 systems. Other processors, such as Itanium and POWER, have included such support since inception and the standard kernel for those platforms supports the feature. This is enabled by default on the latest Oracle Linux, Red Hat and Fedora systems if supported by the hardware.

#### Rule Install PAE Kernel on Supported 32-bit x86 Systems [ref]

Systems that are using the 64-bit x86 kernel package do not need to install the kernel-PAE package because the 64-bit x86 kernel already includes this support. However, if the system is 32-bit and also supports the PAE and NX features as determined in the previous section, the kernel-PAE package should be installed to enable XD or NX support. The `kernel-PAE` package can be installed with the following command:

    $ apt-get install kernel-PAE

The installation process should also have configured the bootloader to load the new kernel at boot. Verify this after reboot and modify `/etc/default/grub` if necessary.
Warning: The kernel-PAE package should not be installed on older systems that do not support the XD or NX bit, as 8this may prevent them from booting.8

Rationale: | On 32-bit systems that support the XD or NX bit, the vendor-supplied PAE kernel is required to enable either Execute Disable (XD) or No Execute (NX) support.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_install_PAE_kernel_on_x86-32

References:

cis-csc | 11, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05
cui | 3.1.7
isa-62443-2009 | 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4
nist | CM-6(a)
nist-csf | PR.IP-1
anssi | R1
pcidss4 | 2.2.1, 2.2

Group Memory Poisoning Group contains 2 rules
[ref] Memory Poisoning consists of writing a special value to uninitialized or freed memory. Poisoning can be used as a mechanism to prevent leak of information and detection of corrupted memory.

#### Rule Enable page allocator poisoning [ref]

To enable poisoning of free pages, add the argument `page_poison=1` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain page_poison=1 as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) page_poison=1"

Rationale: | Poisoning writes an arbitrary value to freed pages, so any modification or reference to that page after being freed or before being initialized will be detected and prevented. This prevents many types of use-after-free vulnerabilities at little performance cost. Also prevents leak of data and detection of corrupted memory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_page_poison_argument

References:

nist | CM-6(a)
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000134-GPOS-00068
anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$'; }; then

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "page_poison" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"page_poison=[^\"]*\"(.*]\s*)/\1\"page_poison=1\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"page_poison=1\"]" >> "$KARGS_DIR/10-page_poison.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check page_poison argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*page_poison=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check page_poison argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add page_poison argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="page_poison=1 "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing page_poison argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: page_poison=[a-zA-Z0-9,]+
        replace: page_poison=1
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add page_poison argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 page_poison=1"
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_page_poison_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Enable SLUB/SLAB allocator poisoning [ref]

To enable poisoning of SLUB/SLAB objects, add the argument `slub_debug=FZP` to the default GRUB 2 command line for the Linux operating system. Configure the default Grub2 kernel command line to contain slub_debug=FZP as follows:

    # grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) slub_debug=FZP"

Rationale: | Poisoning writes an arbitrary value to freed objects, so any modification or reference to that object after being freed or before being initialized will be detected and prevented. This prevents many types of use-after-free vulnerabilities at little performance cost. Also prevents leak of data and detection of corrupted memory.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_grub2_slub_debug_argument

References:

nist | CM-6(a)
os-srg | SRG-OS-000433-GPOS-00192, SRG-OS-000134-GPOS-00068
anssi | R8

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'grub2-common' 2>/dev/null | grep -q '^installed$'; }; then

    var_slub_debug_options='FZP'

    if /bin/false ; then
        KARGS_DIR="/usr/lib/bootc/kargs.d/"
        if grep -q -E "slub_debug" "$KARGS_DIR/*.toml" ; then
            sed -i -E "s/^(\s*kargs\s*=\s*\[.*)\"slub_debug=[^\"]*\"(.*]\s*)/\1\"slub_debug=$var_slub_debug_options\"\2/" "$KARGS_DIR/*.toml"
        else
            echo "kargs = [\"slub_debug=$var_slub_debug_options\"]" >> "$KARGS_DIR/10-slub_debug.toml"
        fi
    else

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

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | medium
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy
    - name: XCCDF Value var_slub_debug_options # promote to variable
      set_fact:
        var_slub_debug_options: !!str FZP
      tags:
        - always

    - name: Check slub_debug argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=.*slub_debug=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: argcheck
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Check slub_debug argument exists
      ansible.builtin.command: grep '^\s*GRUB_CMDLINE_LINUX=' /etc/default/grub
      check_mode: false
      failed_when: false
      changed_when: false
      register: linecheck
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add slub_debug argument
      ansible.builtin.lineinfile:
        line: GRUB_CMDLINE_LINUX="slub_debug={{ var_slub_debug_options }} "
        state: present
        dest: /etc/default/grub
        create: true
        mode: '0644'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc != 0
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Replace existing slub_debug argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: slub_debug=[a-zA-Z0-9,]+
        replace: slub_debug={{ var_slub_debug_options }}
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc == 0 and
        linecheck.rc == 0
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Add slub_debug argument
      ansible.builtin.replace:
        path: /etc/default/grub
        regexp: (^\s*GRUB_CMDLINE_LINUX=.*)"
        replace: \1 slub_debug={{ var_slub_debug_options }}"
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      - argcheck is not skipped and linecheck is not skipped and argcheck.rc != 0 and
        linecheck.rc == 0
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Update grub defaults and the bootloader menu
      ansible.builtin.command: /usr/sbin/update-grub
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"grub2-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - grub2_slub_debug_argument
      - low_disruption
      - medium_complexity
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Restrict Access to Kernel Message Buffer [ref]

To set the runtime status of the `kernel.dmesg_restrict` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.dmesg_restrict=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.dmesg_restrict = 1

Rationale: | Unprivileged access to the kernel syslog can expose sensitive kernel address information.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_dmesg_restrict

References:

cui | 3.1.5
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3), 164.308(a)(4), 164.310(b), 164.310(c), 164.312(a), 164.312(e)
nist | SI-11(a), SI-11(b)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000138-GPOS-00069
app-srg-ctr | SRG-APP-000243-CTR-000600
anssi | R9
ism | 1546

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.dmesg_restrict from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.dmesg_restrict.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.dmesg_restrict" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.dmesg_restrict
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.dmesg_restrict="1"
    fi

    #
    # If kernel.dmesg_restrict present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.dmesg_restrict = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.dmesg_restrict")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^kernel.dmesg_restrict\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.dmesg_restrict\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Find all files that contain kernel.dmesg_restrict
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.dmesg_restrict\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Find all files that set kernel.dmesg_restrict
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.dmesg_restrict\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Comment out any occurrences of
        kernel.dmesg_restrict from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.dmesg_restrict
        replace: '#kernel.dmesg_restrict'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

    - name: Restrict Access to Kernel Message Buffer - Ensure sysctl kernel.dmesg_restrict
        is set to 1
      ansible.posix.sysctl:
        name: kernel.dmesg_restrict
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.5
      - NIST-800-53-SI-11(a)
      - NIST-800-53-SI-11(b)
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_dmesg_restrict

#### Rule Disable loading and unloading of kernel modules [ref]

To set the runtime status of the `kernel.modules_disabled` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.modules_disabled=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.modules_disabled = 1

Warning: This rule doesn't come with remediation. Remediating this rule during the installation process disrupts the install and boot process.

Rationale: | Malicious kernel modules can have a significant impact on system security and availability. Disabling loading of kernel modules prevents this threat. Note that once this option has been set, it cannot be reverted without doing a system reboot. Make sure that all needed kernel modules are loaded before setting this option.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_modules_disabled

References:

anssi | R10

#### Rule Kernel panic on oops [ref]

To set the runtime status of the `kernel.panic_on_oops` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.panic_on_oops=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.panic_on_oops = 1

Warning: The system may start to panic when it normally wouldn't. A non-catastrophic error that would have allowed the system to continue operating will now result in a panic.

Rationale: | An attacker trying to exploit the kernel may trigger kernel OOPSes, panicking the system will impede them from continuing.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_panic_on_oops

References:

anssi | R9

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.panic_on_oops from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.panic_on_oops.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.panic_on_oops" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.panic_on_oops
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.panic_on_oops="1"
    fi

    #
    # If kernel.panic_on_oops present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.panic_on_oops = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.panic_on_oops")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^kernel.panic_on_oops\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.panic_on_oops\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_panic_on_oops

    - name: Kernel panic on oops - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_panic_on_oops

    - name: Kernel panic on oops - Find all files that contain kernel.panic_on_oops
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.panic_on_oops\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_panic_on_oops

    - name: Kernel panic on oops - Find all files that set kernel.panic_on_oops to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.panic_on_oops\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_panic_on_oops

    - name: Kernel panic on oops - Comment out any occurrences of kernel.panic_on_oops
        from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.panic_on_oops
        replace: '#kernel.panic_on_oops'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_panic_on_oops

    - name: Kernel panic on oops - Ensure sysctl kernel.panic_on_oops is set to 1
      ansible.posix.sysctl:
        name: kernel.panic_on_oops
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_panic_on_oops

#### Rule Limit CPU consumption of the Perf system [ref]

To set the runtime status of the `kernel.perf_cpu_time_max_percent` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.perf_cpu_time_max_percent=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.perf_cpu_time_max_percent = 1

Rationale: | The `kernel.perf_cpu_time_max_percent` configures a threshold of maximum percentile of CPU that can be used by Perf system. Restricting usage of `Perf` system decreases risk of potential availability problems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_perf_cpu_time_max_percent

References:

anssi | R9

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.perf_cpu_time_max_percent from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.perf_cpu_time_max_percent.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.perf_cpu_time_max_percent" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.perf_cpu_time_max_percent
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.perf_cpu_time_max_percent="1"
    fi

    #
    # If kernel.perf_cpu_time_max_percent present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.perf_cpu_time_max_percent = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.perf_cpu_time_max_percent")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^kernel.perf_cpu_time_max_percent\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.perf_cpu_time_max_percent\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_cpu_time_max_percent

    - name: Limit CPU consumption of the Perf system - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_cpu_time_max_percent

    - name: Limit CPU consumption of the Perf system - Find all files that contain kernel.perf_cpu_time_max_percent
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_cpu_time_max_percent\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_cpu_time_max_percent

    - name: Limit CPU consumption of the Perf system - Find all files that set kernel.perf_cpu_time_max_percent
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_cpu_time_max_percent\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_cpu_time_max_percent

    - name: Limit CPU consumption of the Perf system - Comment out any occurrences of
        kernel.perf_cpu_time_max_percent from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.perf_cpu_time_max_percent
        replace: '#kernel.perf_cpu_time_max_percent'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_cpu_time_max_percent

    - name: Limit CPU consumption of the Perf system - Ensure sysctl kernel.perf_cpu_time_max_percent
        is set to 1
      ansible.posix.sysctl:
        name: kernel.perf_cpu_time_max_percent
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_cpu_time_max_percent

#### Rule Limit sampling frequency of the Perf system [ref]

To set the runtime status of the `kernel.perf_event_max_sample_rate` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.perf_event_max_sample_rate=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.perf_event_max_sample_rate = 1

Rationale: | The `kernel.perf_event_max_sample_rate` parameter configures maximum frequency of collecting of samples for the Perf system. It is expressed in samples per second. Restricting usage of `Perf` system decreases risk of potential availability problems.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_perf_event_max_sample_rate

References:

anssi | R9

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.perf_event_max_sample_rate from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.perf_event_max_sample_rate.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.perf_event_max_sample_rate" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.perf_event_max_sample_rate
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.perf_event_max_sample_rate="1"
    fi

    #
    # If kernel.perf_event_max_sample_rate present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.perf_event_max_sample_rate = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.perf_event_max_sample_rate")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^kernel.perf_event_max_sample_rate\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.perf_event_max_sample_rate\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_event_max_sample_rate

    - name: Limit sampling frequency of the Perf system - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_event_max_sample_rate

    - name: Limit sampling frequency of the Perf system - Find all files that contain
        kernel.perf_event_max_sample_rate
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_event_max_sample_rate\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_event_max_sample_rate

    - name: Limit sampling frequency of the Perf system - Find all files that set kernel.perf_event_max_sample_rate
        to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_event_max_sample_rate\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_event_max_sample_rate

    - name: Limit sampling frequency of the Perf system - Comment out any occurrences
        of kernel.perf_event_max_sample_rate from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.perf_event_max_sample_rate
        replace: '#kernel.perf_event_max_sample_rate'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_event_max_sample_rate

    - name: Limit sampling frequency of the Perf system - Ensure sysctl kernel.perf_event_max_sample_rate
        is set to 1
      ansible.posix.sysctl:
        name: kernel.perf_event_max_sample_rate
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_perf_event_max_sample_rate

#### Rule Disallow kernel profiling by unprivileged users [ref]

To set the runtime status of the `kernel.perf_event_paranoid` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.perf_event_paranoid=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.perf_event_paranoid = 2

Rationale: | Kernel profiling can reveal sensitive information about kernel behaviour.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_perf_event_paranoid

References:

nist | AC-6
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000138-GPOS-00069
app-srg-ctr | SRG-APP-000243-CTR-000600
anssi | R9

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.perf_event_paranoid from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.perf_event_paranoid.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.perf_event_paranoid" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.perf_event_paranoid
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.perf_event_paranoid="2"
    fi

    #
    # If kernel.perf_event_paranoid present in /etc/sysctl.conf, change value to "2"
    #	else, add "kernel.perf_event_paranoid = 2" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.perf_event_paranoid")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "2"

    # 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 "^kernel.perf_event_paranoid\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.perf_event_paranoid\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Find all files that contain
        kernel.perf_event_paranoid
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_event_paranoid\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Find all files that set
        kernel.perf_event_paranoid to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.perf_event_paranoid\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Comment out any occurrences
        of kernel.perf_event_paranoid from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.perf_event_paranoid
        replace: '#kernel.perf_event_paranoid'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

    - name: Disallow kernel profiling by unprivileged users - Ensure sysctl kernel.perf_event_paranoid
        is set to 2
      ansible.posix.sysctl:
        name: kernel.perf_event_paranoid
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - disable_strategy
      - low_complexity
      - low_severity
      - medium_disruption
      - reboot_required
      - sysctl_kernel_perf_event_paranoid

#### Rule Configure maximum number of process identifiers [ref]

To set the runtime status of the `kernel.pid_max` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.pid_max=65536

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.pid_max = 65536

Rationale: | The `kernel.pid_max` parameter configures upper limit on process identifiers (PID). If this number is not high enough, it might happen that forking of new processes is not possible, because all available PIDs are exhausted. Increasing this number enhances availability.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_pid_max

References:

anssi | R9

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.pid_max from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.pid_max.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.pid_max" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.pid_max
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.pid_max="65536"
    fi

    #
    # If kernel.pid_max present in /etc/sysctl.conf, change value to "65536"
    #	else, add "kernel.pid_max = 65536" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.pid_max")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "65536"

    # 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 "^kernel.pid_max\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.pid_max\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_pid_max

    - name: Configure maximum number of process identifiers - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_pid_max

    - name: Configure maximum number of process identifiers - Find all files that contain
        kernel.pid_max
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.pid_max\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_pid_max

    - name: Configure maximum number of process identifiers - Find all files that set
        kernel.pid_max to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.pid_max\s*=\s*65536$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_pid_max

    - name: Configure maximum number of process identifiers - Comment out any occurrences
        of kernel.pid_max from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.pid_max
        replace: '#kernel.pid_max'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_pid_max

    - name: Configure maximum number of process identifiers - Ensure sysctl kernel.pid_max
        is set to 65536
      ansible.posix.sysctl:
        name: kernel.pid_max
        value: '65536'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_pid_max

#### Rule Disallow magic SysRq key [ref]

To set the runtime status of the `kernel.sysrq` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.sysrq=0

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.sysrq = 0

Rationale: | The Magic SysRq key allows sending certain commands directly to the running kernel. It can dump various system and process information, potentially revealing sensitive information. It can also reboot or shutdown the machine, disturbing its availability.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_sysrq

References:

anssi | R9

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.sysrq from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.sysrq.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.sysrq" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.sysrq
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.sysrq="0"
    fi

    #
    # If kernel.sysrq present in /etc/sysctl.conf, change value to "0"
    #	else, add "kernel.sysrq = 0" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.sysrq")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "0"

    # 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 "^kernel.sysrq\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.sysrq\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_sysrq

    - name: Disallow magic SysRq key - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_sysrq

    - name: Disallow magic SysRq key - Find all files that contain kernel.sysrq
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.sysrq\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_sysrq

    - name: Disallow magic SysRq key - Find all files that set kernel.sysrq to correct
        value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.sysrq\s*=\s*0$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_sysrq

    - name: Disallow magic SysRq key - Comment out any occurrences of kernel.sysrq from
        config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.sysrq
        replace: '#kernel.sysrq'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_sysrq

    - name: Disallow magic SysRq key - Ensure sysctl kernel.sysrq is set to 0
      ansible.posix.sysctl:
        name: kernel.sysrq
        value: '0'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_sysrq

#### Rule Disable Access to Network bpf() Syscall From Unprivileged Processes [ref]

To set the runtime status of the `kernel.unprivileged_bpf_disabled` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.unprivileged_bpf_disabled=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.unprivileged_bpf_disabled = 1

Rationale: | Loading and accessing the packet filters programs and maps using the bpf() syscall has the potential of revealing sensitive information about the kernel state.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_unprivileged_bpf_disabled

References:

nist | AC-6, SC-7(10)
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000480-GPOS-00227
anssi | R9
ism | 1409

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.unprivileged_bpf_disabled from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.unprivileged_bpf_disabled.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.unprivileged_bpf_disabled" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.unprivileged_bpf_disabled
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.unprivileged_bpf_disabled="1"
    fi

    #
    # If kernel.unprivileged_bpf_disabled present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.unprivileged_bpf_disabled = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.unprivileged_bpf_disabled")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^kernel.unprivileged_bpf_disabled\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.unprivileged_bpf_disabled\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Set
        fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Find
        all files that contain kernel.unprivileged_bpf_disabled
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.unprivileged_bpf_disabled\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Find
        all files that set kernel.unprivileged_bpf_disabled to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.unprivileged_bpf_disabled\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Comment
        out any occurrences of kernel.unprivileged_bpf_disabled from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.unprivileged_bpf_disabled
        replace: '#kernel.unprivileged_bpf_disabled'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

    - name: Disable Access to Network bpf() Syscall From Unprivileged Processes - Ensure
        sysctl kernel.unprivileged_bpf_disabled is set to 1
      ansible.posix.sysctl:
        name: kernel.unprivileged_bpf_disabled
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_unprivileged_bpf_disabled

#### Rule Restrict usage of ptrace to descendant processes [ref]

To set the runtime status of the `kernel.yama.ptrace_scope` kernel parameter, run the following command:

    $ sudo sysctl -w kernel.yama.ptrace_scope=1

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    kernel.yama.ptrace_scope = 1

Rationale: | Unrestricted usage of ptrace allows compromised binaries to run ptrace on another processes of the user. Like this, the attacker can steal sensitive information from the target processes (e.g. SSH sessions, web browser, ...) without any additional assistance from the user (i.e. without resorting to phishing).
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_kernel_yama_ptrace_scope

References:

nist | SC-7(10)
ospp | FMT_SMF_EXT.1
os-srg | SRG-OS-000132-GPOS-00067, SRG-OS-000480-GPOS-00227
anssi | R11
ism | 1409

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of kernel.yama.ptrace_scope from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*kernel.yama.ptrace_scope.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "kernel.yama.ptrace_scope" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for kernel.yama.ptrace_scope
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w kernel.yama.ptrace_scope="1"
    fi

    #
    # If kernel.yama.ptrace_scope present in /etc/sysctl.conf, change value to "1"
    #	else, add "kernel.yama.ptrace_scope = 1" to /etc/sysctl.conf
    #

    # 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' <<< "^kernel.yama.ptrace_scope")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "1"

    # 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 "^kernel.yama.ptrace_scope\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^kernel.yama.ptrace_scope\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

    - name: Restrict usage of ptrace to descendant processes - Set fact for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

    - name: Restrict usage of ptrace to descendant processes - Find all files that contain
        kernel.yama.ptrace_scope
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.yama.ptrace_scope\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

    - name: Restrict usage of ptrace to descendant processes - Find all files that set
        kernel.yama.ptrace_scope to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*kernel.yama.ptrace_scope\s*=\s*1$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

    - name: Restrict usage of ptrace to descendant processes - Comment out any occurrences
        of kernel.yama.ptrace_scope from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*kernel.yama.ptrace_scope
        replace: '#kernel.yama.ptrace_scope'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

    - name: Restrict usage of ptrace to descendant processes - Ensure sysctl kernel.yama.ptrace_scope
        is set to 1
      ansible.posix.sysctl:
        name: kernel.yama.ptrace_scope
        value: '1'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_kernel_yama_ptrace_scope

#### Rule Harden the operation of the BPF just-in-time compiler [ref]

To set the runtime status of the `net.core.bpf_jit_harden` kernel parameter, run the following command:

    $ sudo sysctl -w net.core.bpf_jit_harden=2

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    net.core.bpf_jit_harden = 2

Rationale: | When hardened, the extended Berkeley Packet Filter just-in-time compiler will randomize any kernel addresses in the BPF programs and maps, and will not expose the JIT addresses in `/proc/kallsyms`.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_net_core_bpf_jit_harden

References:

nist | CM-6, SC-7(10)
os-srg | SRG-OS-000480-GPOS-00227
anssi | R12
ism | 1409

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of net.core.bpf_jit_harden from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*net.core.bpf_jit_harden.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "net.core.bpf_jit_harden" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for net.core.bpf_jit_harden
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w net.core.bpf_jit_harden="2"
    fi

    #
    # If net.core.bpf_jit_harden present in /etc/sysctl.conf, change value to "2"
    #	else, add "net.core.bpf_jit_harden = 2" to /etc/sysctl.conf
    #

    # 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' <<< "^net.core.bpf_jit_harden")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "2"

    # 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 "^net.core.bpf_jit_harden\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^net.core.bpf_jit_harden\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Set fact for sysctl
        paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Find all files that
        contain net.core.bpf_jit_harden
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.core.bpf_jit_harden\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Find all files that
        set net.core.bpf_jit_harden to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*net.core.bpf_jit_harden\s*=\s*2$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Comment out any occurrences
        of net.core.bpf_jit_harden from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*net.core.bpf_jit_harden
        replace: '#net.core.bpf_jit_harden'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

    - name: Harden the operation of the BPF just-in-time compiler - Ensure sysctl net.core.bpf_jit_harden
        is set to 2
      ansible.posix.sysctl:
        name: net.core.bpf_jit_harden
        value: '2'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6
      - NIST-800-53-SC-7(10)
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_net_core_bpf_jit_harden

#### Rule Prevent applications from mapping low portion of virtual memory [ref]

To set the runtime status of the `vm.mmap_min_addr` kernel parameter, run the following command:

    $ sudo sysctl -w vm.mmap_min_addr=65536

To make sure that the setting is persistent, add the following line to a file in the directory `/etc/sysctl.d`:

    vm.mmap_min_addr = 65536

Rationale: | The `vm.mmap_min_addr` parameter specifies the minimum virtual address that a process is allowed to mmap. Allowing a process to mmap low portion of virtual memory can have security implications such as such as heightened risk of kernel null pointer dereference defects.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sysctl_vm_mmap_min_addr

References:

anssi | R8

Remediation Shell script ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Comment out any occurrences of vm.mmap_min_addr from /etc/sysctl.d/*.conf files

    for f in /etc/sysctl.d/*.conf /run/sysctl.d/*.conf /usr/local/lib/sysctl.d/*.conf /usr/lib/sysctl.d/*.conf; do

      # skip systemd-sysctl symlink (/etc/sysctl.d/99-sysctl.conf -> /etc/sysctl.conf)
      if [[ "$(readlink -f "$f")" == "/etc/sysctl.conf" ]]; then continue; fi

      matching_list=$(grep -P '^(?!#).*[\s]*vm.mmap_min_addr.*$' $f | uniq )
      if ! test -z "$matching_list"; then
        while IFS= read -r entry; do
          escaped_entry=$(sed -e 's|/|\\/|g' <<< "$entry")
          # comment out "vm.mmap_min_addr" matches to preserve user data
          sed -i --follow-symlinks "s/^${escaped_entry}$/# &/g" $f
        done <<< "$matching_list"
      fi
    done

    #
    # Set sysctl config file which to save the desired value
    #

    SYSCONFIG_FILE="/etc/sysctl.conf"

    #
    # Set runtime for vm.mmap_min_addr
    #
    if ! /bin/false ; then
        /sbin/sysctl -q -n -w vm.mmap_min_addr="65536"
    fi

    #
    # If vm.mmap_min_addr present in /etc/sysctl.conf, change value to "65536"
    #	else, add "vm.mmap_min_addr = 65536" to /etc/sysctl.conf
    #

    # 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' <<< "^vm.mmap_min_addr")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s = %s" "$stripped_key" "65536"

    # 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 "^vm.mmap_min_addr\\>" "${SYSCONFIG_FILE}"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^vm.mmap_min_addr\\>.*/$escaped_formatted_output/gi" "${SYSCONFIG_FILE}"
    else
        if [[ -s "${SYSCONFIG_FILE}" ]] && [[ -n "$(tail -c 1 -- "${SYSCONFIG_FILE}" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "${SYSCONFIG_FILE}"
        fi
        printf '%s\n' "$formatted_output" >> "${SYSCONFIG_FILE}"
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | true
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_vm_mmap_min_addr

    - name: Prevent applications from mapping low portion of virtual memory - Set fact
        for sysctl paths
      ansible.builtin.set_fact:
        sysctl_paths:
        - /etc/sysctl.d/
        - /run/sysctl.d/
        - /usr/local/lib/sysctl.d/
        - /usr/lib/sysctl.d/
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_vm_mmap_min_addr

    - name: Prevent applications from mapping low portion of virtual memory - Find all
        files that contain vm.mmap_min_addr
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*vm.mmap_min_addr\s*=\s*.*$'
      register: find_all_values
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_vm_mmap_min_addr

    - name: Prevent applications from mapping low portion of virtual memory - Find all
        files that set vm.mmap_min_addr to correct value
      ansible.builtin.shell:
        cmd: find -L {{ sysctl_paths | join(" ") }} -type f -name '*.conf' | xargs grep
          -HP '^\s*vm.mmap_min_addr\s*=\s*65536$'
      register: find_correct_value
      check_mode: false
      changed_when: false
      failed_when: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_vm_mmap_min_addr

    - name: Prevent applications from mapping low portion of virtual memory - Comment
        out any occurrences of vm.mmap_min_addr from config files
      ansible.builtin.replace:
        path: '{{ item | split(":") | first }}'
        regexp: ^[\s]*vm.mmap_min_addr
        replace: '#vm.mmap_min_addr'
      loop: '{{ find_all_values.stdout_lines }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - find_correct_value.stdout_lines | length == 0 or find_all_values.stdout_lines
        | length > find_correct_value.stdout_lines | length
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_vm_mmap_min_addr

    - name: Prevent applications from mapping low portion of virtual memory - Ensure sysctl
        vm.mmap_min_addr is set to 65536
      ansible.posix.sysctl:
        name: vm.mmap_min_addr
        value: '65536'
        sysctl_file: /etc/sysctl.conf
        state: present
        reload: true
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - reboot_required
      - sysctl_vm_mmap_min_addr

Group SELinux Group contains 1 group and 10 rules

[ref] SELinux is a feature of the Linux kernel which can be used to guard against misconfigured or compromised programs. SELinux enforces the idea that programs should be limited in what files they can access and what actions they can take.
The default SELinux policy, as configured on Debian 13, has been sufficiently developed and debugged that it should be usable on almost any system with minimal configuration and a small amount of system administrator training. This policy prevents system services - including most of the common network-visible services such as mail servers, FTP servers, and DNS servers - from accessing files which those services have no valid reason to access. This action alone prevents a huge amount of possible damage from network attacks against services, from trojaned software, and so forth.
This guide recommends that SELinux be enabled using the default (targeted) policy on every Debian 13 system, unless that system has unusual requirements which make a stronger policy appropriate.

Group SELinux - Booleans Group contains 1 rule
[ref] Enable or Disable runtime customization of SELinux system policies without having to reload or recompile the SELinux policy.

#### Rule Configure the polyinstantiation_enabled SELinux Boolean [ref]

By default, the SELinux boolean `polyinstantiation_enabled` is disabled. This setting should be configured to true.
To set the `polyinstantiation_enabled` SELinux boolean, run the following command:

    $ sudo setsebool -P polyinstantiation_enabled true

Rationale: |
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sebool_polyinstantiation_enabled

References:

anssi | R55

#### Rule Uninstall setroubleshoot-plugins Package [ref]

The SETroubleshoot plugins are used to analyze SELinux AVC data. The service provides information around configuration errors, unauthorized intrusions, and other potential errors. The `setroubleshoot-plugins` package can be removed with the following command:

    $ apt-get remove setroubleshoot-plugins

Rationale: | The SETroubleshoot service is an unnecessary daemon to have running on a server.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_setroubleshoot-plugins_removed

References:

anssi | R49

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove setroubleshoot-plugins
    # from the system, and may remove any packages
    # that depend on setroubleshoot-plugins. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "setroubleshoot-plugins"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_setroubleshoot-plugins

    class remove_setroubleshoot-plugins {
      package { 'setroubleshoot-plugins':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_setroubleshoot-plugins_removed

    - name: 'Uninstall setroubleshoot-plugins Package: Ensure setroubleshoot-plugins is
        removed'
      ansible.builtin.package:
        name: setroubleshoot-plugins
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_setroubleshoot-plugins_removed

#### Rule Uninstall setroubleshoot-server Package [ref]

The SETroubleshoot service notifies desktop users of SELinux denials. The service provides information around configuration errors, unauthorized intrusions, and other potential errors. The `setroubleshoot-server` package can be removed with the following command:

    $ apt-get remove setroubleshoot-server

Rationale: | The SETroubleshoot service is an unnecessary daemon to have running on a server.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_setroubleshoot-server_removed

References:

anssi | R49

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove setroubleshoot-server
    # from the system, and may remove any packages
    # that depend on setroubleshoot-server. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "setroubleshoot-server"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_setroubleshoot-server

    class remove_setroubleshoot-server {
      package { 'setroubleshoot-server':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_setroubleshoot-server_removed

    - name: 'Uninstall setroubleshoot-server Package: Ensure setroubleshoot-server is
        removed'
      ansible.builtin.package:
        name: setroubleshoot-server
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_setroubleshoot-server_removed

#### Rule Uninstall setroubleshoot Package [ref]

The SETroubleshoot service notifies desktop users of SELinux denials. The service provides information around configuration errors, unauthorized intrusions, and other potential errors. The `setroubleshoot` package can be removed with the following command:

    $ apt-get remove setroubleshoot

Rationale: | The SETroubleshoot service is an unnecessary daemon to have running on a server, especially if X Windows is removed or disabled.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_setroubleshoot_removed

References:

anssi | R49

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove setroubleshoot
    # from the system, and may remove any packages
    # that depend on setroubleshoot. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "setroubleshoot"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_setroubleshoot

    class remove_setroubleshoot {
      package { 'setroubleshoot':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_setroubleshoot_removed

    - name: 'Uninstall setroubleshoot Package: Ensure setroubleshoot is removed'
      ansible.builtin.package:
        name: setroubleshoot
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_setroubleshoot_removed

#### Rule Verify Group Who Owns /etc/selinux Directory [ref]

To properly set the group owner of `/etc/selinux`, run the command:

    $ sudo chgrp root /etc/selinux

Rationale: | The ownership of the /etc/selinux directory by the root group is important because this directory hosts SELinux configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the SELinux configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_groupowner_etc_selinux

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    find -P /etc/selinux/ -maxdepth 0 -type d  ! -group root -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_groupowner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - directory_groupowner_etc_selinux_newgroup is undefined
      tags:
      - configure_strategy
      - directory_groupowner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_groupowner_etc_selinux_newgroup variable if root found
      ansible.builtin.set_fact:
        directory_groupowner_etc_selinux_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - directory_groupowner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/selinux/
      ansible.builtin.file:
        path: /etc/selinux/
        follow: false
        state: directory
        group: '{{ directory_groupowner_etc_selinux_newgroup }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_groupowner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/selinux Directory [ref]

To properly set the owner of `/etc/selinux`, run the command:

    $ sudo chown root /etc/selinux

Rationale: | The ownership of the /etc/selinux directory by the root user is important because this directory hosts SELinux configuration. Protection of this directory is critical for system security. Assigning the ownership to root ensures exclusive control of the SELinux configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_owner_etc_selinux

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    find -P /etc/selinux/ -maxdepth 0 -type d  ! -user 0 -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_owner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the directory_owner_etc_selinux_newown variable if represented by uid
      ansible.builtin.set_fact:
        directory_owner_etc_selinux_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on directory /etc/selinux/
      ansible.builtin.file:
        path: /etc/selinux/
        follow: false
        state: directory
        owner: '{{ directory_owner_etc_selinux_newown }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_owner_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/selinux Directory [ref]

To properly set the permissions of `/etc/selinux`, run the command:

    $ sudo chmod 0755 /etc/selinux

Rationale: | Setting correct permissions on the /etc/selinux directory is important because this directory hosts SELinux configuration. Protection of this directory is critical for system security. Restricting the permissions ensures exclusive control of the SELinux configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_directory_permissions_etc_selinux

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    find -H /etc/selinux/ -maxdepth 0 -perm /u+s,g+ws,o+wt -type d -exec chmod u-s,g-ws,o-wt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - directory_permissions_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/selinux/ file(s)
      ansible.builtin.command: 'find -P /etc/selinux/ -maxdepth 0 -perm /u+s,g+ws,o+wt  -type
        d '
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/selinux/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-s,g-ws,o-wt
        state: directory
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - directory_permissions_etc_selinux
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/sestatus.conf File [ref]

To properly set the group owner of `/etc/sestatus.conf`, run the command:

    $ sudo chgrp root /etc/sestatus.conf

Rationale: | The ownership of the /etc/sestatus.conf file by the root group is important because this file hosts SELinux configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the SELinux configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_sestatus_conf

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "root" >/dev/null 2>&1; then
      newgroup="root"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "root is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/sestatus.conf" | grep -E -w -q "root"; then
        chgrp --no-dereference "$newgroup" /etc/sestatus.conf
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the root group is defined
      ansible.builtin.getent:
        database: group
        key: root
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_groupowner_etc_sestatus_conf_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_etc_sestatus_conf_newgroup variable if root found
      ansible.builtin.set_fact:
        file_groupowner_etc_sestatus_conf_newgroup: root
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["root"] is defined
      tags:
      - configure_strategy
      - file_groupowner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/sestatus.conf
      ansible.builtin.stat:
        path: /etc/sestatus.conf
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/sestatus.conf
      ansible.builtin.file:
        path: /etc/sestatus.conf
        follow: false
        group: '{{ file_groupowner_etc_sestatus_conf_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/sestatus.conf File [ref]

To properly set the owner of `/etc/sestatus.conf`, run the command:

    $ sudo chown root /etc/sestatus.conf

Rationale: | The ownership of the /etc/sestatus.conf file by the root user is important because this file hosts SELinux configuration. Protection of this file is critical for system security. Assigning the ownership to root ensures exclusive control of the SELinux configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_sestatus_conf

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/sestatus.conf" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/sestatus.conf
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_etc_sestatus_conf_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_sestatus_conf_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/sestatus.conf
      ansible.builtin.stat:
        path: /etc/sestatus.conf
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/sestatus.conf
      ansible.builtin.file:
        path: /etc/sestatus.conf
        follow: false
        owner: '{{ file_owner_etc_sestatus_conf_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/sestatus.conf File [ref]

To properly set the permissions of `/etc/sestatus.conf`, run the command:

    $ sudo chmod 0644 /etc/sestatus.conf

Rationale: | Setting correct permissions on the /etc/sestatus.conf file is important because this file hosts SELinux configuration. Protection of this file is critical for system security. Restricting the permissions ensures exclusive control of the SELinux configuration.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_sestatus_conf

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xs,g-xws,o-xwt /etc/sestatus.conf

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/sestatus.conf
      ansible.builtin.stat:
        path: /etc/sestatus.conf
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwt on /etc/sestatus.conf
      ansible.builtin.file:
        path: /etc/sestatus.conf
        mode: u-xs,g-xws,o-xwt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_sestatus_conf
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Services Group contains 16 groups and 37 rules

[ref] The best protection against vulnerable software is running less software. This section describes how to review the software which Debian 13 installs on a system and disable software which is not needed. It then enumerates the software packages installed on a default Debian 13 system and provides guidance about which ones can be safely disabled.
Debian 13 provides a convenient minimal install option that essentially installs the bare necessities for a functional system. When building Debian 13 systems, it is highly recommended to select the minimal packages and then build up the system from there.

Group DHCP Group contains 1 group and 2 rules

[ref] The Dynamic Host Configuration Protocol (DHCP) allows systems to request and obtain an IP address and other configuration parameters from a server.
This guide recommends configuring networking on clients by manually editing the appropriate files under `/etc/sysconfig`. Use of DHCP can make client systems vulnerable to compromise by rogue DHCP servers, and should be avoided unless necessary. If using DHCP is necessary, however, there are best practices that should be followed to minimize security risk.

Group Disable DHCP Server Group contains 2 rules
[ref] The DHCP server `dhcpd` is not installed or activated by default. If the software was installed and activated, but the system does not need to act as a DHCP server, it should be disabled and removed.

#### Rule Uninstall DHCP Server Package [ref]

If the system does not need to act as a DHCP server, the dhcp package can be uninstalled. The `dhcp` package can be removed with the following command:

    $ apt-get remove dhcp

Rationale: | Removing the DHCP server ensures that it cannot be easily or accidentally reactivated and disrupt network operation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_dhcp_removed

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove dhcp
    # from the system, and may remove any packages
    # that depend on dhcp. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "dhcp"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_dhcp

    class remove_dhcp {
      package { 'dhcp':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall DHCP Server Package: Ensure dhcp is removed'
      ansible.builtin.package:
        name: dhcp
        state: absent
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_dhcp_removed

#### Rule Uninstall kea Package [ref]

If the system does not need to act as a DHCP server, the kea package can be uninstalled.
Rationale: | Removing the DHCP server ensures that it cannot be easily or accidentally reactivated and disrupt network operation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_kea_removed

References:

anssi | R62

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove kea
    # from the system, and may remove any packages
    # that depend on kea. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "kea"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_kea

    class remove_kea {
      package { 'kea':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall kea Package: Ensure kea is removed'
      ansible.builtin.package:
        name: kea
        state: absent
      tags:
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_kea_removed

Group Mail Server Software Group contains 1 group and 3 rules

[ref] Mail servers are used to send and receive email over the network. Mail is a very common service, and Mail Transfer Agents (MTAs) are obvious targets of network attack. Ensure that systems are not running MTAs unnecessarily, and configure needed MTAs as defensively as possible.
Very few systems at any site should be configured to directly receive email over the network. Users should instead use mail client programs to retrieve email from a central server that supports protocols such as IMAP or POP3. However, it is normal for most systems to be independently capable of sending email, for instance so that cron jobs can report output to an administrator. Most MTAs, including Postfix, support a submission-only mode in which mail can be sent from the local system to a central site MTA (or directly delivered to a local account), but the system still cannot receive mail directly over a network.
The `alternatives` program in Debian 13 permits selection of other mail server software (such as Sendmail), but Postfix is the default and is preferred. Postfix was coded with security in mind and can also be more effectively contained by SELinux as its modular design has resulted in separate processes performing specific actions. More information is available on its website, http://www.postfix.org.

Group Configure SMTP For Mail Clients Group contains 2 rules
[ref] This section discusses settings for Postfix in a submission-only e-mail configuration.

#### Rule Configure System to Forward All Mail For The Root Account [ref]

Make sure that mails delivered to root user are forwarded to a monitored email address. Make sure that the address change_me@localhost is a valid email address reachable from the system in question. Use the following command to configure the alias:

    $ sudo echo "root: change_me@localhost" >> /etc/aliases
    $ sudo newaliases

Rationale: | A number of system services utilize email messages sent to the root user to notify system administrators of active or impending issues. These messages must be forwarded to at least one monitored email address.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_postfix_client_configure_mail_alias

References:

nist | CM-6(a)
os-srg | SRG-OS-000046-GPOS-00022
anssi | R75

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    var_postfix_root_mail_alias='change_me@localhost'

    # 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' <<< "^root")

    # shellcheck disable=SC2059
    printf -v formatted_output "%s: %s" "$stripped_key" "$var_postfix_root_mail_alias"

    # 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 "^root\\>" "/etc/aliases"; then
        escaped_formatted_output=$(sed -e 's|/|\\/|g' <<< "$formatted_output")
        LC_ALL=C sed -i --follow-symlinks "s/^root\\>.*/$escaped_formatted_output/gi" "/etc/aliases"
    else
        if [[ -s "/etc/aliases" ]] && [[ -n "$(tail -c 1 -- "/etc/aliases" || true)" ]]; then
            LC_ALL=C sed -i --follow-symlinks '$a'\\ "/etc/aliases"
        fi
        printf '%s\n' "$formatted_output" >> "/etc/aliases"
    fi

    if [ -f /usr/bin/newaliases ]; then
        newaliases
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias
    - name: XCCDF Value var_postfix_root_mail_alias # promote to variable
      set_fact:
        var_postfix_root_mail_alias: !!str change_me@localhost
      tags:
        - always

    - name: Configure System to Forward All Mail For The Root Account - Make sure that
        "/etc/aliases" has a defined value for root
      ansible.builtin.lineinfile:
        path: /etc/aliases
        line: 'root: {{ var_postfix_root_mail_alias }}'
        regexp: ^(?:[rR][oO][oO][tT]|"[rR][oO][oO][tT]")\s*:\s*(.+)$
        create: true
        state: present
      register: aliases_root_mail_alias_changed
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias

    - name: Configure System to Forward All Mail For The Root Account - Check if newaliases
        command is available
      ansible.builtin.stat:
        path: /usr/bin/newaliases
      register: result_newaliases_present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias

    - name: Configure System to Forward All Mail For The Root Account - Update postfix
        aliases
      ansible.builtin.command:
        cmd: newaliases
      when:
      - '"linux-base" in ansible_facts.packages'
      - aliases_root_mail_alias_changed is changed
      - result_newaliases_present.stat.exists
      tags:
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - postfix_client_configure_mail_alias

#### Rule Disable Postfix Network Listening [ref]

Edit the file `/etc/postfix/main.cf` to ensure that only the following `inet_interfaces` line appears:

    inet_interfaces = loopback-only

Rationale: | This ensures `postfix` accepts mail messages (such as cron job reports) from the local system only, and not from the network, which protects it from network attack.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_postfix_network_listening_disabled

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
anssi | R74
pcidss4 | 1.4.2, 1.4

#### Rule Uninstall Sendmail Package [ref]

Sendmail is not the default mail transfer agent and is not installed by default. The `sendmail` package can be removed with the following command:

    $ apt-get remove sendmail

Rationale: | The sendmail software was not developed with security in mind and its design prevents it from being effectively contained by SELinux. Postfix should be used instead.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_sendmail_removed

References:

cis-csc | 11, 14, 3, 9
cobit5 | BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS05.02, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 7.6
iso27001-2013 | A.12.1.2, A.12.5.1, A.12.6.2, A.14.2.2, A.14.2.3, A.14.2.4, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.IP-1, PR.PT-3
os-srg | SRG-OS-000480-GPOS-00227, SRG-OS-000095-GPOS-00049
anssi | R62

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove sendmail
    # from the system, and may remove any packages
    # that depend on sendmail. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "sendmail"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_sendmail

    class remove_sendmail {
      package { 'sendmail':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sendmail_removed

    - name: 'Uninstall Sendmail Package: Ensure sendmail is removed'
      ansible.builtin.package:
        name: sendmail
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sendmail_removed

Group Network Time Protocol Group contains 6 rules

[ref] The Network Time Protocol is used to manage the system clock over a network. Computer clocks are not very accurate, so time will drift unpredictably on unmanaged systems. Central time protocols can be used both to ensure that time is consistent among a network of systems, and that their time is consistent with the outside world.
If every system on a network reliably reports the same time, then it is much easier to correlate log messages in case of an attack. In addition, a number of cryptographic protocols (such as Kerberos) use timestamps to prevent certain types of attacks. If your network does not have synchronized time, these protocols may be unreliable or even unusable.
Depending on the specifics of the network, global time accuracy may be just as important as local synchronization, or not very important at all. If your network is connected to the Internet, using a public timeserver (or one provided by your enterprise) provides globally accurate timestamps which may be essential in investigating or responding to an attack which originated outside of your network.
A typical network setup involves a small number of internal systems operating as NTP servers, and the remainder obtaining time information from those internal servers.
There is a choice between the daemons `ntpd` and `chronyd`, which are available from the repositories in the `ntp` and `chrony` packages respectively.
The default `chronyd` daemon can work well when external time references are only intermittently accessible, can perform well even when the network is congested for longer periods of time, can usually synchronize the clock faster and with better time accuracy, and quickly adapts to sudden changes in the rate of the clock, for example, due to changes in the temperature of the crystal oscillator. `Chronyd` should be considered for all systems which are frequently suspended or otherwise intermittently disconnected and reconnected to a network. Mobile and virtual systems for example.
The `ntpd` NTP daemon fully supports NTP protocol version 4 (RFC 5905), including broadcast, multicast, manycast clients and servers, and the orphan mode. It also supports extra authentication schemes based on public-key cryptography (RFC 5906). The NTP daemon (`ntpd`) should be considered for systems which are normally kept permanently on. Systems which are required to use broadcast or multicast IP, or to perform authentication of packets with the `Autokey` protocol, should consider using `ntpd`.
Refer to https://wiki.debian.org/NTP for more detailed comparison of features of `chronyd` and `ntpd` daemon features respectively, and for further guidance how to choose between the two NTP daemons.
The upstream manual pages at https://chrony-project.org/documentation.html for `chronyd` and http://www.ntp.org for `ntpd` provide additional information on the capabilities and configuration of each of the NTP daemons.

#### Rule The Chrony package is installed [ref]

System time should be synchronized between all systems in an environment. This is typically done by establishing an authoritative time server or set of servers and having all systems synchronize their clocks to them. The `chrony` package can be installed with the following command:

    $ apt-get install chrony

Rationale: | Time synchronization is important to support time sensitive security mechanisms like Kerberos and also ensures log files have consistent time records across the enterprise, which aids in forensic investigations.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_chrony_installed

References:

ospp | FMT_SMF_EXT.1
pcidss | Req-10.4
os-srg | SRG-OS-000355-GPOS-00143
anssi | R71
ism | 0988, 1405
pcidss4 | 10.6.1, 10.6

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "chrony"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_chrony

    class install_chrony {
      package { 'chrony':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSS-Req-10.4
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_chrony_installed

    - name: Ensure chrony is installed
      ansible.builtin.package:
        name: chrony
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.4
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_chrony_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "chrony"
    version = "*"

#### Rule Enable the NTP Daemon [ref]

Run the following command to determine the current status of the `chrony` service:

    $ sudo systemctl is-active chrony

If the service is running, it should return the following:

    active

Note: The `chronyd` daemon is enabled by default.
Run the following command to determine the current status of the `ntpd` service:

    $ sudo systemctl is-active ntpd

If the service is running, it should return the following:

    active

Note: The `ntpd` daemon is not enabled by default. Though as mentioned in the previous sections in certain environments the `ntpd` daemon might be preferred to be used rather than the `chronyd` one. Refer to: for guidance which NTP daemon to choose depending on the environment used.

Rationale:

Enabling some of `chrony` or `ntpd` services ensures that the NTP daemon will be running and that the system will synchronize its time to any servers specified. This is important whether the system is configured to be a client (and synchronize only its own clock) or it is also acting as an NTP server to other systems. Synchronizing time is essential for authentication services such as Kerberos, but it is also important for maintaining accurate logs and auditing possible security breaches.
The `chronyd` and `ntpd` NTP daemons offer all of the functionality of `ntpdate`, which is now deprecated.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_chronyd_or_ntpd_enabled

References:

cis-csc | 1, 14, 15, 16, 3, 5, 6
cobit5 | APO11.04, BAI03.05, DSS05.04, DSS05.07, MEA02.01
cui | 3.3.7
isa-62443-2009 | 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1
nist | CM-6(a), AU-8(1)(a), AU-12(1)
nist-csf | PR.PT-1
pcidss | Req-10.4.1
app-srg-ctr | SRG-APP-000116-CTR-000235
anssi | R71
ism | 0988, 1405
pcidss4 | 10.6.1, 10.6

#### Rule A remote time server for Chrony is configured [ref]

`Chrony` is a daemon which implements the Network Time Protocol (NTP). It is designed to synchronize system clocks across a variety of systems and use a source that is highly accurate. More information on `chrony` can be found at https://chrony-project.org/. `Chrony` can be configured to be a client and/or a server. Add or edit server or pool lines to `/etc/chrony/chrony.conf` as appropriate:

    server <remote-server>

Multiple servers may be configured.

Rationale: | If `chrony` is in use on the system proper configuration is vital to ensuring time synchronization is working properly.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_chronyd_specify_remote_server

References:

nist | CM-6(a), AU-8(1)(a)
pcidss | Req-10.4.3
os-srg | SRG-OS-000355-GPOS-00143
anssi | R71
ism | 0988, 1405
pcidss4 | 10.6.2, 10.6

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'chrony' 2>/dev/null | grep -q '^installed$'; }; then

    var_multiple_time_servers='0.pool.ntp.org,1.pool.ntp.org,2.pool.ntp.org,3.pool.ntp.org'

    config_file="/etc/chrony/chrony.conf"

    if ! grep -q '^[[:space:]]*\(server\|pool\)[[:space:]]\+[[:graph:]]\+' "$config_file" ; then
      if ! grep -q '#[[:space:]]*server' "$config_file" ; then
        for server in $(echo "$var_multiple_time_servers" | tr ',' '\n') ; do
          printf '\nserver %s' "$server" >> "$config_file"
        done
      else
        sed -i 's/#[ \t]*server/server/g' "$config_file"
      fi
      if [[ -s "$config_file" ]] && [[ -n "$(tail -c 1 -- "$config_file" || true)" ]]; then
          LC_ALL=C sed -i --follow-symlinks '$a'\\ "$config_file"
      fi
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.2
      - chronyd_specify_remote_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
    - name: XCCDF Value var_multiple_time_servers # promote to variable
      set_fact:
        var_multiple_time_servers: !!str 0.pool.ntp.org,1.pool.ntp.org,2.pool.ntp.org,3.pool.ntp.org
      tags:
        - always

    - name: Detect if chrony is already configured with pools or servers
      ansible.builtin.find:
        path: /etc
        patterns: chrony.conf
        contains: ^[\s]*(?:server|pool)[\s]+[\w]+
      register: chrony_servers
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.2
      - chronyd_specify_remote_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Configure remote time servers
      ansible.builtin.lineinfile:
        path: /etc/chrony/chrony.conf
        line: server {{ item }}
        state: present
        create: true
      loop: '{{ var_multiple_time_servers.split(",") }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"chrony" in ansible_facts.packages'
      - chrony_servers.matched == 0
      tags:
      - NIST-800-53-AU-8(1)(a)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.3
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.2
      - chronyd_specify_remote_server
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Who Owns /etc/chrony.keys File [ref]

To properly set the group owner of `/etc/chrony.keys`, run the command:

    $ sudo chgrp chrony /etc/chrony.keys

Rationale: | The ownership of the /etc/chrony.keys file by the chrony group is important because this file hosts chrony cryptographic keys. Protection of this file is critical for system security. Assigning the ownership to chrony ensures exclusive control of the chrony cryptography keys.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_etc_chrony_keys

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "chrony" >/dev/null 2>&1; then
      newgroup="chrony"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "chrony is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/chrony.keys" | grep -E -w -q "chrony"; then
        chgrp --no-dereference "$newgroup" /etc/chrony.keys
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupowner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Check that the chrony group is defined
      ansible.builtin.getent:
        database: group
        key: chrony
      ignore_errors: true
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_groupowner_etc_chrony_keys_newgroup is undefined
      tags:
      - configure_strategy
      - file_groupowner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_etc_chrony_keys_newgroup variable if chrony found
      ansible.builtin.set_fact:
        file_groupowner_etc_chrony_keys_newgroup: chrony
      when:
      - '"linux-base" in ansible_facts.packages'
      - ansible_facts.getent_group["chrony"] is defined
      tags:
      - configure_strategy
      - file_groupowner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/chrony.keys
      ansible.builtin.stat:
        path: /etc/chrony.keys
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupowner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/chrony.keys
      ansible.builtin.file:
        path: /etc/chrony.keys
        follow: false
        group: '{{ file_groupowner_etc_chrony_keys_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_groupowner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify User Who Owns /etc/chrony.keys File [ref]

To properly set the owner of `/etc/chrony.keys`, run the command:

    $ sudo chown root /etc/chrony.keys

Rationale: | The ownership of the /etc/chrony.keys file by the chrony user is important because this file hosts chrony cryptographic keys. Protection of this file is critical for system security. Assigning the ownership to chrony ensures exclusive control of the chrony cryptographic keys.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_etc_chrony_keys

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/chrony.keys" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/chrony.keys
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_owner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_etc_chrony_keys_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_etc_chrony_keys_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/chrony.keys
      ansible.builtin.stat:
        path: /etc/chrony.keys
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_owner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/chrony.keys
      ansible.builtin.file:
        path: /etc/chrony.keys
        follow: false
        owner: '{{ file_owner_etc_chrony_keys_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_owner_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions On /etc/chrony.keys File [ref]

To properly set the permissions of `/etc/chrony.keys`, run the command:

    $ sudo chmod 0640 /etc/chrony.keys

Rationale: | Setting correct permissions on the /etc/chrony.keys file is important because this file hosts chrony cryptographic keys. Protection of this file is critical for system security. Assigning the correct mode ensures exclusive control of the chrony cryptographic keys.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_etc_chrony_keys

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xs,g-xws,o-xwrt /etc/chrony.keys

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_permissions_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/chrony.keys
      ansible.builtin.stat:
        path: /etc/chrony.keys
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_permissions_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xws,o-xwrt on /etc/chrony.keys
      ansible.builtin.file:
        path: /etc/chrony.keys
        mode: u-xs,g-xws,o-xwrt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - configure_strategy
      - file_permissions_etc_chrony_keys
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Obsolete Services Group contains 6 groups and 11 rules

[ref] This section discusses a number of network-visible services which have historically caused problems for system security, and for which disabling or severely limiting the service has been the best available guidance for some time. As a result of this, many of these services are not installed as part of Debian 13 by default.
Organizations which are running these services should switch to more secure equivalents as soon as possible. If it remains absolutely necessary to run one of these services for legacy reasons, care should be taken to restrict the service as much as possible, for instance by configuring host firewall software such as `iptables` to restrict access to the vulnerable service to only those remote hosts which have a known need to use it.

Group Xinetd Group contains 1 rule
[ref] The `xinetd` service acts as a dedicated listener for some network services (mostly, obsolete ones) and can be used to provide access controls and perform some logging. It has been largely obsoleted by other features, and it is not installed by default. The older Inetd service is not even available as part of Debian 13.

#### Rule Uninstall xinetd Package [ref]

The `xinetd` package can be removed with the following command:

    $ apt-get remove xinetd

Rationale: | Removing the `xinetd` package decreases the risk of the xinetd service's accidental (or intentional) activation.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_xinetd_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
anssi | R62
ism | 1409
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # CAUTION: This remediation script will remove xinetd
    # from the system, and may remove any packages
    # that depend on xinetd. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "xinetd"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_xinetd

    class remove_xinetd {
      package { 'xinetd':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_xinetd_removed

    - name: 'Uninstall xinetd Package: Ensure xinetd is removed'
      ansible.builtin.package:
        name: xinetd
        state: absent
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_xinetd_removed

Group NIS Group contains 2 rules
[ref] The Network Information Service (NIS), also known as 'Yellow Pages' (YP), and its successor NIS+ have been made obsolete by Kerberos, LDAP, and other modern centralized authentication services. NIS should not be used because it suffers from security problems inherent in its design, such as inadequate protection of important authentication information.

#### Rule Remove NIS Client [ref]

The Network Information Service (NIS), formerly known as Yellow Pages, is a client-server directory service protocol used to distribute system configuration files. The NIS client (`ypbind`) was used to bind a system to an NIS server and receive the distributed configuration files.
Rationale: | The NIS service is inherently an insecure system that has been vulnerable to DOS attacks, buffer overflows and has poor authentication for querying NIS maps. NIS generally has been replaced by such protocols as Lightweight Directory Access Protocol (LDAP). It is recommended that the service be removed.
Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_ypbind_removed

References:

hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
anssi | R62
ism | 1409
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove ypbind
    # from the system, and may remove any packages
    # that depend on ypbind. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "ypbind"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_ypbind

    class remove_ypbind {
      package { 'ypbind':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Remove NIS Client: Ensure ypbind is removed'
      ansible.builtin.package:
        name: ypbind
        state: absent
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_ypbind_removed
      - unknown_severity

#### Rule Uninstall ypserv Package [ref]

The `ypserv` package can be removed with the following command:

    $ apt-get remove ypserv

Rationale: | The NIS service provides an unencrypted authentication service which does not provide for the confidentiality and integrity of user passwords or the remote session. Removing the `ypserv` package decreases the risk of the accidental (or intentional) activation of NIS or NIS+ services.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_ypserv_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a), IA-5(1)(c)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-2.2.2
os-srg | SRG-OS-000095-GPOS-00049
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove ypserv
    # from the system, and may remove any packages
    # that depend on ypserv. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "ypserv"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_ypserv

    class remove_ypserv {
      package { 'ypserv':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall ypserv Package: Ensure ypserv is removed'
      ansible.builtin.package:
        name: ypserv
        state: absent
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-IA-5(1)(c)
      - PCI-DSS-Req-2.2.2
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_ypserv_removed

Group Rlogin, Rsh, and Rexec Group contains 2 rules
[ref] The Berkeley r-commands are legacy services which allow cleartext remote access and have an insecure trust model.

#### Rule Uninstall rsh-server Package [ref]

The `rsh-server` package can be removed with the following command:

    $ apt-get remove rsh-server

Rationale:

The `rsh-server` service provides unencrypted remote access service which does not provide for the confidentiality and integrity of user passwords or the remote session and has very weak authentication. If a privileged user were to login using this service, the privileged user password could be compromised. The `rsh-server` package provides several obsolete and insecure network services. Removing it decreases the risk of those services' accidental (or intentional) activation.

Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsh-server_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a), IA-5(1)(c)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000095-GPOS-00049
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove rsh-server
    # from the system, and may remove any packages
    # that depend on rsh-server. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "rsh-server"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_rsh-server

    class remove_rsh-server {
      package { 'rsh-server':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall rsh-server Package: Ensure rsh-server is removed'
      ansible.builtin.package:
        name: rsh-server
        state: absent
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-IA-5(1)(c)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_rsh-server_removed

#### Rule Uninstall rsh Package [ref]

The `rsh` package contains the client commands for the rsh services

Rationale:

These legacy clients contain numerous security exposures and have been replaced with the more secure SSH package. Even if the server is removed, it is best to ensure the clients are also removed to prevent users from inadvertently attempting to use these commands and therefore exposing their credentials. Note that removing the `rsh` package removes the clients for `rsh`,`rcp`, and `rlogin`.

Severity: | unknown
Rule ID: | xccdf_org.ssgproject.content_rule_package_rsh_removed

References:

cui | 3.1.13
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
iso27001-2013 | A.8.2.3, A.13.1.1, A.13.2.1, A.13.2.3, A.14.1.2, A.14.1.3
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove rsh
    # from the system, and may remove any packages
    # that depend on rsh. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "rsh"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_rsh

    class remove_rsh {
      package { 'rsh':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall rsh Package: Ensure rsh is removed'
      ansible.builtin.package:
        name: rsh
        state: absent
      tags:
      - NIST-800-171-3.1.13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_rsh_removed
      - unknown_severity

Group Chat/Messaging Services Group contains 2 rules
[ref] The talk software makes it possible for users to send and receive messages across systems through a terminal session.

#### Rule Uninstall talk-server Package [ref]

The `talk-server` package can be removed with the following command:

     $ apt-get remove talk-server

Rationale: | The talk software presents a security risk as it uses unencrypted protocols for communications. Removing the `talk-server` package decreases the risk of the accidental (or intentional) activation of talk services.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_talk-server_removed

References:

hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove talk-server
    # from the system, and may remove any packages
    # that depend on talk-server. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "talk-server"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_talk-server

    class remove_talk-server {
      package { 'talk-server':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall talk-server Package: Ensure talk-server is removed'
      ansible.builtin.package:
        name: talk-server
        state: absent
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_talk-server_removed

#### Rule Uninstall talk Package [ref]

The `talk` package contains the client program for the Internet talk protocol, which allows the user to chat with other users on different systems. Talk is a communication program which copies lines from one terminal to the terminal of another user. The `talk` package can be removed with the following command:

    $ apt-get remove talk

Rationale: | The talk software presents a security risk as it uses unencrypted protocols for communications. Removing the `talk` package decreases the risk of the accidental (or intentional) activation of talk client program.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_talk_removed

References:

hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove talk
    # from the system, and may remove any packages
    # that depend on talk. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "talk"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_talk

    class remove_talk {
      package { 'talk':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall talk Package: Ensure talk is removed'
      ansible.builtin.package:
        name: talk
        state: absent
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_talk_removed

Group Telnet Group contains 2 rules
[ref] The telnet protocol does not provide confidentiality or integrity for information transmitted on the network. This includes authentication information such as passwords. Organizations which use telnet should be actively working to migrate to a more secure protocol.

#### Rule Uninstall telnet-server Package [ref]

The `telnet-server` package can be removed with the following command:

    $ apt-get remove telnet-server

Rationale:

It is detrimental for operating systems to provide, or install by default, functionality exceeding requirements or mission objectives. These unnecessary capabilities are often overlooked and therefore may remain insecure. They increase the risk to the platform by providing additional attack vectors.
The telnet service provides an unencrypted remote access service which does not provide for the confidentiality and integrity of user passwords or the remote session. If a privileged user were to login using this service, the privileged user password could be compromised.
Removing the `telnet-server` package decreases the risk of the telnet service's accidental (or intentional) activation.

Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_telnet-server_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
pcidss | Req-2.2.2
os-srg | SRG-OS-000095-GPOS-00049
anssi | R62
ism | 1409
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove telnet-server
    # from the system, and may remove any packages
    # that depend on telnet-server. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "telnet-server"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_telnet-server

    class remove_telnet-server {
      package { 'telnet-server':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall telnet-server Package: Ensure telnet-server is removed'
      ansible.builtin.package:
        name: telnet-server
        state: absent
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSS-Req-2.2.2
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_telnet-server_removed

#### Rule Remove telnet Clients [ref]

The telnet client allows users to start connections to other systems via the telnet protocol.
Rationale: | The `telnet` protocol is insecure and unencrypted. The use of an unencrypted transmission medium could allow an unauthorized user to steal credentials. The `ssh` package provides an encrypted session and stronger security and is included in Debian 13.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_telnet_removed

References:

cui | 3.1.13
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
iso27001-2013 | A.8.2.3, A.13.1.1, A.13.2.1, A.13.2.3, A.14.1.2, A.14.1.3
anssi | R62
ism | 1409
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove telnet
    # from the system, and may remove any packages
    # that depend on telnet. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "telnet"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_telnet

    class remove_telnet {
      package { 'telnet':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Remove telnet Clients: Ensure telnet is removed'
      ansible.builtin.package:
        name: telnet
        state: absent
      tags:
      - NIST-800-171-3.1.13
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_telnet_removed

Group TFTP Server Group contains 2 rules
[ref] TFTP is a lightweight version of the FTP protocol which has traditionally been used to configure networking equipment. However, TFTP provides little security, and modern versions of networking operating systems frequently support configuration via SSH or other more secure protocols. A TFTP server should be run only if no more secure method of supporting existing equipment can be found.

#### Rule Uninstall tftp-server Package [ref]

The `tftp-server` package can be removed with the following command:

     $ apt-get remove tftp-server

Rationale: | Removing the `tftp-server` package decreases the risk of the accidental (or intentional) activation of tftp services. If TFTP is required for operational support (such as transmission of router configurations), its use must be documented with the Information Systems Security Manager (ISSM), restricted to only authorized personnel, and have access control rules established.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_package_tftp-server_removed

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove tftp-server
    # from the system, and may remove any packages
    # that depend on tftp-server. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "tftp-server"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_tftp-server

    class remove_tftp-server {
      package { 'tftp-server':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Uninstall tftp-server Package: Ensure tftp-server is removed'
      ansible.builtin.package:
        name: tftp-server
        state: absent
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - high_severity
      - low_complexity
      - low_disruption
      - no_reboot_needed
      - package_tftp-server_removed

#### Rule Remove tftp Daemon [ref]

Trivial File Transfer Protocol (TFTP) is a simple file transfer protocol, typically used to automatically transfer configuration or boot files between systems. TFTP does not support authentication and can be easily hacked. The package `tftp` is a client program that allows for connections to a `tftp` server.
Rationale: | It is recommended that TFTP be removed, unless there is a specific need for TFTP (such as a boot server). In that case, use extreme caution when configuring the services.
Severity: | low
Rule ID: | xccdf_org.ssgproject.content_rule_package_tftp_removed

References:

os-srg | SRG-OS-000074-GPOS-00042
anssi | R62
pcidss4 | 2.2.4, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    # CAUTION: This remediation script will remove tftp
    # from the system, and may remove any packages
    # that depend on tftp. Execute this
    # remediation AFTER testing on a non-production
    # system!

    DEBIAN_FRONTEND=noninteractive apt-get remove -y "tftp"

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    include remove_tftp

    class remove_tftp {
      package { 'tftp':
        ensure => 'purged',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | disable

    - name: 'Remove tftp Daemon: Ensure tftp is removed'
      ansible.builtin.package:
        name: tftp
        state: absent
      tags:
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.4
      - disable_strategy
      - low_complexity
      - low_disruption
      - low_severity
      - no_reboot_needed
      - package_tftp_removed

Group SSH Server Group contains 1 group and 10 rules

[ref] The SSH protocol is recommended for remote login and remote file transfer. SSH provides confidentiality and integrity for data exchanged between two systems, as well as server authentication, through the use of public key cryptography. The implementation included with the system is called OpenSSH, and more detailed documentation is available from its website, https://www.openssh.com. Its server program is called `sshd` and provided by the RPM package `openssh-server`.

Group Configure OpenSSH Server if Necessary Group contains 1 rule
[ref] If the system needs to act as an SSH server, then certain changes should be made to the OpenSSH daemon configuration file `/etc/ssh/sshd_config`. The following recommendations can be applied to this file. See the `sshd_config(5)` man page for more detailed information.

#### Rule Disable SSH Root Login [ref]

The root user should never be allowed to login to a system directly over a network. To disable root login via SSH, add or correct the following line in `/etc/ssh/sshd_config`:

    PermitRootLogin no

Rationale: | Even though the communications channel may be encrypted, an additional layer of security is gained by extending the policy of not logging directly on as root. In addition, logging in with a user-specific account provides individual accountability of actions performed on the system and also helps to minimize direct attack attempts on root's password.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sshd_disable_root_login

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 3, 5
cjis | 5.5.6
cobit5 | APO01.06, DSS05.02, DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.02, DSS06.03, DSS06.06, DSS06.10
cui | 3.1.1, 3.1.5
hipaa | 164.308(a)(4)(i), 164.308(b)(1), 164.308(b)(3), 164.310(b), 164.312(e)(1), 164.312(e)(2)(ii)
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.18.1.4, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.2.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2, CIP-007-3 R5.2, CIP-007-3 R5.3.1, CIP-007-3 R5.3.2, CIP-007-3 R5.3.3
nist | AC-6(2), AC-17(a), IA-2, IA-2(5), CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-1, PR.AC-4, PR.AC-6, PR.AC-7, PR.DS-5, PR.PT-3
ospp | FAU_GEN.1
pcidss | Req-2.2.4
os-srg | SRG-OS-000109-GPOS-00056, SRG-OS-000480-GPOS-00227
app-srg-ctr | SRG-APP-000148-CTR-000335, SRG-APP-000190-CTR-000500
anssi | R33
ism | 1546
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    if [ -e "/etc/ssh/sshd_config" ] ; then

        LC_ALL=C sed -i "/^\s*PermitRootLogin\s\+/Id" "/etc/ssh/sshd_config"
    else
        touch "/etc/ssh/sshd_config"
    fi
    # make sure file has newline at the end
    sed -i -e '$a\' "/etc/ssh/sshd_config"

    cp "/etc/ssh/sshd_config" "/etc/ssh/sshd_config.bak"
    # Insert at the beginning of the file
    printf '%s\n' "PermitRootLogin no" > "/etc/ssh/sshd_config"
    cat "/etc/ssh/sshd_config.bak" >> "/etc/ssh/sshd_config"
    # Clean up after ourselves.
    rm "/etc/ssh/sshd_config.bak"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.5.6
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(2)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-IA-2
      - NIST-800-53-IA-2(5)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_root_login

    - name: Disable SSH Root Login
      block:

      - name: Check for duplicate values
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*PermitRootLogin\s+
          state: absent
        check_mode: true
        changed_when: false
        register: dupes

      - name: Deduplicate values from /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*PermitRootLogin\s+
          state: absent
        when: dupes.found is defined and dupes.found > 1

      - name: Insert correct line to /etc/ssh/sshd_config
        ansible.builtin.lineinfile:
          path: /etc/ssh/sshd_config
          create: true
          regexp: (?i)(?i)^\s*PermitRootLogin\s+
          line: PermitRootLogin no
          state: present
          insertbefore: BOF
          validate: /usr/sbin/sshd -t -f %s
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.5.6
      - NIST-800-171-3.1.1
      - NIST-800-171-3.1.5
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(2)
      - NIST-800-53-CM-6(a)
      - NIST-800-53-CM-7(a)
      - NIST-800-53-CM-7(b)
      - NIST-800-53-IA-2
      - NIST-800-53-IA-2(5)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
      - sshd_disable_root_login

#### Rule Verify Group Who Owns SSH Server config file [ref]

To properly set the group owner of `/etc/ssh/sshd_config`, run the command:

    $ sudo chgrp root /etc/ssh/sshd_config

Rationale: | Service configuration files enable or disable features of their respective services that if configured incorrectly can lead to insecure and vulnerable configurations. Therefore, service configuration files should be owned by the correct group to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupowner_sshd_config

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    if ! stat -c "%g %G" "/etc/ssh/sshd_config" | grep -E -w -q "0"; then
        chgrp --no-dereference "$newgroup" /etc/ssh/sshd_config
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupowner_sshd_config_newgroup variable if represented by gid
      ansible.builtin.set_fact:
        file_groupowner_sshd_config_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ssh/sshd_config
      ansible.builtin.stat:
        path: /etc/ssh/sshd_config
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ssh/sshd_config
      ansible.builtin.file:
        path: /etc/ssh/sshd_config
        follow: false
        group: '{{ file_groupowner_sshd_config_newgroup }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_groupowner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Ownership on SSH Server Private *_key Key Files [ref]

SSH server private keys, files that match the `/etc/ssh/*_key` glob, must be group-owned by `root` group. Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.
Rationale: | If an unauthorized user obtains the private SSH host key file, the host could be impersonated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownership_sshd_private_key

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    find -P /etc/ssh/ -maxdepth 1 -type f  ! -group 0 -regextype posix-extended -regex '^.*_key$' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownership_sshd_private_key_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupownership_sshd_private_key_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/ file(s) matching ^.*_key$
      ansible.builtin.command: find -P /etc/ssh/ -maxdepth 1 -type f  ! -group 0 -regextype
        posix-extended -regex "^.*_key$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ssh/ file(s) matching ^.*_key$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownership_sshd_private_key_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Group Ownership on SSH Server Public *.pub Key Files [ref]

SSH server public keys, files that match the `/etc/ssh/*.pub` glob, must be group-owned by `root` group. Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.
Rationale: | If a public host key file is modified by an unauthorized user, the SSH service may be compromised.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_groupownership_sshd_pub_key

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newgroup=""
    if getent group "0" >/dev/null 2>&1; then
      newgroup="0"
    fi

    if [[ -z "${newgroup}" ]]; then
      >&2 echo "0 is not a defined group on the system"
    else
    find -P /etc/ssh/ -maxdepth 1 -type f  ! -group 0 -regextype posix-extended -regex '^.*\.pub$' -exec chgrp --no-dereference "$newgroup" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_groupownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_groupownership_sshd_pub_key_newgroup variable if represented
        by gid
      ansible.builtin.set_fact:
        file_groupownership_sshd_pub_key_newgroup: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/ file(s) matching ^.*\.pub$
      ansible.builtin.command: find -P /etc/ssh/ -maxdepth 1 -type f  ! -group 0 -regextype
        posix-extended -regex "^.*\.pub$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure group owner on /etc/ssh/ file(s) matching ^.*\.pub$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        group: '{{ file_groupownership_sshd_pub_key_newgroup }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_groupownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Owner on SSH Server config file [ref]

To properly set the owner of `/etc/ssh/sshd_config`, run the command:

    $ sudo chown root /etc/ssh/sshd_config

Rationale: | Service configuration files enable or disable features of their respective services that if configured incorrectly can lead to insecure and vulnerable configurations. Therefore, service configuration files should be owned by the correct group to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_owner_sshd_config

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else
    if ! stat -c "%u %U" "/etc/ssh/sshd_config" | grep -E -w -q "0"; then
        chown --no-dereference "$newown" /etc/ssh/sshd_config
    fi

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_owner_sshd_config_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_owner_sshd_config_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ssh/sshd_config
      ansible.builtin.stat:
        path: /etc/ssh/sshd_config
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/ssh/sshd_config
      ansible.builtin.file:
        path: /etc/ssh/sshd_config
        follow: false
        owner: '{{ file_owner_sshd_config_newown }}'
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - configure_strategy
      - file_owner_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Ownership on SSH Server Private *_key Key Files [ref]

SSH server private keys, files that match the `/etc/ssh/*_key` glob, must be owned by `root` user. Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.
Rationale: | If an unauthorized user obtains the private SSH host key file, the host could be impersonated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_sshd_private_key

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else

    find -P /etc/ssh/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*_key$' -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_ownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_ownership_sshd_private_key_newown variable if represented by
        uid
      ansible.builtin.set_fact:
        file_ownership_sshd_private_key_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/ file(s) matching ^.*_key$
      ansible.builtin.command: find -P /etc/ssh/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex "^.*_key$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/ssh/ file(s) matching ^.*_key$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_sshd_private_key_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Ownership on SSH Server Public *.pub Key Files [ref]

SSH server public keys, files that match the `/etc/ssh/*.pub` glob, must be owned by `root` user. Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.
Rationale: | If a public host key file is modified by an unauthorized user, the SSH service may be compromised.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_ownership_sshd_pub_key

References:

anssi | R50

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    newown=""
    if id "0" >/dev/null 2>&1; then
      newown="0"
    fi

    if [[ -z "$newown" ]]; then
      >&2 echo "0 is not a defined user on the system"
    else

    find -P /etc/ssh/ -maxdepth 1 -type f  ! -user 0 -regextype posix-extended -regex '^.*\.pub$' -exec chown --no-dereference "$newown" {} \;

    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - configure_strategy
      - file_ownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set the file_ownership_sshd_pub_key_newown variable if represented by uid
      ansible.builtin.set_fact:
        file_ownership_sshd_pub_key_newown: '0'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/ file(s) matching ^.*\.pub$
      ansible.builtin.command: find -P /etc/ssh/ -maxdepth 1 -type f  ! -user 0 -regextype
        posix-extended -regex "^.*\.pub$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure owner on /etc/ssh/ file(s) matching ^.*\.pub$
      ansible.builtin.file:
        path: '{{ item }}'
        follow: false
        owner: '{{ file_ownership_sshd_pub_key_newown }}'
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - configure_strategy
      - file_ownership_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on SSH Server config file [ref]

To properly set the permissions of `/etc/ssh/sshd_config`, run the command:

    $ sudo chmod 0600 /etc/ssh/sshd_config

Rationale: | Service configuration files enable or disable features of their respective services that if configured incorrectly can lead to insecure and vulnerable configurations. Therefore, service configuration files should be owned by the correct group to prevent unauthorized changes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_sshd_config

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    chmod u-xs,g-xwrs,o-xwrt /etc/ssh/sshd_config

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Test for existence /etc/ssh/sshd_config
      ansible.builtin.stat:
        path: /etc/ssh/sshd_config
      register: file_exists
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure permission u-xs,g-xwrs,o-xwrt on /etc/ssh/sshd_config
      ansible.builtin.file:
        path: /etc/ssh/sshd_config
        mode: u-xs,g-xwrs,o-xwrt
      when:
      - '"linux-base" in ansible_facts.packages'
      - file_exists.stat is defined and file_exists.stat.exists
      tags:
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_config
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on SSH Server Private *_key Key Files [ref]

SSH server private keys - files that match the `/etc/ssh/*_key` glob, have to have restricted permissions. If those files are owned by the `root` user and the `root` group, they have to have the `0600` permission or stricter. Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.
Rationale: | If an unauthorized user obtains the private SSH host key file, the host could be impersonated.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_sshd_private_key

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.13, 3.13.10
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-2.2.4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
ism | 1449
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    for keyfile in /etc/ssh/*_key; do
        test -f "$keyfile" || continue
        if test root:root = "$(stat -c "%U:%G" "$keyfile")"; then

    	chmod u-xs,g-xwrs,o-xwrt "$keyfile"

        else
            echo "Key-like file '$keyfile' is owned by an unexpected user:group combination"
        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

    include ssh_private_key_perms

    class ssh_private_key_perms {
      exec { 'sshd_priv_key':
        command => "chmod 0640 /etc/ssh/*_key",
        path    => '/bin:/usr/bin'
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find root:root-owned keys
      ansible.builtin.command: find -H /etc/ssh/ -maxdepth 1 -user root -regex ".*_key$"
        -type f -group root -perm /u+xs,g+xwrs,o+xwrt
      register: root_owned_keys
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for root:root-owned keys
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xwrs,o-xwrt
        state: file
      with_items:
      - '{{ root_owned_keys.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_private_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Verify Permissions on SSH Server Public *.pub Key Files [ref]

To properly set the permissions of `/etc/ssh/*.pub`, run the command:

    $ sudo chmod 0644 /etc/ssh/*.pub

Warning: Remediation is not possible at bootable container build time because SSH host keys are generated post-deployment.

Rationale: | If a public host key file is modified by an unauthorized user, the SSH service may be compromised.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_file_permissions_sshd_pub_key

References:

cis-csc | 12, 13, 14, 15, 16, 18, 3, 5
cobit5 | APO01.06, DSS05.04, DSS05.07, DSS06.02
cui | 3.1.13, 3.13.10
isa-62443-2009 | 4.3.3.7.3
isa-62443-2013 | SR 2.1, SR 5.2
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nerc-cip | CIP-003-8 R5.1.1, CIP-003-8 R5.3, CIP-004-6 R2.3, CIP-007-3 R2.1, CIP-007-3 R2.2, CIP-007-3 R2.3, CIP-007-3 R5.1, CIP-007-3 R5.1.1, CIP-007-3 R5.1.2
nist | AC-17(a), CM-6(a), AC-6(1)
nist-csf | PR.AC-4, PR.DS-5
pcidss | Req-2.2.4
os-srg | SRG-OS-000480-GPOS-00227
anssi | R50
pcidss4 | 2.2.6, 2.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    find -P /etc/ssh/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type f -regextype posix-extended -regex '^.*\.pub$' -exec chmod u-xs,g-xws,o-xwt {} \;

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

    include ssh_public_key_perms

    class ssh_public_key_perms {
      exec { 'sshd_pub_key':
        command => "chmod 0644 /etc/ssh/*.pub",
        path    => '/bin:/usr/bin'
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Find /etc/ssh/ file(s)
      ansible.builtin.command: find -P /etc/ssh/ -maxdepth 1 -perm /u+xs,g+xws,o+xwt  -type
        f -regextype posix-extended -regex "^.*\.pub$"
      register: files_found
      changed_when: false
      failed_when: false
      check_mode: false
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Set permissions for /etc/ssh/ file(s)
      ansible.builtin.file:
        path: '{{ item }}'
        mode: u-xs,g-xws,o-xwt
        state: file
      with_items:
      - '{{ files_found.stdout_lines }}'
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.13
      - NIST-800-171-3.13.10
      - NIST-800-53-AC-17(a)
      - NIST-800-53-AC-6(1)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-2.2.4
      - PCI-DSSv4-2.2
      - PCI-DSSv4-2.2.6
      - configure_strategy
      - file_permissions_sshd_pub_key
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group System Security Services Daemon Group contains 1 group and 5 rules

[ref] The System Security Services Daemon (SSSD) is a system daemon that provides access to different identity and authentication providers such as Red Hat's IdM, Microsoft's AD, openLDAP, MIT Kerberos, etc. It uses a common framework that can provide caching and offline support to systems utilizing SSSD. SSSD using caching to reduce load on authentication servers permit offline authentication as well as store extended user data.
For more information, see

Group System Security Services Daemon (SSSD) - LDAP Group contains 2 rules

[ref] The System Security Services Daemon (SSSD) is a system daemon that provides access to different identity and authentication providers such as Red Hat's IdM, Microsoft's AD, openLDAP, MIT Kerberos, etc. It uses a common framework that can provide caching and offline support to systems utilizing SSSD. SSSD using caching to reduce load on authentication servers permit offline authentication as well as store extended user data.
SSSD can support many backends including LDAP. The `sssd-ldap` backend allows SSSD to fetch identity information from an LDAP server.

#### Rule Configure SSSD LDAP Backend Client to Demand a Valid Certificate from the Server [ref]

Configure SSSD to demand a valid certificate from the server to protect the integrity of LDAP remote access sessions by setting the

    ldap_tls_reqcert

option in

    /etc/sssd/sssd.conf

to `demand`.

Rationale: | Without a valid certificate presented to the LDAP client backend, the identity of a server can be forged compromising LDAP remote access sessions.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_ldap_configure_tls_reqcert

References:

nist | SC-12(3), CM-6(a)
os-srg | SRG-OS-000250-GPOS-00093
anssi | R67

#### Rule Configure SSSD LDAP Backend to Use TLS For All Transactions [ref]

The LDAP client should be configured to implement TLS for the integrity of all remote LDAP authentication sessions. If the `id_provider` is set to `ldap` or `ipa` in `/etc/sssd/sssd.conf` or any of the `/etc/sssd/sssd.conf.d` configuration files, `ldap_id_use_start_tls` must be set to `true`.
To check if LDAP is configured to use TLS when `id_provider` is set to `ldap` or `ipa`, use the following command:

    $ sudo grep -i ldap_id_use_start_tls /etc/sssd/sssd.conf /etc/sssd/conf.d/*.conf

Rationale: | Without cryptographic integrity protections, information can be altered by unauthorized users without detection. The ssl directive specifies whether to use TLS or not. If not specified it will default to no. It should be set to start_tls rather than doing LDAP over SSL.
Severity: | high
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_ldap_start_tls

References:

cis-csc | 11, 12, 14, 15, 3, 8, 9
cobit5 | APO13.01, BAI10.01, BAI10.02, BAI10.03, BAI10.05, DSS01.04, DSS05.02, DSS05.03, DSS05.05, DSS06.06
isa-62443-2009 | 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.3, 4.3.3.5.4, 4.3.3.5.5, 4.3.3.5.6, 4.3.3.5.7, 4.3.3.5.8, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.1, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.3.2, 4.3.4.3.3
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.11, SR 1.12, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.6, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.2, SR 2.3, SR 2.4, SR 2.5, SR 2.6, SR 2.7, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.1.2, A.12.5.1, A.12.6.2, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.2, A.14.2.3, A.14.2.4, A.6.2.1, A.6.2.2, A.9.1.2
nist | CM-7(a), CM-7(b), CM-6(a)
nist-csf | PR.AC-3, PR.IP-1, PR.PT-3, PR.PT-4
os-srg | SRG-OS-000250-GPOS-00093
anssi | R67

#### Rule Install the SSSD Package [ref]

The `sssd` package should be installed. The `sssd` package can be installed with the following command:

    $ apt-get install sssd

Rationale: |
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_sssd_installed

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000375-GPOS-00160
anssi | R67

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'sssd-common' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "sssd"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_sssd

    class install_sssd {
      package { 'sssd':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sssd_installed

    - name: Ensure sssd is installed
      ansible.builtin.package:
        name: sssd
        state: present
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_sssd_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "sssd"
    version = "*"

#### Rule Enable the SSSD Service [ref]

The SSSD service should be enabled. The `sssd` service can be enabled with the following command:

    $ sudo systemctl enable sssd.service

Warning: The service requires a valid sssd configuration. If the configuration is not present, the service will fail to start and consequently this rule will be reported as failing. The configuration shipped in your distribution package might not be sufficient. Manual modification of configuration files might be required.

Rationale: |
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_sssd_enabled

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | CM-6(a), IA-5(10)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000375-GPOS-00160
anssi | R67

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'sssd-common' 2>/dev/null | grep -q '^installed$' && { ( dpkg-query --show --showformat='${db:Status-Status}' 'sssd-common' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' ); }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'sssd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'sssd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'sssd.service'

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include enable_sssd

    class enable_sssd {
      service {'sssd':
        enable => true,
        ensure => 'running',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(10)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_sssd_enabled

    - name: Enable the SSSD Service - Enable service sssd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable the SSSD Service - Enable Service sssd
        ansible.builtin.systemd:
          name: sssd
          enabled: true
          state: started
          masked: false
        when:
        - '"sssd-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-5(10)
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_sssd_enabled
      - special_service_block
      when:
      - '"sssd-common" in ansible_facts.packages'
      - ( "sssd-common" in ansible_facts.packages and "linux-base" in ansible_facts.packages
        )

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["sssd"]

#### Rule Configure PAM in SSSD Services [ref]

SSSD should be configured to run SSSD `pam` services. To configure SSSD to known SSH hosts, add `pam` to `services` under the `[sssd]` section in `/etc/sssd/sssd.conf`. For example:

    [sssd]
    services = sudo, autofs, pam

Rationale: | Using an authentication device, such as a CAC or token that is separate from the information system, ensures that even if the information system is compromised, that compromise will not affect credentials stored on the authentication device.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_sssd_enable_pam_services

References:

cis-csc | 1, 12, 15, 16, 5
cobit5 | DSS05.04, DSS05.05, DSS05.07, DSS05.10, DSS06.03, DSS06.10
isa-62443-2009 | 4.3.3.2.2, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.6.1, 4.3.3.6.2, 4.3.3.6.3, 4.3.3.6.4, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.3.6.9, 4.3.3.7.2, 4.3.3.7.4
isa-62443-2013 | SR 1.1, SR 1.10, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1
iso27001-2013 | A.18.1.4, A.7.1.1, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.2, A.9.4.3
nist | IA-2(1), CM-6(a)
nist-csf | PR.AC-1, PR.AC-6, PR.AC-7
os-srg | SRG-OS-000375-GPOS-00160, SRG-OS-000376-GPOS-00161, SRG-OS-000377-GPOS-00162
anssi | R67

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | medium
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

    - name: Configure PAM in SSSD Services - Find all the conf files inside the /etc/sssd/conf.d/
        directory
      ansible.builtin.find:
        paths:
        - /etc/sssd/conf.d/
        patterns: '*.conf'
      register: sssd_conf_d_files
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

    - name: Configure PAM in SSSD Services - Modify lines in files in the /etc/sssd/conf.d/
        directory
      ansible.builtin.replace:
        path: '{{ item }}'
        regexp: ^(\s*\[sssd\].*(?:\n\s*[^[\s].*)*\n\s*services\s*=(?!.*\bpam\b).*)$
        replace: \1,pam
      with_items: '{{ sssd_conf_d_files.files | map(attribute=''path'') }}'
      register: modify_lines_sssd_conf_d_files
      when:
      - '"sssd-common" in ansible_facts.packages'
      - sssd_conf_d_files.matched is defined and sssd_conf_d_files.matched >= 1
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

    - name: Configure PAM in SSSD Services - Find /etc/sssd/sssd.conf
      ansible.builtin.stat:
        path: /etc/sssd/sssd.conf
      register: sssd_conf_file
      when: '"sssd-common" in ansible_facts.packages'
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

    - name: Configure PAM in SSSD Services - Modify lines in /etc/sssd/sssd.conf
      ansible.builtin.replace:
        path: /etc/sssd/sssd.conf
        regexp: ^(\s*\[sssd\].*(?:\n\s*[^[\s].*)*\n\s*services\s*=(?!.*\bpam\b).*)$
        replace: \1,pam
      register: modify_lines_sssd_conf_file
      when:
      - '"sssd-common" in ansible_facts.packages'
      - sssd_conf_file.stat.exists
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

    - name: Configure PAM in SSSD Services - Find services key in /etc/sssd/sssd.conf
      ansible.builtin.replace:
        path: /etc/sssd/sssd.conf
        regexp: ^\s*\[sssd\][^\[\]]*?(?:\n(?!\[)[^\n]*?services\s*=)+
        replace: ''
      changed_when: false
      check_mode: true
      register: sssd_conf_file_services
      when:
      - '"sssd-common" in ansible_facts.packages'
      - sssd_conf_file.stat.exists
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

    - name: Configure PAM in SSSD Services - Insert entry to /etc/sssd/sssd.conf
      community.general.ini_file:
        path: /etc/sssd/sssd.conf
        section: sssd
        option: services
        value: pam
      when:
      - '"sssd-common" in ansible_facts.packages'
      - not modify_lines_sssd_conf_d_files.changed
      - not modify_lines_sssd_conf_file.changed
      - (sssd_conf_file_services.msg is defined and "replacements" not in sssd_conf_file_services.msg)
        or not sssd_conf_file.stat.exists
      tags:
      - NIST-800-53-CM-6(a)
      - NIST-800-53-IA-2(1)
      - configure_strategy
      - low_complexity
      - medium_disruption
      - medium_severity
      - no_reboot_needed
      - sssd_enable_pam_services

Group System Accounting with auditd Group contains 8 groups and 54 rules

[ref] The audit service provides substantial capabilities for recording system activities. By default, the service audits about SELinux AVC denials and certain types of security-relevant events such as system logins, account modifications, and authentication events performed by programs such as sudo. Under its default configuration, `auditd` has modest disk space requirements, and should not noticeably impact system performance.
NOTE: The Linux Audit daemon `auditd` can be configured to use the `augenrules` program to read audit rules files (`*.rules`) located in `/etc/audit/rules.d` location and compile them to create the resulting form of the `/etc/audit/audit.rules` configuration file during the daemon startup (default configuration). Alternatively, the `auditd` daemon can use the `auditctl` utility to read audit rules from the `/etc/audit/audit.rules` configuration file during daemon startup, and load them into the kernel. The expected behavior is configured via the appropriate `ExecStartPost` directive setting in the `/usr/lib/systemd/system/auditd.service` configuration file. To instruct the `auditd` daemon to use the `augenrules` program to read audit rules (default configuration), use the following setting:

    ExecStartPost=-/sbin/augenrules --load

in the `/usr/lib/systemd/system/auditd.service` configuration file. In order to instruct the `auditd` daemon to use the `auditctl` utility to read audit rules, use the following setting:

    ExecStartPost=-/sbin/auditctl -R /etc/audit/audit.rules

in the `/usr/lib/systemd/system/auditd.service` configuration file. Refer to `[Service]` section of the `/usr/lib/systemd/system/auditd.service` configuration file for further details.
Government networks often have substantial auditing requirements and `auditd` can be configured to meet these requirements. Examining some example audit records demonstrates how the Linux audit system satisfies common requirements. The following example from Red Hat Enterprise Linux 7 Documentation available at `https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html-single/selinux_users_and_administrators_guide/index#sect-Security-Enhanced_Linux-Fixing_Problems-Raw_Audit_Messages` shows the substantial amount of information captured in a two typical "raw" audit messages, followed by a breakdown of the most important fields. In this example the message is SELinux-related and reports an AVC denial (and the associated system call) that occurred when the Apache HTTP Server attempted to access the `/var/www/html/file1` file (labeled with the `samba_share_t` type):

    type=AVC msg=audit(1226874073.147:96): avc:  denied  { getattr } for pid=2465 comm="httpd"
    path="/var/www/html/file1" dev=dm-0 ino=284133 scontext=unconfined_u:system_r:httpd_t:s0
    tcontext=unconfined_u:object_r:samba_share_t:s0 tclass=file

    type=SYSCALL msg=audit(1226874073.147:96): arch=40000003 syscall=196 success=no exit=-13
    a0=b98df198 a1=bfec85dc a2=54dff4 a3=2008171 items=0 ppid=2463 pid=2465 auid=502 uid=48
    gid=48 euid=48 suid=48 fsuid=48 egid=48 sgid=48 fsgid=48 tty=(none) ses=6 comm="httpd"
    exe="/usr/sbin/httpd" subj=unconfined_u:system_r:httpd_t:s0 key=(null)

- `msg=audit(1226874073.147:96)`
  - The number in parentheses is the unformatted time stamp (Epoch time) for the event, which can be converted to standard time by using the `date` command.
- `{ getattr }`
  - The item in braces indicates the permission that was denied. `getattr` indicates the source process was trying to read the target file's status information. This occurs before reading files. This action is denied due to the file being accessed having the wrong label. Commonly seen permissions include `getattr`, `read`, and `write`.
- `comm="httpd"`
  - The executable that launched the process. The full path of the executable is found in the `exe=` section of the system call (`SYSCALL`) message, which in this case, is `exe="/usr/sbin/httpd"`.
- `path="/var/www/html/file1"`
  - The path to the object (target) the process attempted to access.
- `scontext="unconfined_u:system_r:httpd_t:s0"`
  - The SELinux context of the process that attempted the denied action. In this case, it is the SELinux context of the Apache HTTP Server, which is running in the `httpd_t` domain.
- `tcontext="unconfined_u:object_r:samba_share_t:s0"`
  - The SELinux context of the object (target) the process attempted to access. In this case, it is the SELinux context of `file1`. Note: the `samba_share_t` type is not accessible to processes running in the `httpd_t` domain.
- From the system call (`SYSCALL`) message, two items are of interest:
  - `success=no`: indicates whether the denial (AVC) was enforced or not. `success=no` indicates the system call was not successful (SELinux denied access). `success=yes` indicates the system call was successful - this can be seen for permissive domains or unconfined domains, such as `initrc_t` and `kernel_t`.
  - `exe="/usr/sbin/httpd"`: the full path to the executable that launched the process, which in this case, is `exe="/usr/sbin/httpd"`.

Group Configure auditd Rules for Comprehensive Auditing Group contains 7 groups and 52 rules

[ref] The `auditd` program can perform comprehensive monitoring of system activity. This section describes recommended configuration settings for comprehensive auditing, but a full description of the auditing system's capabilities is beyond the scope of this guide. The mailing list linux-audit@redhat.com exists to facilitate community discussion of the auditing system.
The audit subsystem supports extensive collection of events, including:

- Tracing of arbitrary system calls (identified by name or number) on entry or exit.
- Filtering by PID, UID, call success, system call argument (with some limitations), etc.
- Monitoring of specific files for modifications to the file's contents or metadata.

Auditing rules at startup are controlled by the file `/etc/audit/audit.rules`. Add rules to it to meet the auditing requirements for your organization. Each line in `/etc/audit/audit.rules` represents a series of arguments that can be passed to `auditctl` and can be individually tested during runtime. See documentation in `/usr/share/doc/audit-VERSION` and in the related man pages for more details.
If copying any example audit rulesets from `/usr/share/doc/audit-VERSION`, be sure to comment out the lines containing `arch=` which are not appropriate for your system's architecture. Then review and understand the following rules, ensuring rules are activated as needed for the appropriate architecture.
After reviewing all the rules, reading the following sections, and editing as needed, the new rules can be activated as follows:

    $ sudo service auditd restart

Group Record Events that Modify the System's Discretionary Access Controls Group contains 14 rules

[ref] At a minimum, the audit system should collect file permission changes for all users and root. Note that the "-F arch=b32" lines should be present even on a 64 bit system. These commands identify system calls for auditing. Even if the system is 64 bit it can still execute 32 bit system calls. Additionally, these rules can be configured in a number of ways while still achieving the desired effect. An example of this is that the "-S" calls could be split up and placed on separate lines, however, this is less efficient. Add the following to `/etc/audit/audit.rules`:

    -a always,exit -F arch=b32 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

        -a always,exit -F arch=b32 -S chown,fchown,fchownat,lchown -F auid>=1000 -F auid!=unset -F key=perm_mod
        -a always,exit -F arch=b32 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If your system is 64 bit then these lines should be duplicated and the arch=b32 replaced with arch=b64 as follows:

    -a always,exit -F arch=b64 -S chmod,fchmod,fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

        -a always,exit -F arch=b64 -S chown,fchown,fchownat,lchown -F auid>=1000 -F auid!=unset -F key=perm_mod
        -a always,exit -F arch=b64 -S setxattr,lsetxattr,fsetxattr,removexattr,lremovexattr,fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

#### Rule Record Events that Modify the System's Discretionary Access Controls - chmod [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chmod -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_chmod

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
ism | 0582
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="chmod"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chmod fchmod fchmodat"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit chmod tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for chmod for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of chmod in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of chmod in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for chmod for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of chmod in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of chmod in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - chown [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S chown -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_chown

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
ism | 0582
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="chown"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chown fchown fchownat lchown"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit chown tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for chown for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of chown in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of chown in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for chown for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of chown in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - chown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of chown in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_chown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchmod [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmod -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchmod

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="fchmod"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chmod fchmod fchmodat"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit fchmod tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchmod for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmod in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmod in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchmod for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmod in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmod
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmod in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmod
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchmodat [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchmodat -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchmodat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="fchmodat"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chmod fchmod fchmodat"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmodat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit fchmodat tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmodat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchmodat for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmodat
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmodat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmodat
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmodat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmodat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchmodat for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmodat
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmodat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchmodat
          syscall_grouping:
          - chmod
          - fchmod
          - fchmodat

      - name: Check existence of fchmodat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchmodat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchown [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchown -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchown

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="fchown"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chown fchown fchownat lchown"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit fchown tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchown for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchown in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchown in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchown for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchown in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchown in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fchownat [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fchownat -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fchownat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="fchownat"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chown fchown fchownat lchown"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchownat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit fchownat tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchownat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchownat for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchownat
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchownat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchownat
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchownat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchownat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fchownat for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchownat
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchownat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fchownat
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of fchownat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fchownat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fremovexattr [ref]

At a minimum, the audit system should collect file permission changes for all users and root.
If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fremovexattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000466-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="fremovexattr"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="fremovexattr lremovexattr removexattr fsetxattr lsetxattr setxattr"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit fremovexattr tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fremovexattr for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fremovexattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fremovexattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fremovexattr for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fremovexattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fremovexattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - fsetxattr [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S fsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S fsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S fsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_fsetxattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000466-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="fsetxattr"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="fremovexattr lremovexattr removexattr fsetxattr lsetxattr setxattr"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit fsetxattr tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fsetxattr for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fsetxattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fsetxattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for fsetxattr for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fsetxattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - fsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of fsetxattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_fsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - lchown [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lchown -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_lchown

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000466-GPOS-00210, SRG-OS-000458-GPOS-00203, SRG-OS-000474-GPOS-00219
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="lchown"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="chown fchown fchownat lchown"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit lchown tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for lchown for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of lchown in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of lchown in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for lchown for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of lchown in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lchown
          syscall_grouping:
          - chown
          - fchown
          - fchownat
          - lchown

      - name: Check existence of lchown in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lchown
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - lremovexattr [ref]

At a minimum, the audit system should collect file permission changes for all users and root.
If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S lremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S lremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lremovexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_lremovexattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000466-GPOS-00210, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="lremovexattr"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="fremovexattr lremovexattr removexattr fsetxattr lsetxattr setxattr"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit lremovexattr tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for lremovexattr for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lremovexattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lremovexattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for lremovexattr for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lremovexattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lremovexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lremovexattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lremovexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - lsetxattr [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S lsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S lsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S lsetxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_lsetxattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000466-GPOS-00210, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="lsetxattr"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="fremovexattr lremovexattr removexattr fsetxattr lsetxattr setxattr"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit lsetxattr tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for lsetxattr for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lsetxattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lsetxattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for lsetxattr for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lsetxattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - lsetxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of lsetxattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_lsetxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - removexattr [ref]

At a minimum, the audit system should collect file permission changes for all users and root.
If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S removexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S removexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S removexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S removexattr -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_removexattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000458-GPOS-00203, SRG-OS-000462-GPOS-00206, SRG-OS-000463-GPOS-00207, SRG-OS-000468-GPOS-00212, SRG-OS-000471-GPOS-00215, SRG-OS-000474-GPOS-00219, SRG-OS-000466-GPOS-00210, SRG-OS-000064-GPOS-00033
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="removexattr"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="fremovexattr lremovexattr removexattr fsetxattr lsetxattr setxattr"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_removexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit removexattr tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_removexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for removexattr for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - removexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of removexattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - removexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of removexattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_removexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for removexattr for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - removexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of removexattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - removexattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of removexattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_removexattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - setxattr [ref]

At a minimum, the audit system should collect file permission changes for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S setxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S setxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S setxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S setxattr -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_setxattr

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000466-GPOS-00210, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203
app-srg-ctr | SRG-APP-000091-CTR-000160, SRG-APP-000492-CTR-001220, SRG-APP-000493-CTR-001225, SRG-APP-000494-CTR-001230, SRG-APP-000500-CTR-001260, SRG-APP-000507-CTR-001295, SRG-APP-000495-CTR-001235
anssi | R73
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="setxattr"
    	KEY="perm_mod"
    	SYSCALL_GROUPING="fremovexattr lremovexattr removexattr fsetxattr lsetxattr setxattr"

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_setxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit setxattr tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_setxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for setxattr for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - setxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of setxattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - setxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of setxattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_setxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for setxattr for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - setxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of setxattr in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - setxattr
          syscall_grouping:
          - fremovexattr
          - lremovexattr
          - removexattr
          - fsetxattr
          - lsetxattr
          - setxattr

      - name: Check existence of setxattr in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_dac_modification_setxattr
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Discretionary Access Controls - umount2 [ref]

At a minimum, the audit system should collect file system umount2 changes. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S umount2 -F auid>=1000 -F auid!=unset -F key=perm_mod

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | The changing of file permissions could indicate that a user is attempting to gain access to information that would otherwise be disallowed. Auditing DAC modifications can facilitate the identification of patterns of abuse among both authorized and unauthorized users.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_dac_modification_umount2

References:

os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="umount2"
    	KEY="perm_mod"
    	SYSCALL_GROUPING=""

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit umount2 tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for umount2 for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for umount2 for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/perm_mod.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/perm_mod.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - umount2
          syscall_grouping: []

      - name: Check existence of umount2 in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=perm_mod
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - audit_rules_dac_modification_umount2
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

Group Record File Deletion Events by User Group contains 5 rules

[ref] At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir,unlink,unlinkat,rename,renameat,renameat2 -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir,unlink,unlinkat,rename,renameat,renameat2 -F auid>=1000 -F auid!=unset -F key=delete

#### Rule Ensure auditd Collects File Deletion Events by User - rename [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rename -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rename -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_rename

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="rename"
    	KEY="delete"
    	SYSCALL_GROUPING="unlink unlinkat rename renameat renameat2 rmdir"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rename
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit rename tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rename
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for rename for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rename
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rename in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rename
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rename in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rename
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for rename for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rename
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rename in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rename
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rename in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rename
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - renameat [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S renameat -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S renameat -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_renameat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="renameat"
    	KEY="delete"
    	SYSCALL_GROUPING="unlink unlinkat rename renameat renameat2 rmdir"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_renameat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit renameat tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_renameat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for renameat for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - renameat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of renameat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - renameat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of renameat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_renameat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for renameat for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - renameat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of renameat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - renameat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of renameat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_renameat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - rmdir [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S rmdir -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_rmdir

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="rmdir"
    	KEY="delete"
    	SYSCALL_GROUPING="unlink unlinkat rename renameat renameat2 rmdir"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit rmdir tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for rmdir for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for rmdir for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - rmdir
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of rmdir in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_rmdir
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - unlink [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlink -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlink -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_unlink

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="unlink"
    	KEY="delete"
    	SYSCALL_GROUPING="unlink unlinkat rename renameat renameat2 rmdir"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlink
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit unlink tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlink
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for unlink for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlink
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlink in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlink
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlink in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlink
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for unlink for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlink
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlink in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlink
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlink in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlink
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects File Deletion Events by User - unlinkat [ref]

At a minimum, the audit system should collect file deletion events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlinkat -F auid>=1000 -F auid!=unset -F key=delete

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S unlinkat -F auid>=1000 -F auid!=unset -F key=delete

Rationale: | Auditing file deletions will create an audit trail for files that are removed from the system. The audit trail could aid in system troubleshooting, as well as, detecting malicious processes that attempt to delete log files to conceal their presence.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_file_deletion_events_unlinkat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.5, 4.3.3.6.6, 4.3.3.6.7, 4.3.3.6.8, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.4, A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.1.1, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.MA-2, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000467-GPOS-00211, SRG-OS-000468-GPOS-00212
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000501-CTR-001265, SRG-APP-000502-CTR-001270
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="unlinkat"
    	KEY="delete"
    	SYSCALL_GROUPING="unlink unlinkat rename renameat renameat2 rmdir"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlinkat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit unlinkat tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlinkat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for unlinkat for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlinkat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlinkat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlinkat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlinkat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlinkat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for unlinkat for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlinkat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlinkat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/delete.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/delete.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - unlinkat
          syscall_grouping:
          - unlink
          - unlinkat
          - rename
          - renameat
          - renameat2
          - rmdir

      - name: Check existence of unlinkat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=delete
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_file_deletion_events_unlinkat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

Group Record Unauthorized Access Attempts Events to Files (unsuccessful) Group contains 5 rules

[ref] At a minimum, the audit system should collect unauthorized file accesses for all users and root. Note that the "-F arch=b32" lines should be present even on a 64 bit system. These commands identify system calls for auditing. Even if the system is 64 bit it can still execute 32 bit system calls. Additionally, these rules can be configured in a number of ways while still achieving the desired effect. An example of this is that the "-S" calls could be split up and placed on separate lines, however, this is less efficient. Add the following to `/etc/audit/audit.rules`:

    -a always,exit -F arch=b32 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
        -a always,exit -F arch=b32 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If your system is 64 bit then these lines should be duplicated and the arch=b32 replaced with arch=b64 as follows:

    -a always,exit -F arch=b64 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
        -a always,exit -F arch=b64 -S creat,open,openat,open_by_handle_at,truncate,ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

#### Rule Record Unsuccessful Access Attempts to Files - creat [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S creat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S creat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_creat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL="creat"
    KEY="access"
    SYSCALL_GROUPING="creat ftruncate truncate open openat open_by_handle_at"

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EACCES"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EPERM"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit creat tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for creat EACCES for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for creat EACCES for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for creat EPERM for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for creat EPERM for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - creat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of creat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_creat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - ftruncate [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S ftruncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_ftruncate

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL="ftruncate"
    KEY="access"
    SYSCALL_GROUPING="creat ftruncate truncate open openat open_by_handle_at"

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EACCES"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EPERM"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit ftruncate tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for ftruncate EACCES for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for ftruncate EACCES for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for ftruncate EPERM for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for ftruncate EPERM for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - ftruncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of ftruncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_ftruncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - open [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S open -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S open -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_open

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( ( grep -sqE "^.*\.aarch64$" /proc/sys/kernel/osrelease || grep -sqE "^aarch64$" /proc/sys/kernel/arch; ) ); }; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL="open"
    KEY="access"
    SYSCALL_GROUPING="creat ftruncate truncate open openat open_by_handle_at"

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EACCES"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EPERM"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_open
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit open tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_open
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open EACCES for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_open
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open EACCES for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_open
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open EPERM for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_open
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for open EPERM for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - open
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of open in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_architecture == "aarch64" )
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_open
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - openat [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S openat -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S openat -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_openat

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL="openat"
    KEY="access"
    SYSCALL_GROUPING="creat ftruncate truncate open openat open_by_handle_at"

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EACCES"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EPERM"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit openat tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for openat EACCES for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for openat EACCES for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for openat EPERM for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for openat EPERM for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - openat
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of openat in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_openat
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Unsuccessful Access Attempts to Files - truncate [ref]

At a minimum, the audit system should collect unauthorized file accesses for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b32 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

If the system is 64 bit then also add the following lines:

    -a always,exit -F arch=b64 -S truncate -F exit=-EACCES -F auid>=1000 -F auid!=unset -F key=access
    -a always,exit -F arch=b64 -S truncate -F exit=-EPERM -F auid>=1000 -F auid!=unset -F key=access

Warning: Note that these rules can be configured in a number of ways while still achieving the desired effect. Here the system calls have been placed independent of other system calls. Grouping these system calls with others as identifying earlier in this guide is more efficient.

Rationale: | Unsuccessful attempts to access files could be an indicator of malicious activity on a system. Auditing these events could serve as evidence of potential system compromise.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_unsuccessful_file_modification_truncate

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.4, Req-10.2.1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000064-GPOS-00033, SRG-OS-000458-GPOS-00203, SRG-OS-000461-GPOS-00205
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
ism | 0582, 0846

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL="truncate"
    KEY="access"
    SYSCALL_GROUPING="creat ftruncate truncate open openat open_by_handle_at"

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EACCES"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F exit=-EPERM"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit truncate tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for truncate EACCES for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for truncate EACCES for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EACCES -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EACCES -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EACCES
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for truncate EPERM for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for truncate EPERM for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/access.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/access.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - truncate
          syscall_grouping:
          - creat
          - ftruncate
          - truncate
          - open
          - openat
          - open_by_handle_at

      - name: Check existence of truncate in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F exit=-EPERM -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F exit=-EPERM -F auid>=1000 -F auid!=unset
            (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F exit=-EPERM
            -F auid>=1000 -F auid!=unset -F key=access
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.1
      - PCI-DSS-Req-10.2.4
      - audit_rules_unsuccessful_file_modification_truncate
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

Group Record Information on Kernel Modules Loading and Unloading Group contains 3 rules

[ref] To capture kernel module loading and unloading events, use following lines, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S init_module,delete_module -F key=modules

Place to add the lines depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the lines to file `/etc/audit/audit.rules`.

#### Rule Ensure auditd Collects Information on Kernel Module Unloading - delete_module [ref]

To capture kernel module loading and unloading events, use the following line, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S delete_module -F key=modules

Place to add the line depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the line to file `/etc/audit/audit.rules`.

Rationale: | The removal of kernel modules can be used to alter the behavior of the kernel and potentially introduce malicious code into kernel space. It is important to have an audit trail of modules that have been introduced into the kernel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_kernel_module_loading_delete

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000504-CTR-001280
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    # Note: 32-bit and 64-bit kernel syscall numbers not always line up =>
    #       it's required on a 64-bit system to check also for the presence
    #       of 32-bit's equivalent of the corresponding rule.
    #       (See `man 7 audit.rules` for details )
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""

    	AUID_FILTERS=""

    	SYSCALL="delete_module"
    	KEY="modules"
    	SYSCALL_GROUPING="create_module delete_module finit_module init_module query_module"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_delete
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Unloading - delete_module
        - Set architecture for audit ['delete_module'] tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_delete
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Unloading - delete_module
        - Perform remediation of Audit rules for ['delete_module'] for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - delete_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of delete_module in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/modules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/modules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - delete_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of delete_module in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_delete
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Unloading - delete_module
        - Perform remediation of Audit rules for ['delete_module'] for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - delete_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of delete_module in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/modules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/modules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - delete_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of delete_module in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_delete
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure auditd Collects Information on Kernel Module Loading and Unloading - finit_module [ref]

To capture kernel module loading and unloading events, use the following line, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S finit_module -F key=modules

Place to add the line depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the line to file `/etc/audit/audit.rules`.

Rationale: | The addition/removal of kernel modules can be used to alter the behavior of the kernel and potentially introduce malicious code into kernel space. It is important to have an audit trail of modules that have been introduced into the kernel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_kernel_module_loading_finit

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000504-CTR-001280
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    # Note: 32-bit and 64-bit kernel syscall numbers not always line up =>
    #       it's required on a 64-bit system to check also for the presence
    #       of 32-bit's equivalent of the corresponding rule.
    #       (See `man 7 audit.rules` for details )
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""

    	AUID_FILTERS=""

    	SYSCALL="finit_module"
    	KEY="modules"
    	SYSCALL_GROUPING="create_module delete_module finit_module init_module query_module"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_finit
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading and Unloading
        - finit_module - Set architecture for audit ['finit_module'] tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_finit
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading and Unloading
        - finit_module - Perform remediation of Audit rules for ['finit_module'] for 32bit
        platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - finit_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of finit_module in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/modules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/modules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - finit_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of finit_module in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_finit
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading and Unloading
        - finit_module - Perform remediation of Audit rules for ['finit_module'] for 64bit
        platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - finit_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of finit_module in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/modules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/modules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - finit_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of finit_module in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_finit
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure auditd Collects Information on Kernel Module Loading - init_module [ref]

To capture kernel module loading and unloading events, use the following line, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S init_module -F key=modules

Place to add the line depends on a way `auditd` daemon is configured. If it is configured to use the `augenrules` program (the default), add the line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`. If the `auditd` daemon is configured to use the `auditctl` utility, add the line to file `/etc/audit/audit.rules`.

Rationale: | The addition of kernel modules can be used to alter the behavior of the kernel and potentially introduce malicious code into kernel space. It is important to have an audit trail of modules that have been introduced into the kernel.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_kernel_module_loading_init

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000504-CTR-001280
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    # Note: 32-bit and 64-bit kernel syscall numbers not always line up =>
    #       it's required on a 64-bit system to check also for the presence
    #       of 32-bit's equivalent of the corresponding rule.
    #       (See `man 7 audit.rules` for details )
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""

    	AUID_FILTERS=""

    	SYSCALL="init_module"
    	KEY="modules"
    	SYSCALL_GROUPING="create_module delete_module finit_module init_module query_module"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_init
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading - init_module
        - Set architecture for audit ['init_module'] tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_init
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading - init_module
        - Perform remediation of Audit rules for ['init_module'] for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - init_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of init_module in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/modules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/modules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - init_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of init_module in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_init
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on Kernel Module Loading - init_module
        - Perform remediation of Audit rules for ['init_module'] for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - init_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of init_module in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/modules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/modules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - init_module
          syscall_grouping:
          - create_module
          - delete_module
          - finit_module
          - init_module
          - query_module

      - name: Check existence of init_module in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=modules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - audit_rules_kernel_module_loading_init
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

Group Record Attempts to Alter Logon and Logout Events Group contains 2 rules

[ref] The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d` in order to watch for attempted manual edits of files involved in storing logon events:

    -w /var/log/tallylog -p wa -k logins
    -w /var/log/faillock -p wa -k logins
    -w /var/log/lastlog -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file in order to watch for unattempted manual edits of files involved in storing logon events:

    -w /var/log/tallylog -p wa -k logins
    -w /var/log/faillock -p wa -k logins
    -w /var/log/lastlog -p wa -k logins

#### Rule Record Attempts to Alter Logon and Logout Events - faillock [ref]

The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/faillock -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/faillock -p wa -k logins

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_login_events_faillock

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.3
os-srg | SRG-OS-000392-GPOS-00172, SRG-OS-000470-GPOS-00214, SRG-OS-000473-GPOS-00218
app-srg-ctr | SRG-APP-000503-CTR-001275, SRG-APP-000506-CTR-001290
anssi | R73
ism | 0582
pcidss4 | 10.2.1.3, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    var_accounts_passwords_pam_faillock_dir='/var/log/faillock'

    # 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 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')

    # 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]+${var_accounts_passwords_pam_faillock_dir}" "$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\+${var_accounts_passwords_pam_faillock_dir} $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 "wa" | 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\+${var_accounts_passwords_pam_faillock_dir}$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 ${var_accounts_passwords_pam_faillock_dir} -p wa -k logins" >> "$audit_rules_file"

        fi
    done
    # 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 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/logins.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+${var_accounts_passwords_pam_faillock_dir}" /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/logins.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/logins.rules"
        # If the logins.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

    # 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]+${var_accounts_passwords_pam_faillock_dir}" "$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\+${var_accounts_passwords_pam_faillock_dir} $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 "wa" | 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\+${var_accounts_passwords_pam_faillock_dir}$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 ${var_accounts_passwords_pam_faillock_dir} -p wa -k logins" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy
    - name: XCCDF Value var_accounts_passwords_pam_faillock_dir # promote to variable
      set_fact:
        var_accounts_passwords_pam_faillock_dir: !!str /var/log/faillock
      tags:
        - always

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Check if watch
        rule for {{ var_accounts_passwords_pam_faillock_dir }} already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+{{ var_accounts_passwords_pam_faillock_dir }}\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Search /etc/audit/rules.d
        for other rules with specified key logins
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)logins$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Use /etc/audit/rules.d/logins.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/logins.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Use matched
        file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Add watch rule
        for {{ var_accounts_passwords_pam_faillock_dir }} in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w {{ var_accounts_passwords_pam_faillock_dir }} -p wa -k logins
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Check if watch
        rule for {{ var_accounts_passwords_pam_faillock_dir }} already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+{{ var_accounts_passwords_pam_faillock_dir }}\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - faillock - Add watch rule
        for {{ var_accounts_passwords_pam_faillock_dir }} in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w {{ var_accounts_passwords_pam_faillock_dir }} -p wa -k logins
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_faillock
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Logon and Logout Events - lastlog [ref]

The audit system already collects login information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/lastlog -p wa -k logins

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/lastlog -p wa -k logins

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_login_events_lastlog

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.3
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000473-GPOS-00218, SRG-OS-000470-GPOS-00214
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000503-CTR-001275, SRG-APP-000506-CTR-001290
anssi | R73
ism | 0582
pcidss4 | 10.2.1.3, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/var/log/lastlog" "$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\+/var/log/lastlog $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 "wa" | 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\+/var/log/lastlog$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 /var/log/lastlog -p wa -k logins" >> "$audit_rules_file"

        fi
    done
    # 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 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/logins.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/var/log/lastlog" /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/logins.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/logins.rules"
        # If the logins.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

    # 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]+/var/log/lastlog" "$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\+/var/log/lastlog $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 "wa" | 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\+/var/log/lastlog$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 /var/log/lastlog -p wa -k logins" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Check if watch
        rule for /var/log/lastlog already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/log/lastlog\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Search /etc/audit/rules.d
        for other rules with specified key logins
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)logins$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Use /etc/audit/rules.d/logins.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/logins.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Use matched file
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Add watch rule
        for /var/log/lastlog in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/log/lastlog -p wa -k logins
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Check if watch
        rule for /var/log/lastlog already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/log/lastlog\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Logon and Logout Events - lastlog - Add watch rule
        for /var/log/lastlog in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/log/lastlog -p wa -k logins
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.3
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_login_events_lastlog
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

Group Record Information on the Use of Privileged Commands Group contains 6 rules
[ref] At a minimum, the audit system should collect the execution of privileged commands for all users and root.

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands [ref]

The audit system should collect information about usage of privileged commands for all users. These are commands with suid or sgid bits on and they are specially risky in local block device partitions not mounted with noexec and nosuid options. Therefore, these partitions should be first identified by the following command:

    findmnt -n -l -k -it $(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,) | grep -Pv "noexec|nosuid"

For all partitions listed by the previous command, it is necessary to search for setuid / setgid programs using the following command:

    $ sudo find PARTITION -xdev -perm /6000 -type f 2>/dev/null

For each setuid / setgid program identified by the previous command, an audit rule must be present in the appropriate place using the following line structure, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -F path=PROG_PATH -F perm=x -F auid>=1000 -F auid!=unset -F key=privileged

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup, add the line to a file with suffix `.rules` in the `/etc/audit/rules.d` directory, replacing the PROG_PATH part with the full path of that setuid / setgid identified program. If the `auditd` daemon is configured to use the `auditctl` utility instead, add the line to the `/etc/audit/audit.rules` file, also replacing the PROG_PATH part with the full path of that setuid / setgid identified program.
Warning: This rule checks for multiple syscalls related to privileged commands. If needed to check specific privileged commands, other more specific rules should be considered. For example:

- `audit_rules_privileged_commands_su`
- `audit_rules_privileged_commands_umount`
- `audit_rules_privileged_commands_passwd`

Warning: Note that OVAL check and Bash / Ansible remediation of this rule explicitly excludes file systems mounted at `/proc` directory and its subdirectories. It is a virtual file system and it doesn't contain executable applications. At the same time, interacting with this file system during check or remediation caused undesirable errors.

Rationale:

Misuse of privileged functions, either intentionally or unintentionally by authorized users, or by unauthorized external entities that have compromised system accounts, is a serious and ongoing concern that can have significant adverse impacts on organizations. Auditing the use of privileged functions is one way to detect such misuse and identify the risk from insider and advanced persistent threats.
Privileged programs are subject to escalation-of-privilege attacks, which attempt to subvert their normal role of providing some necessary but limited capability. As such, motivation exists to monitor these programs for unusual activity.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_privileged_commands

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO08.04, APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.05, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.5, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.3.4.5.9, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 3.9, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.1, A.16.1.2, A.16.1.3, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.3, A.6.2.1, A.6.2.2
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-2, DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, DE.DP-4, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4, RS.CO-2
pcidss | Req-10.2.2
os-srg | SRG-OS-000327-GPOS-00127
anssi | R73
ism | 0582, 0846

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { ! ( [ -f /.dockerenv ] || [ -f /run/.containerenv ] ); }; then

    ACTION_ARCH_FILTERS="-a always,exit"
    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL=""
    KEY="privileged"
    SYSCALL_GROUPING=""

    function add_audit_rule()
    {
        local PRIV_CMD="$1"
        local OTHER_FILTERS="-F path=$PRIV_CMD -F perm=x"
        # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
        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_GROUPING

        # 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 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

        # 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
        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_GROUPING

        # 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 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' )

        # 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
    }

    if /bin/false ; then
      PRIV_CMDS=$(find / -perm /6000 -type f -not -path "/sysroot/*" 2>/dev/null)
      for PRIV_CMD in $PRIV_CMDS; do
        add_audit_rule $PRIV_CMD
      done
    else
      FILTER_NODEV=$(awk '/nodev/ { print $2 }' /proc/filesystems | paste -sd,)
      PARTITIONS=$(findmnt -n -l -k -it "$FILTER_NODEV" | grep -Pv "noexec|nosuid|/proc($|/.*$)" | awk '{ print $1 }')
      for PARTITION in $PARTITIONS; do
        PRIV_CMDS=$(find "${PARTITION}" -xdev -perm /6000 -type f 2>/dev/null)
        for PRIV_CMD in $PRIV_CMDS; do
          add_audit_rule $PRIV_CMD
        done
      done
    fi

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | configure

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - audit_rules_privileged_commands
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - Set
        List of Mount Points Which Permits Execution of Privileged Commands
      ansible.builtin.set_fact:
        privileged_mount_points: '{{ (ansible_facts.mounts | rejectattr(''options'', ''search'',
          ''noexec|nosuid'') | rejectattr(''mount'', ''match'', ''/proc($|/.*$)'') | map(attribute=''mount'')
          | list ) }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - audit_rules_privileged_commands
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - Search
        for Privileged Commands in Eligible Mount Points
      ansible.builtin.shell:
        cmd: find {{ item }} -xdev -perm /6000 -type f 2>/dev/null
      register: result_privileged_commands_search
      changed_when: false
      failed_when: false
      with_items: '{{ privileged_mount_points }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - audit_rules_privileged_commands
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - Set
        List of Privileged Commands Found in Eligible Mount Points
      ansible.builtin.set_fact:
        privileged_commands: '{{ privileged_commands | default([]) + item.stdout_lines
          }}'
      loop: '{{ result_privileged_commands_search.results }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - item is not skipped
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - audit_rules_privileged_commands
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

    - name: Ensure auditd Collects Information on the Use of Privileged Commands - Privileged
        Commands are Present in the System
      block:

      - name: Ensure auditd Collects Information on the Use of Privileged Commands - Ensure
          Rules for All Privileged Commands in augenrules Format
        ansible.builtin.lineinfile:
          path: /etc/audit/rules.d/privileged.rules
          line: -a always,exit -F path={{ item }} -F perm=x -F auid>=1000 -F auid!=unset
            -F key=privileged
          regexp: ^.*path={{ item | regex_escape() }} .*$
          create: true
        with_items:
        - '{{ privileged_commands }}'

      - name: Ensure auditd Collects Information on the Use of Privileged Commands - Ensure
          Rules for All Privileged Commands in auditctl Format
        ansible.builtin.lineinfile:
          path: /etc/audit/audit.rules
          line: -a always,exit -F path={{ item }} -F perm=x -F auid>=1000 -F auid!=unset
            -F key=privileged
          regexp: ^.*path={{ item | regex_escape() }} .*$
          create: true
        with_items:
        - '{{ privileged_commands }}'

      - name: Ensure auditd Collects Information on the Use of Privileged Commands - Search
          for Duplicated Rules in Other Files
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          recurse: false
          contains: ^-a always,exit -F path={{ item }} .*$
          patterns: '*.rules'
        with_items:
        - '{{ privileged_commands }}'
        register: result_augenrules_files

      - name: Ensure auditd Collects Information on the Use of Privileged Commands - Ensure
          Rules for Privileged Commands are Defined Only in One File
        ansible.builtin.lineinfile:
          path: '{{ item.1.path }}'
          regexp: ^-a always,exit -F path={{ item.0.item }} .*$
          state: absent
        with_subelements:
        - '{{ result_augenrules_files.results }}'
        - files
        when:
        - item.1.path != '/etc/audit/rules.d/privileged.rules'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not ( ansible_virtualization_type in ["docker", "lxc", "openvz", "podman", "container"]
        )
      - privileged_commands is defined
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - audit_rules_privileged_commands
      - configure_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - insmod [ref]

At a minimum, the audit system should collect the execution of privileged commands for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add a line of the following form to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /sbin/insmod -p x -k modules

Rationale:

Misuse of privileged functions, either intentionally or unintentionally by authorized users, or by unauthorized external entities that have compromised system accounts, is a serious and ongoing concern and can have significant adverse impacts on organizations. Auditing the use of privileged functions is one way to detect such misuse and identify the risk from insider and advanced persistent threats.
Privileged programs are subject to escalation-of-privilege attacks, which attempt to subvert their normal role of providing some necessary but limited capability. As such, motivation exists to monitor these programs for unusual activity.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_privileged_commands_insmod

References:

nist | AU-12(c), AU-12.1(iv), AU-3, AU-3.1, AU-12(a), AU-12.1(ii), MA-4(1)(a)
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # 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 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')

    # 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]+/sbin/insmod" "$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\+/sbin/insmod $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 "x" | 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\+/sbin/insmod$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 /sbin/insmod -p x -k modules" >> "$audit_rules_file"

        fi
    done
    # 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 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/modules.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/sbin/insmod" /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/modules.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/modules.rules"
        # If the modules.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

    # 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]+/sbin/insmod" "$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\+/sbin/insmod $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 "x" | 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\+/sbin/insmod$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 /sbin/insmod -p x -k modules" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - kmod [ref]

At a minimum, the audit system should collect the execution of privileged commands for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add a line of the following form to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F path=/usr/bin/kmod -F auid>=1000 -F auid!=unset -F key=privileged

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add a line of the following form to `/etc/audit/audit.rules`:

    -a always,exit -F path=/usr/bin/kmod -F auid>=1000 -F auid!=unset -F key=privileged

Rationale: | Without generating audit records that are specific to the security and mission needs of the organization, it would be difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one. Audit records can be generated from various components within the information system (e.g., module or policy filter).
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_privileged_commands_kmod

References:

nist | AU-3, AU-3.1, AU-12(a), AU-12.1(ii), AU-12.1(iv)AU-12(c), MA-4(1)(a)
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000471-GPOS-00216, SRG-OS-000477-GPOS-00222
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000504-CTR-001280
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/kmod -F perm=x"
    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL=""
    KEY="privileged"
    SYSCALL_GROUPING=""

    ACTION_ARCH_FILTERS="-a always,exit"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    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_GROUPING

    # 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 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

    # 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
    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_GROUPING

    # 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 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' )

    # 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

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - modprobe [ref]

At a minimum, the audit system should collect the execution of privileged commands for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add a line of the following form to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /sbin/modprobe -p x -k modules

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add a line of the following form to `/etc/audit/audit.rules`:

    -w /sbin/modprobe -p x -k modules

Rationale:

Misuse of privileged functions, either intentionally or unintentionally by authorized users, or by unauthorized external entities that have compromised system accounts, is a serious and ongoing concern and can have significant adverse impacts on organizations. Auditing the use of privileged functions is one way to detect such misuse and identify the risk from insider and advanced persistent threats.
Privileged programs are subject to escalation-of-privilege attacks, which attempt to subvert their normal role of providing some necessary but limited capability. As such, motivation exists to monitor these programs for unusual activity.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_privileged_commands_modprobe

References:

nist | AU-12(a), AU-12.1(ii), AU-3, AU-3.1, AU-12(c), AU-12.1(iv), MA-4(1)(a)
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # 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 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')

    # 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]+/sbin/modprobe" "$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\+/sbin/modprobe $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 "x" | 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\+/sbin/modprobe$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 /sbin/modprobe -p x -k modules" >> "$audit_rules_file"

        fi
    done
    # 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 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/modules.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/sbin/modprobe" /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/modules.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/modules.rules"
        # If the modules.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

    # 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]+/sbin/modprobe" "$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\+/sbin/modprobe $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 "x" | 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\+/sbin/modprobe$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 /sbin/modprobe -p x -k modules" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - rmmod [ref]

At a minimum, the audit system should collect the execution of privileged commands for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add a line of the following form to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /sbin/rmmod -p x -k modules

Rationale:

Misuse of privileged functions, either intentionally or unintentionally by authorized users, or by unauthorized external entities that have compromised system accounts, is a serious and ongoing concern and can have significant adverse impacts on organizations. Auditing the use of privileged functions is one way to detect such misuse and identify the risk from insider and advanced persistent threats.
Privileged programs are subject to escalation-of-privilege attacks, which attempt to subvert their normal role of providing some necessary but limited capability. As such, motivation exists to monitor these programs for unusual activity.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_privileged_commands_rmmod

References:

os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
anssi | R73

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # 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 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')

    # 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]+/sbin/rmmod" "$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\+/sbin/rmmod $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 "x" | 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\+/sbin/rmmod$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 /sbin/rmmod -p x -k modules" >> "$audit_rules_file"

        fi
    done
    # 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 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/modules.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/sbin/rmmod" /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/modules.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/modules.rules"
        # If the modules.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

    # 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]+/sbin/rmmod" "$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\+/sbin/rmmod $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 "x" | 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\+/sbin/rmmod$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 /sbin/rmmod -p x -k modules" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

#### Rule Ensure auditd Collects Information on the Use of Privileged Commands - sudo [ref]

At a minimum, the audit system should collect the execution of privileged commands for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add a line of the following form to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F path=/usr/bin/sudo -F auid>=1000 -F auid!=unset -F key=privileged

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add a line of the following form to `/etc/audit/audit.rules`:

    -a always,exit -F path=/usr/bin/sudo -F auid>=1000 -F auid!=unset -F key=privileged

Rationale:

Misuse of privileged functions, either intentionally or unintentionally by authorized users, or by unauthorized external entities that have compromised system accounts, is a serious and ongoing concern and can have significant adverse impacts on organizations. Auditing the use of privileged functions is one way to detect such misuse and identify the risk from insider and advanced persistent threats.
Privileged programs are subject to escalation-of-privilege attacks, which attempt to subvert their normal role of providing some necessary but limited capability. As such, motivation exists to monitor these programs for unusual activity.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_privileged_commands_sudo

References:

cis-csc | 1, 12, 13, 14, 15, 16, 2, 3, 5, 6, 7, 8, 9
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, BAI03.05, DSS01.03, DSS03.05, DSS05.02, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.4.4.7, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 6.1, SR 6.2
iso27001-2013 | A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.14.2.7, A.15.2.1, A.15.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.PT-1
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215, SRG-OS-000466-GPOS-00210, SRG-OS-000755-GPOS-00220
app-srg-ctr | SRG-APP-000029-CTR-000085, SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255
anssi | R33

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Retrieve hardware architecture of the underlying system
    OTHER_FILTERS="-F path=/usr/bin/sudo -F perm=x"
    AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    SYSCALL=""
    KEY="privileged"
    SYSCALL_GROUPING=""

    ACTION_ARCH_FILTERS="-a always,exit"
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    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_GROUPING

    # 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 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

    # 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
    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_GROUPING

    # 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 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' )

    # 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

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Group Records Events that Modify Date and Time Information Group contains 4 rules
[ref] Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time. All changes to the system time should be audited.

#### Rule Record attempts to alter time through adjtimex [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S adjtimex -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S adjtimex -F key=audit_time_rules

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S adjtimex -F key=audit_time_rules

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S adjtimex -F key=audit_time_rules

The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined syscalls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale: | Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_time_adjtimex

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.4.2.b
anssi | R73
ism | 0582
pcidss4 | 10.6.3, 10.6

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # 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'
        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_GROUPING

        # 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 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

        # 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
        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_GROUPING

        # 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 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' )

        # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_adjtimex
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set architecture for audit tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_adjtimex
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for adjtimex for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - adjtimex
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of adjtimex in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/audit_time_rules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/audit_time_rules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F key=audit_time_rules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - adjtimex
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of adjtimex in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F key=audit_time_rules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_adjtimex
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for adjtimex for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - adjtimex
          syscall_grouping:
          - adjtimex
          - settimeofday

      - name: Check existence of adjtimex in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/audit_time_rules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/audit_time_rules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F key=audit_time_rules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - adjtimex
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of adjtimex in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F key=audit_time_rules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_adjtimex
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Time Through clock_settime [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -a always,exit -F arch=b32 -S clock_settime -F a0=0x0 -F key=time-change

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S clock_settime -F a0=0x0 -F key=time-change

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file:

    -a always,exit -F arch=b32 -S clock_settime -F a0=0x0 -F key=time-change

If the system is 64 bit then also add the following line:

    -a always,exit -F arch=b64 -S clock_settime -F a0=0x0 -F key=time-change

The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined syscalls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale: | Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_time_clock_settime

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.4.2.b
anssi | R73
ism | 0582
pcidss4 | 10.6.3, 10.6

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS="-F a0=0x0"
    	AUID_FILTERS=""
    	SYSCALL="clock_settime"
    	KEY="time-change"
    	SYSCALL_GROUPING=""
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_clock_settime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set architecture for audit tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_clock_settime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for clock_settime for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - clock_settime
          syscall_grouping: []

      - name: Check existence of clock_settime in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F a0=0x0 (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/time-change.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/time-change.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F a0=0x0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F a0=0x0 -F
            key=time-change
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - clock_settime
          syscall_grouping: []

      - name: Check existence of clock_settime in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F a0=0x0 (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F a0=0x0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F a0=0x0 -F
            key=time-change
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_clock_settime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for clock_settime for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - clock_settime
          syscall_grouping: []

      - name: Check existence of clock_settime in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F a0=0x0 (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/time-change.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/time-change.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F a0=0x0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F a0=0x0 -F
            key=time-change
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - clock_settime
          syscall_grouping: []

      - name: Check existence of clock_settime in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F a0=0x0 (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F a0=0x0 (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F a0=0x0 -F
            key=time-change
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_clock_settime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Time Through stime [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d` for both 32 bit and 64 bit systems:

    -a always,exit -F arch=b32 -S stime -F key=audit_time_rules

Since the 64 bit version of the "stime" system call is not defined in the audit lookup table, the corresponding "-F arch=b64" form of this rule is not expected to be defined on 64 bit systems (the aforementioned "-F arch=b32" stime rule form itself is sufficient for both 32 bit and 64 bit systems). If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file for both 32 bit and 64 bit systems:

    -a always,exit -F arch=b32 -S stime -F key=audit_time_rules

Since the 64 bit version of the "stime" system call is not defined in the audit lookup table, the corresponding "-F arch=b64" form of this rule is not expected to be defined on 64 bit systems (the aforementioned "-F arch=b32" stime rule form itself is sufficient for both 32 bit and 64 bit systems). The -k option allows for the specification of a key in string form that can be used for better reporting capability through ausearch and aureport. Multiple system calls can be defined on the same line to save space if desired, but is not required. See an example of multiple combined system calls:

    -a always,exit -F arch=b64 -S adjtimex,settimeofday -F key=audit_time_rules

Rationale: | Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_time_stime

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.4.2.b
anssi | R73
ism | 0582
pcidss4 | 10.6.3, 10.6

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_stime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Perform remediation of Audit rules for stime syscall for x86 platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - stime
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of stime in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/audit_time_rules.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/audit_time_rules.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F key=audit_time_rules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - stime
          syscall_grouping:
          - adjtimex
          - settimeofday
          - stime

      - name: Check existence of stime in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F key=audit_time_rules
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ( not ( ansible_architecture == "aarch64" ) and not ( ansible_architecture ==
        "s390x" ) )
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_stime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter the localtime File [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/localtime -p wa -k audit_time_rules

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/localtime -p wa -k audit_time_rules

Rationale: | Arbitrary changes to the system time can be used to obfuscate nefarious activities in log files, as well as to confuse network services that are highly dependent upon an accurate system time (such as sshd). All changes to the system time should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_time_watch_localtime

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.4.2.b
anssi | R73
ism | 0582
pcidss4 | 10.6.3, 10.6

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/localtime" "$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\+/etc/localtime $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 "wa" | 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\+/etc/localtime$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 /etc/localtime -p wa -k audit_time_rules" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_time_rules.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/localtime" /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/audit_time_rules.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_time_rules.rules"
        # If the audit_time_rules.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

    # 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]+/etc/localtime" "$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\+/etc/localtime $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 "wa" | 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\+/etc/localtime$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 /etc/localtime -p wa -k audit_time_rules" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Check if watch rule for /etc/localtime
        already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/localtime\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Search /etc/audit/rules.d for
        other rules with specified key audit_time_rules
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_time_rules$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Use /etc/audit/rules.d/audit_time_rules.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_time_rules.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Use matched file as the recipient
        for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Add watch rule for /etc/localtime
        in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/localtime -p wa -k audit_time_rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Check if watch rule for /etc/localtime
        already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/localtime\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter the localtime File - Add watch rule for /etc/localtime
        in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/localtime -p wa -k audit_time_rules
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.4.2.b
      - PCI-DSSv4-10.6
      - PCI-DSSv4-10.6.3
      - audit_rules_time_watch_localtime
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Make the auditd Configuration Immutable [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d` in order to make the auditd configuration immutable:

    -e 2

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file in order to make the auditd configuration immutable:

    -e 2

With this setting, a reboot will be required to change any audit rules.

Rationale: | Making the audit configuration immutable prevents accidental as well as malicious modification of the audit rules, although it may be problematic if legitimate changes are needed during system operation.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_immutable

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 3, 4, 5, 6, 7, 8
cjis | 5.4.1.1
cobit5 | APO01.06, APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, BAI03.05, BAI08.02, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS05.04, DSS05.07, DSS06.02, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.3.1, 3.4.3
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.310(a)(2)(iv), 164.312(d), 164.310(d)(2)(iii), 164.312(b), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.7.3, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.8, SR 2.9, SR 5.2, SR 6.1
iso27001-2013 | A.10.1.1, A.11.1.4, A.11.1.5, A.11.2.1, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.1.3, A.13.2.1, A.13.2.3, A.13.2.4, A.14.1.2, A.14.1.3, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.7.1.1, A.7.1.2, A.7.3.1, A.8.2.2, A.8.2.3, A.9.1.1, A.9.1.2, A.9.2.3, A.9.4.1, A.9.4.4, A.9.4.5
nist | AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, ID.SC-4, PR.AC-4, PR.DS-5, PR.PT-1, RS.AN-1, RS.AN-4
pcidss | Req-10.5.2
os-srg | SRG-OS-000057-GPOS-00027, SRG-OS-000058-GPOS-00028, SRG-OS-000059-GPOS-00029
app-srg-ctr | SRG-APP-000119-CTR-000245, SRG-APP-000120-CTR-000250
anssi | R73
pcidss4 | 10.3.2, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Traverse all of:
    #
    # /etc/audit/audit.rules,			(for auditctl case)
    # /etc/audit/rules.d/*.rules			(for augenrules case)
    #
    # files to check if '-e .*' setting is present in that '*.rules' file already.
    # If found, delete such occurrence since auditctl(8) manual page instructs the
    # '-e 2' rule should be placed as the last rule in the configuration
    find /etc/audit /etc/audit/rules.d -maxdepth 1 -type f -name '*.rules' -exec sed -i '/-e[[:space:]]\+.*/d' {} ';'

    # Append '-e 2' requirement at the end of both:
    # * /etc/audit/audit.rules file 		(for auditctl case)
    # * /etc/audit/rules.d/immutable.rules		(for augenrules case)

    for AUDIT_FILE in "/etc/audit/audit.rules" "/etc/audit/rules.d/immutable.rules"
    do
    	echo '' >> $AUDIT_FILE
    	echo '# Set the audit.rules configuration immutable per security requirements' >> $AUDIT_FILE
    	echo '# Reboot is required to change audit rules once this setting is applied' >> $AUDIT_FILE
    	echo '-e 2' >> $AUDIT_FILE
    	chmod o-rwx $AUDIT_FILE
    	chmod g-rwx $AUDIT_FILE
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Collect all files from /etc/audit/rules.d
        with .rules extension
      ansible.builtin.find:
        paths: /etc/audit/rules.d/
        patterns: '*.rules'
      register: find_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Check if target files exist and
        get their content
      ansible.builtin.stat:
        path: '{{ item }}'
      register: audit_files_stat
      loop:
      - /etc/audit/audit.rules
      - /etc/audit/rules.d/immutable.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Read content of existing audit files
      ansible.builtin.slurp:
        src: '{{ item.item }}'
      register: audit_files_content
      loop: '{{ audit_files_stat.results }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - item.stat.exists
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Check if -e 2 is already correctly
        set in target files
      ansible.builtin.set_fact:
        immutable_correctly_set: |-
          {{
            audit_files_content.results
            | selectattr('content', 'defined')
            | map(attribute='content')
            | map('b64decode')
            | select('search', '^-e 2$', multiline=True)
            | list
            | length == 2
          }}
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Remove any existing -e option from
        all Audit config files
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        regexp: ^\s*-e\s+.*$
        state: absent
      loop: '{{ find_rules_d.files | map(attribute=''path'') | list + [''/etc/audit/audit.rules'']
        }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not immutable_correctly_set
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Ensure target directories exist
      ansible.builtin.file:
        path: '{{ item | dirname }}'
        state: directory
        mode: '0750'
      loop:
      - /etc/audit/audit.rules
      - /etc/audit/rules.d/immutable.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not immutable_correctly_set
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Make the auditd Configuration Immutable - Add Audit -e 2 option to make rules
        immutable
      ansible.builtin.lineinfile:
        path: '{{ item }}'
        create: true
        line: -e 2
        regexp: ^\s*-e\s+.*$
        mode: g-rwx,o-rwx
      loop:
      - /etc/audit/audit.rules
      - /etc/audit/rules.d/immutable.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - not immutable_correctly_set
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.4.3
      - NIST-800-53-AC-6(9)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.2
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.2
      - audit_rules_immutable
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Ensure auditd Collects Information on Exporting to Media (successful) [ref]

At a minimum, the audit system should collect media exportation events for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following line to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S mount -F auid>=1000 -F auid!=unset -F key=export

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following line to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S mount -F auid>=1000 -F auid!=unset -F key=export

Rationale: | The unauthorized exportation of data to external media could result in an information leak where classified information, Privacy Act information, and intellectual property could be lost. An audit trail should be created each time a filesystem is mounted to help identify and guard against information loss.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_media_export

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.7
os-srg | SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000471-GPOS-00215
app-srg-ctr | SRG-APP-000495-CTR-001235
anssi | R73
pcidss4 | 10.2.1.7, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS="-F auid>=1000 -F auid!=unset"
    	SYSCALL="mount"
    	KEY="export"
    	SYSCALL_GROUPING=""

    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | true
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_media_export
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Set architecture for audit mount tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_media_export
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for mount for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - mount
          syscall_grouping: []

      - name: Check existence of mount in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/export.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/export.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=export
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - mount
          syscall_grouping: []

      - name: Check existence of mount in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=export
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_media_export
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

    - name: Perform remediation of Audit rules for mount for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - mount
          syscall_grouping: []

      - name: Check existence of mount in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/export.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/export.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k
            |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=export
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - mount
          syscall_grouping: []

      - name: Check existence of mount in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* -F auid>=1000 -F auid!=unset (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( -F auid>=1000 -F auid!=unset (?:-k |-F
            key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F auid>=1000
            -F auid!=unset -F key=export
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.7
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.7
      - audit_rules_media_export
      - low_complexity
      - low_disruption
      - medium_severity
      - reboot_required
      - restrict_strategy

#### Rule Record Events that Modify the System's Network Environment [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S sethostname,setdomainname -F key=audit_rules_networkconfig_modification
    -w /etc/issue -p wa -k audit_rules_networkconfig_modification
    -w /etc/issue.net -p wa -k audit_rules_networkconfig_modification
    -w /etc/hosts -p wa -k audit_rules_networkconfig_modification

    -w /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules` file, setting ARCH to either b32 for 32-bit system, or having two lines for both b32 and b64 in case your system is 64-bit:

    -a always,exit -F arch=ARCH -S sethostname,setdomainname -F key=audit_rules_networkconfig_modification
    -w /etc/issue -p wa -k audit_rules_networkconfig_modification
    -w /etc/issue.net -p wa -k audit_rules_networkconfig_modification
    -w /etc/hosts -p wa -k audit_rules_networkconfig_modification
    -w /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification

Rationale: | The network environment should not be modified by anything other than administrator action. Any change to network parameters should be audited.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_networkconfig_modification

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nist | AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.5.5
anssi | R73
ism | 0582
pcidss4 | 10.3.4, 10.3

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # First perform the remediation of the syscall rule
    # Retrieve hardware architecture of the underlying system
    [ "$(getconf LONG_BIT)" = "32" ] && RULE_ARCHS=("b32") || RULE_ARCHS=("b32" "b64")

    for ARCH in "${RULE_ARCHS[@]}"
    do
    	ACTION_ARCH_FILTERS="-a always,exit -F arch=$ARCH"
    	OTHER_FILTERS=""
    	AUID_FILTERS=""
    	SYSCALL="sethostname setdomainname"
    	KEY="audit_rules_networkconfig_modification"
    	SYSCALL_GROUPING="sethostname setdomainname"
    	# Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    	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_GROUPING

    # 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 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

    # 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
    	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_GROUPING

    # 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 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' )

    # 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
    done

    # Then perform the remediations for the watch rules
    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'
    # 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 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')

    # 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]+/etc/issue" "$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\+/etc/issue $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 "wa" | 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\+/etc/issue$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 /etc/issue -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_networkconfig_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/issue" /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/audit_rules_networkconfig_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_networkconfig_modification.rules"
        # If the audit_rules_networkconfig_modification.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

    # 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]+/etc/issue" "$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\+/etc/issue $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 "wa" | 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\+/etc/issue$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 /etc/issue -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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')

    # 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]+/etc/issue.net" "$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\+/etc/issue.net $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 "wa" | 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\+/etc/issue.net$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 /etc/issue.net -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_networkconfig_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/issue.net" /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/audit_rules_networkconfig_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_networkconfig_modification.rules"
        # If the audit_rules_networkconfig_modification.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

    # 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]+/etc/issue.net" "$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\+/etc/issue.net $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 "wa" | 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\+/etc/issue.net$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 /etc/issue.net -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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')

    # 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]+/etc/hosts" "$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\+/etc/hosts $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 "wa" | 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\+/etc/hosts$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 /etc/hosts -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_networkconfig_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/hosts" /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/audit_rules_networkconfig_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_networkconfig_modification.rules"
        # If the audit_rules_networkconfig_modification.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

    # 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]+/etc/hosts" "$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\+/etc/hosts $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 "wa" | 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\+/etc/hosts$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 /etc/hosts -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done

    # 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 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')

    # 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]+/etc/sysconfig/network" "$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\+/etc/sysconfig/network $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 "wa" | 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\+/etc/sysconfig/network$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 /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_networkconfig_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/sysconfig/network" /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/audit_rules_networkconfig_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_networkconfig_modification.rules"
        # If the audit_rules_networkconfig_modification.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

    # 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]+/etc/sysconfig/network" "$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\+/etc/sysconfig/network $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 "wa" | 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\+/etc/sysconfig/network$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 /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Set architecture for audit tasks
      ansible.builtin.set_fact:
        audit_arch: b64
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - ansible_architecture == "aarch64" or ansible_architecture == "ppc64" or ansible_architecture
        == "ppc64le" or ansible_architecture == "s390x" or ansible_architecture == "x86_64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Remediate audit rules for network configuration for 32bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - sethostname
          - setdomainname
          syscall_grouping:
          - sethostname
          - setdomainname

      - name: Check existence of sethostname, setdomainname in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/audit_rules_networkconfig_modification.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/audit_rules_networkconfig_modification.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F key=audit_rules_networkconfig_modification
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - sethostname
          - setdomainname
          syscall_grouping:
          - sethostname
          - setdomainname

      - name: Check existence of sethostname, setdomainname in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b32(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b32)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b32 -S {{ syscalls | join(',') }} -F key=audit_rules_networkconfig_modification
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Remediate audit rules for network configuration for 64bit platform
      block:

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - sethostname
          - setdomainname
          syscall_grouping:
          - sethostname
          - setdomainname

      - name: Check existence of sethostname, setdomainname in /etc/audit/rules.d/
        ansible.builtin.find:
          paths: /etc/audit/rules.d
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-k\s+|-F\s+key=)\S+\s*$
          patterns: '*.rules'
        register: find_command
        loop: '{{ (syscall_grouping + syscalls) | unique }}'

      - name: Reset syscalls found per file
        ansible.builtin.set_fact:
          syscalls_per_file: {}
          found_paths_dict: {}

      - name: Declare syscalls found per file
        ansible.builtin.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
        ansible.builtin.set_fact: found_paths="{{ find_command.results | map(attribute='files')
          | flatten | map(attribute='path') | list }}"

      - name: Count occurrences of syscalls in paths
        ansible.builtin.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
        ansible.builtin.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/audit_rules_networkconfig_modification.rules
        ansible.builtin.set_fact: audit_file="/etc/audit/rules.d/audit_rules_networkconfig_modification.rules"
        when: found_paths | length == 0

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_per_file[audit_file]
            | join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F key=audit_rules_networkconfig_modification
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0

      - name: Declare list of syscalls
        ansible.builtin.set_fact:
          syscalls:
          - sethostname
          - setdomainname
          syscall_grouping:
          - sethostname
          - setdomainname

      - name: Check existence of sethostname, setdomainname in /etc/audit/audit.rules
        ansible.builtin.find:
          paths: /etc/audit
          contains: -a always,exit -F arch=b64(( -S |,)\w+)*(( -S |,){{ item }})+(( -S
            |,)\w+)* (-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
        ansible.builtin.set_fact: audit_file="/etc/audit/audit.rules"

      - name: Declare found syscalls
        ansible.builtin.set_fact: syscalls_found="{{ find_command.results | selectattr('matched')
          | map(attribute='item') | list }}"

      - name: Declare missing syscalls
        ansible.builtin.set_fact: missing_syscalls="{{ syscalls | difference(syscalls_found)
          }}"

      - name: Replace the audit rule in {{ audit_file }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          regexp: (-a always,exit -F arch=b64)(?=.*(?:(?:-S |,)(?:{{ syscalls_found |
            join("|") }}))\b)((?:( -S |,)\w+)+)( (?:-k |-F key=)\w+)
          line: \1\2\3{{ missing_syscalls | join("\3") }}\4
          backrefs: true
          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 }}
        ansible.builtin.lineinfile:
          path: '{{ audit_file }}'
          line: -a always,exit -F arch=b64 -S {{ syscalls | join(',') }} -F key=audit_rules_networkconfig_modification
          create: true
          mode: g-rwx,o-rwx
          state: present
        when: syscalls_found | length == 0
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - audit_arch == "b64"
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/issue already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/issue\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_networkconfig_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_networkconfig_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use matched file
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/issue in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/issue -p wa -k audit_rules_networkconfig_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/issue already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/issue\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/issue in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/issue -p wa -k audit_rules_networkconfig_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/issue.net already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/issue.net\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_networkconfig_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_networkconfig_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use matched file
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/issue.net in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/issue.net -p wa -k audit_rules_networkconfig_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/issue.net already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/issue.net\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/issue.net in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/issue.net -p wa -k audit_rules_networkconfig_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/hosts already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/hosts\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_networkconfig_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_networkconfig_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use matched file
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/hosts in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/hosts -p wa -k audit_rules_networkconfig_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/hosts already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/hosts\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/hosts in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/hosts -p wa -k audit_rules_networkconfig_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/sysconfig/network already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/sysconfig/network\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_networkconfig_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_networkconfig_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_networkconfig_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Use matched file
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/sysconfig/network in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Check if watch
        rule for /etc/sysconfig/network already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/sysconfig/network\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify the System's Network Environment - Add watch rule
        for /etc/sysconfig/network in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/sysconfig/network -p wa -k audit_rules_networkconfig_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.5.5
      - PCI-DSSv4-10.3
      - PCI-DSSv4-10.3.4
      - audit_rules_networkconfig_modification
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Process and Session Initiation Information btmp [ref]

The audit system already collects process information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/btmp -p wa -k session

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/btmp -p wa -k session

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_session_events_btmp

References:

hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
nist | AU-12(c), AU-12.1(iv)
os-srg | SRG-OS-000472-GPOS-00217
anssi | R73
ism | 0582, 0846
pcidss4 | 10.2.1.3, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/var/log/btmp" "$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\+/var/log/btmp $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 "wa" | 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\+/var/log/btmp$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 /var/log/btmp -p wa -k session" >> "$audit_rules_file"

        fi
    done
    # 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 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/session.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/var/log/btmp" /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/session.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/session.rules"
        # If the session.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

    # 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]+/var/log/btmp" "$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\+/var/log/btmp $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 "wa" | 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\+/var/log/btmp$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 /var/log/btmp -p wa -k session" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Check if watch rule for /var/log/btmp already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/log/btmp\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Search /etc/audit/rules.d for other rules with specified key session
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)session$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Use /etc/audit/rules.d/session.rules as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/session.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Use matched file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Add watch rule for /var/log/btmp in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/log/btmp -p wa -k session
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Check if watch rule for /var/log/btmp already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/log/btmp\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information btmp -
        Add watch rule for /var/log/btmp in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/log/btmp -p wa -k session
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_btmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Process and Session Initiation Information utmp [ref]

The audit system already collects process information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/run/utmp -p wa -k session

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/run/utmp -p wa -k session

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_session_events_utmp

References:

hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
nist | AU-12(c), AU-12.1(iv)
os-srg | SRG-OS-000472-GPOS-00217
anssi | R73
ism | 0582, 0846
pcidss4 | 10.2.1.3, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/var/run/utmp" "$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\+/var/run/utmp $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 "wa" | 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\+/var/run/utmp$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 /var/run/utmp -p wa -k session" >> "$audit_rules_file"

        fi
    done
    # 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 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/session.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/var/run/utmp" /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/session.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/session.rules"
        # If the session.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

    # 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]+/var/run/utmp" "$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\+/var/run/utmp $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 "wa" | 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\+/var/run/utmp$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 /var/run/utmp -p wa -k session" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Check if watch rule for /var/run/utmp already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/run/utmp\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Search /etc/audit/rules.d for other rules with specified key session
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)session$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Use /etc/audit/rules.d/session.rules as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/session.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Use matched file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Add watch rule for /var/run/utmp in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/run/utmp -p wa -k session
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Check if watch rule for /var/run/utmp already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/run/utmp\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information utmp -
        Add watch rule for /var/run/utmp in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/run/utmp -p wa -k session
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_utmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to Alter Process and Session Initiation Information wtmp [ref]

The audit system already collects process information for all users and root. If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/wtmp -p wa -k session

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/wtmp -p wa -k session

Rationale: | Manual editing of these files may indicate nefarious activity, such as an attacker attempting to remove evidence of an intrusion.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_session_events_wtmp

References:

hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
nist | AU-12(c), AU-12.1(iv)
os-srg | SRG-OS-000472-GPOS-00217
anssi | R73
ism | 0582, 0846
pcidss4 | 10.2.1.3, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/var/log/wtmp" "$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\+/var/log/wtmp $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 "wa" | 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\+/var/log/wtmp$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 /var/log/wtmp -p wa -k session" >> "$audit_rules_file"

        fi
    done
    # 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 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/session.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/var/log/wtmp" /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/session.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/session.rules"
        # If the session.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

    # 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]+/var/log/wtmp" "$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\+/var/log/wtmp $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 "wa" | 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\+/var/log/wtmp$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 /var/log/wtmp -p wa -k session" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Check if watch rule for /var/log/wtmp already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/log/wtmp\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Search /etc/audit/rules.d for other rules with specified key session
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)session$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Use /etc/audit/rules.d/session.rules as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/session.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Use matched file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Add watch rule for /var/log/wtmp in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/log/wtmp -p wa -k session
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Check if watch rule for /var/log/wtmp already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/log/wtmp\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to Alter Process and Session Initiation Information wtmp -
        Add watch rule for /var/log/wtmp in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/log/wtmp -p wa -k session
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-12.1(iv)
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_rules_session_events_wtmp
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure auditd Collects System Administrator Actions [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/sudoers -p wa -k actions

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/sudoers -p wa -k actions

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/sudoers.d/ -p wa -k actions

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/sudoers.d/ -p wa -k actions

Rationale: | The actions taken by system administrators should be audited to keep a record of what was executed on the system, as well as, for accountability purposes.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_sysadmin_actions

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nist | AC-2(7)(b), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.2, Req-10.2.5.b

os-srg

SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000304-GPOS-00121, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221

app-srg-ctr | SRG-APP-000026-CTR-000070, SRG-APP-000027-CTR-000075, SRG-APP-000028-CTR-000080, SRG-APP-000291-CTR-000675, SRG-APP-000292-CTR-000680, SRG-APP-000293-CTR-000685, SRG-APP-000294-CTR-000690, SRG-APP-000319-CTR-000745, SRG-APP-000320-CTR-000750, SRG-APP-000509-CTR-001305
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/sudoers" "$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\+/etc/sudoers $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 "wa" | 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\+/etc/sudoers$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 /etc/sudoers -p wa -k actions" >> "$audit_rules_file"

        fi
    done
    # 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 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/actions.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/sudoers" /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/actions.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/actions.rules"
        # If the actions.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

    # 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]+/etc/sudoers" "$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\+/etc/sudoers $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 "wa" | 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\+/etc/sudoers$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 /etc/sudoers -p wa -k actions" >> "$audit_rules_file"

        fi
    done
    # 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 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')

    # 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]+/etc/sudoers.d/" "$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\+/etc/sudoers.d/ $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 "wa" | 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\+/etc/sudoers.d/$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 /etc/sudoers.d/ -p wa -k actions" >> "$audit_rules_file"

        fi
    done
    # 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 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/actions.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/sudoers.d/" /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/actions.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/actions.rules"
        # If the actions.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

    # 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]+/etc/sudoers.d/" "$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\+/etc/sudoers.d/ $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 "wa" | 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\+/etc/sudoers.d/$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 /etc/sudoers.d/ -p wa -k actions" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Check if watch rule
        for /etc/sudoers already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/sudoers\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Add watch rule for /etc/sudoers
        in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/sudoers -p wa -k actions
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Check if watch rule
        for /etc/sudoers already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/sudoers\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Search /etc/audit/rules.d
        for other rules with specified key actions
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)actions$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Use /etc/audit/rules.d/actions.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/actions.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Use matched file as
        the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Add watch rule for /etc/sudoers
        in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/sudoers -p wa -k actions
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Check if watch rule
        for /etc/sudoers.d/ already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/sudoers.d/\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Add watch rule for /etc/sudoers.d/
        in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/sudoers.d/ -p wa -k actions
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Check if watch rule
        for /etc/sudoers.d/ already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/sudoers.d/\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Search /etc/audit/rules.d
        for other rules with specified key actions
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)actions$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Use /etc/audit/rules.d/actions.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/actions.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Use matched file as
        the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Ensure auditd Collects System Administrator Actions - Add watch rule for /etc/sudoers.d/
        in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/sudoers.d/ -p wa -k actions
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(7)(b)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_sysadmin_actions
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/group [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/group -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/group -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_group

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/group" "$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\+/etc/group $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 "wa" | 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\+/etc/group$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 /etc/group -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_usergroup_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/group" /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/audit_rules_usergroup_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_usergroup_modification.rules"
        # If the audit_rules_usergroup_modification.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

    # 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]+/etc/group" "$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\+/etc/group $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 "wa" | 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\+/etc/group$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 /etc/group -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Check if watch
        rule for /etc/group already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/group\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_usergroup_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_usergroup_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Use /etc/audit/rules.d/audit_rules_usergroup_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_usergroup_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Use matched
        file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Add watch
        rule for /etc/group in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/group -p wa -k audit_rules_usergroup_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Check if watch
        rule for /etc/group already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/group\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/group - Add watch
        rule for /etc/group in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/group -p wa -k audit_rules_usergroup_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_group
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/gshadow [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/gshadow -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/gshadow -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_gshadow

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/gshadow" "$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\+/etc/gshadow $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 "wa" | 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\+/etc/gshadow$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 /etc/gshadow -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_usergroup_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/gshadow" /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/audit_rules_usergroup_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_usergroup_modification.rules"
        # If the audit_rules_usergroup_modification.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

    # 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]+/etc/gshadow" "$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\+/etc/gshadow $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 "wa" | 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\+/etc/gshadow$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 /etc/gshadow -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Check if
        watch rule for /etc/gshadow already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/gshadow\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_usergroup_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_usergroup_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Use /etc/audit/rules.d/audit_rules_usergroup_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_usergroup_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Use matched
        file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Add watch
        rule for /etc/gshadow in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/gshadow -p wa -k audit_rules_usergroup_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Check if
        watch rule for /etc/gshadow already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/gshadow\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/gshadow - Add watch
        rule for /etc/gshadow in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/gshadow -p wa -k audit_rules_usergroup_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_gshadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/security/opasswd [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_opasswd

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000496-CTR-001240, SRG-APP-000497-CTR-001245, SRG-APP-000498-CTR-001250, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/security/opasswd" "$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\+/etc/security/opasswd $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 "wa" | 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\+/etc/security/opasswd$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 /etc/security/opasswd -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_usergroup_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/security/opasswd" /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/audit_rules_usergroup_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_usergroup_modification.rules"
        # If the audit_rules_usergroup_modification.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

    # 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]+/etc/security/opasswd" "$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\+/etc/security/opasswd $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 "wa" | 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\+/etc/security/opasswd$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 /etc/security/opasswd -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Check if watch rule for /etc/security/opasswd already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/security/opasswd\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Search /etc/audit/rules.d for other rules with specified key audit_rules_usergroup_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_usergroup_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Use /etc/audit/rules.d/audit_rules_usergroup_modification.rules as the recipient
        for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_usergroup_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Use matched file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Add watch rule for /etc/security/opasswd in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Check if watch rule for /etc/security/opasswd already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/security/opasswd\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/security/opasswd -
        Add watch rule for /etc/security/opasswd in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/security/opasswd -p wa -k audit_rules_usergroup_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_opasswd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/passwd [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/passwd -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/passwd -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_passwd

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5

os-srg

SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000304-GPOS-00121, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221, SRG-OS-000274-GPOS-00104, SRG-OS-000275-GPOS-00105, SRG-OS-000276-GPOS-00106, SRG-OS-000277-GPOS-00107

app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/passwd" "$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\+/etc/passwd $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 "wa" | 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\+/etc/passwd$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 /etc/passwd -p wa -k audit_rules_usergroup_modification_passwd" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_usergroup_modification_passwd.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/passwd" /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/audit_rules_usergroup_modification_passwd.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_usergroup_modification_passwd.rules"
        # If the audit_rules_usergroup_modification_passwd.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

    # 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]+/etc/passwd" "$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\+/etc/passwd $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 "wa" | 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\+/etc/passwd$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 /etc/passwd -p wa -k audit_rules_usergroup_modification_passwd" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Check if
        watch rule for /etc/passwd already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/passwd\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_usergroup_modification_passwd
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_usergroup_modification_passwd$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Use /etc/audit/rules.d/audit_rules_usergroup_modification_passwd.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_usergroup_modification_passwd.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Use matched
        file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Add watch
        rule for /etc/passwd in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/passwd -p wa -k audit_rules_usergroup_modification_passwd
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Check if
        watch rule for /etc/passwd already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/passwd\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/passwd - Add watch
        rule for /etc/passwd in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/passwd -p wa -k audit_rules_usergroup_modification_passwd
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_passwd
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Events that Modify User/Group Information - /etc/shadow [ref]

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /etc/shadow -p wa -k audit_rules_usergroup_modification

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /etc/shadow -p wa -k audit_rules_usergroup_modification

Rationale: | In addition to auditing new user and group accounts, these watches will alert the system administrator(s) to any modifications. Any unexpected users, groups, or modifications should be investigated for legitimacy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_rules_usergroup_modification_shadow

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, DSS06.03, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.1.7
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C), 164.312(a)(2)(i), 164.312(b), 164.312(d), 164.312(e)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.2.2, 4.3.3.3.9, 4.3.3.5.1, 4.3.3.5.2, 4.3.3.5.8, 4.3.3.6.6, 4.3.3.7.2, 4.3.3.7.3, 4.3.3.7.4, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.1, SR 1.13, SR 1.2, SR 1.3, SR 1.4, SR 1.5, SR 1.7, SR 1.8, SR 1.9, SR 2.1, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.1.2, A.6.2.1, A.6.2.2, A.7.1.1, A.9.1.2, A.9.2.1, A.9.2.2, A.9.2.3, A.9.2.4, A.9.2.6, A.9.3.1, A.9.4.1, A.9.4.2, A.9.4.3, A.9.4.4, A.9.4.5
nerc-cip | CIP-004-6 R2.2.2, CIP-004-6 R2.2.3, CIP-007-3 R.1.3, CIP-007-3 R5, CIP-007-3 R5.1.1, CIP-007-3 R5.1.3, CIP-007-3 R5.2.1, CIP-007-3 R5.2.3
nist | AC-2(4), AU-2(d), AU-12(c), AC-6(9), CM-6(a)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-1, PR.AC-3, PR.AC-4, PR.AC-6, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
pcidss | Req-10.2.5
os-srg | SRG-OS-000004-GPOS-00004, SRG-OS-000037-GPOS-00015, SRG-OS-000042-GPOS-00020, SRG-OS-000062-GPOS-00031, SRG-OS-000304-GPOS-00121, SRG-OS-000392-GPOS-00172, SRG-OS-000462-GPOS-00206, SRG-OS-000470-GPOS-00214, SRG-OS-000471-GPOS-00215, SRG-OS-000239-GPOS-00089, SRG-OS-000240-GPOS-00090, SRG-OS-000241-GPOS-00091, SRG-OS-000303-GPOS-00120, SRG-OS-000466-GPOS-00210, SRG-OS-000476-GPOS-00221
app-srg-ctr | SRG-APP-000495-CTR-001235, SRG-APP-000499-CTR-001255, SRG-APP-000503-CTR-001275
anssi | R73
ism | 0582
pcidss4 | 10.2.1.5, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/etc/shadow" "$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\+/etc/shadow $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 "wa" | 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\+/etc/shadow$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 /etc/shadow -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done
    # 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 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/audit_rules_usergroup_modification.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/etc/shadow" /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/audit_rules_usergroup_modification.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/audit_rules_usergroup_modification.rules"
        # If the audit_rules_usergroup_modification.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

    # 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]+/etc/shadow" "$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\+/etc/shadow $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 "wa" | 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\+/etc/shadow$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 /etc/shadow -p wa -k audit_rules_usergroup_modification" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Check if
        watch rule for /etc/shadow already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/etc/shadow\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Search /etc/audit/rules.d
        for other rules with specified key audit_rules_usergroup_modification
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)audit_rules_usergroup_modification$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Use /etc/audit/rules.d/audit_rules_usergroup_modification.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/audit_rules_usergroup_modification.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Use matched
        file as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Add watch
        rule for /etc/shadow in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /etc/shadow -p wa -k audit_rules_usergroup_modification
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Check if
        watch rule for /etc/shadow already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/etc/shadow\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Events that Modify User/Group Information - /etc/shadow - Add watch
        rule for /etc/shadow in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /etc/shadow -p wa -k audit_rules_usergroup_modification
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.1.7
      - NIST-800-53-AC-2(4)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.2.5
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.5
      - audit_rules_usergroup_modification_shadow
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Record Attempts to perform maintenance activities [ref]

The Debian 13 operating system must generate audit records for privileged activities, nonlocal maintenance, diagnostic sessions and other system-level access. Verify the operating system audits activities performed during nonlocal maintenance and diagnostic sessions. Run the following command:

    $ sudo auditctl -l | grep sudo.log
    -w /var/log/sudo.log -p wa -k maintenance

If the `auditd` daemon is configured to use the `augenrules` program to read audit rules during daemon startup (the default), add the following lines to a file with suffix `.rules` in the directory `/etc/audit/rules.d`:

    -w /var/log/sudo.log -p wa -k maintenance

If the `auditd` daemon is configured to use the `auditctl` utility to read audit rules during daemon startup, add the following lines to `/etc/audit/audit.rules`:

    -w /var/log/sudo.log -p wa -k maintenance

Rationale:

If events associated with nonlocal administrative access or diagnostic sessions are not logged, a major tool for assessing and investigating attacks would not be available. This requirement addresses auditing-related issues associated with maintenance tools used specifically for diagnostic and repair actions on organizational information systems. Nonlocal maintenance and diagnostic activities are those activities conducted by individuals communicating through a network, either an external network (e.g., the internet) or an internal network. Local maintenance and diagnostic activities are those activities carried out by individuals physically present at the information system or information system component and not communicating across a network connection. This requirement applies to hardware/software diagnostic test equipment or tools. This requirement does not cover hardware/software components that may support information system maintenance, yet are a part of the system, for example, the software implementing "ping," "ls," "ipconfig," or the hardware and software implementing the monitoring port of an Ethernet switch.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_audit_sudo_log_events

References:

pcidss | Req-10.2.2, Req-10.2.5.b
os-srg | SRG-OS-000392-GPOS-00172, SRG-OS-000471-GPOS-00215
anssi | R73
pcidss4 | 10.2.1.3, 10.2.1, 10.2

Remediation Shell script ⇲

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$' && dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    # Perform the remediation for both possible tools: 'auditctl' and 'augenrules'

    # 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 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')

    # 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]+/var/log/sudo.log" "$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\+/var/log/sudo.log $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 "wa" | 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\+/var/log/sudo.log$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 /var/log/sudo.log -p wa -k maintenance" >> "$audit_rules_file"

        fi
    done
    # 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 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/maintenance.rules' to list of files for inspection.

    readarray -t matches < <(grep -HP "[\s]*-w[\s]+/var/log/sudo.log" /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/maintenance.rules' into list of files for inspection
        key_rule_file="/etc/audit/rules.d/maintenance.rules"
        # If the maintenance.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

    # 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]+/var/log/sudo.log" "$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\+/var/log/sudo.log $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 "wa" | 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\+/var/log/sudo.log$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 /var/log/sudo.log -p wa -k maintenance" >> "$audit_rules_file"

        fi
    done

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | restrict

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Check if watch rule for
        /var/log/sudo.log already exists in /etc/audit/rules.d/
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^\s*-w\s+/var/log/sudo.log\s+-p\s+wa(\s|$)+
        patterns: '*.rules'
      register: find_existing_watch_rules_d
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Search /etc/audit/rules.d
        for other rules with specified key maintenance
      ansible.builtin.find:
        paths: /etc/audit/rules.d
        contains: ^.*(?:-F key=|-k\s+)maintenance$
        patterns: '*.rules'
      register: find_watch_key
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Use /etc/audit/rules.d/maintenance.rules
        as the recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - /etc/audit/rules.d/maintenance.rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Use matched file as the
        recipient for the rule
      ansible.builtin.set_fact:
        all_files:
        - '{{ find_watch_key.files | map(attribute=''path'') | list | first }}'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - 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
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Add watch rule for /var/log/sudo.log
        in /etc/audit/rules.d/
      ansible.builtin.lineinfile:
        path: '{{ all_files[0] }}'
        line: -w /var/log/sudo.log -p wa -k maintenance
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_rules_d.matched is defined and find_existing_watch_rules_d.matched
        == 0
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Check if watch rule for
        /var/log/sudo.log already exists in /etc/audit/audit.rules
      ansible.builtin.find:
        paths: /etc/audit/
        contains: ^\s*-w\s+/var/log/sudo.log\s+-p\s+wa(\s|$)+
        patterns: audit.rules
      register: find_existing_watch_audit_rules
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

    - name: Record Attempts to perform maintenance activities - Add watch rule for /var/log/sudo.log
        in /etc/audit/audit.rules
      ansible.builtin.lineinfile:
        line: -w /var/log/sudo.log -p wa -k maintenance
        state: present
        dest: /etc/audit/audit.rules
        create: true
        mode: '0600'
      when:
      - '"auditd" in ansible_facts.packages'
      - '"linux-base" in ansible_facts.packages'
      - find_existing_watch_audit_rules.matched is defined and find_existing_watch_audit_rules.matched
        == 0
      tags:
      - PCI-DSS-Req-10.2.2
      - PCI-DSS-Req-10.2.5.b
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - PCI-DSSv4-10.2.1.3
      - audit_sudo_log_events
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - restrict_strategy

#### Rule Ensure the audit Subsystem is Installed [ref]

The audit package should be installed.
Rationale: | The auditd service is an access monitoring and accounting daemon, watching system calls to audit any access, in comparison with potential local access control policy such as SELinux policy.
Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_package_audit_installed

References:

hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(5)(ii)(C), 164.310(a)(2)(iv), 164.310(d)(2)(iii), 164.312(b)
nerc-cip | CIP-004-6 R3.3, CIP-007-3 R6.5
nist | AC-7(a), AU-7(1), AU-7(2), AU-14, AU-12(2), AU-2(a), CM-6(a)
ospp | FAU_GEN.1
pcidss | Req-10.1

os-srg

SRG-OS-000062-GPOS-00031, SRG-OS-000037-GPOS-00015, SRG-OS-000038-GPOS-00016, SRG-OS-000039-GPOS-00017, SRG-OS-000040-GPOS-00018, SRG-OS-000041-GPOS-00019, SRG-OS-000042-GPOS-00021, SRG-OS-000051-GPOS-00024, SRG-OS-000054-GPOS-00025, SRG-OS-000122-GPOS-00063, SRG-OS-000254-GPOS-00095, SRG-OS-000255-GPOS-00096, SRG-OS-000337-GPOS-00129, SRG-OS-000348-GPOS-00136, SRG-OS-000349-GPOS-00137, SRG-OS-000350-GPOS-00138, SRG-OS-000351-GPOS-00139, SRG-OS-000352-GPOS-00140, SRG-OS-000353-GPOS-00141, SRG-OS-000354-GPOS-00142, SRG-OS-000358-GPOS-00145, SRG-OS-000365-GPOS-00152, SRG-OS-000392-GPOS-00172, SRG-OS-000475-GPOS-00220

anssi | R33, R73
ism | 0582, 0846
pcidss4 | 10.2.1, 10.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$'; then

    DEBIAN_FRONTEND=noninteractive apt-get install -y "auditd"

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include install_auditd

    class install_auditd {
      package { 'auditd':
        ensure => 'installed',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AU-12(2)
      - NIST-800-53-AU-14
      - NIST-800-53-AU-2(a)
      - NIST-800-53-AU-7(1)
      - NIST-800-53-AU-7(2)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.1
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_audit_installed

    - name: Ensure auditd is installed
      ansible.builtin.package:
        name: auditd
        state: present
      when: '"linux-base" in ansible_facts.packages'
      tags:
      - NIST-800-53-AC-7(a)
      - NIST-800-53-AU-12(2)
      - NIST-800-53-AU-14
      - NIST-800-53-AU-2(a)
      - NIST-800-53-AU-7(1)
      - NIST-800-53-AU-7(2)
      - NIST-800-53-CM-6(a)
      - PCI-DSS-Req-10.1
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - package_audit_installed

Remediation OSBuild Blueprint snippet ⇲

    [[packages]]
    name = "auditd"
    version = "*"

#### Rule Enable auditd Service [ref]

The `auditd` service is an essential userspace component of the Linux Auditing System, as it is responsible for writing audit records to disk. The `auditd` service can be enabled with the following command:

    $ sudo systemctl enable auditd.service

Rationale:

Without establishing what type of events occurred, it would be difficult to establish, correlate, and investigate the events leading up to an outage or attack. Ensuring the `auditd` service is active ensures audit records generated by the kernel are appropriately recorded.
Additionally, a properly configured audit subsystem ensures that actions of individual system users can be uniquely traced to those users so they can be held accountable for their actions.

Severity: | medium
Rule ID: | xccdf_org.ssgproject.content_rule_service_auditd_enabled

References:

cis-csc | 1, 11, 12, 13, 14, 15, 16, 19, 2, 3, 4, 5, 6, 7, 8, 9
cjis | 5.4.1.1
cobit5 | APO10.01, APO10.03, APO10.04, APO10.05, APO11.04, APO12.06, APO13.01, BAI03.05, BAI08.02, DSS01.03, DSS01.04, DSS02.02, DSS02.04, DSS02.07, DSS03.01, DSS03.05, DSS05.02, DSS05.03, DSS05.04, DSS05.05, DSS05.07, MEA01.01, MEA01.02, MEA01.03, MEA01.04, MEA01.05, MEA02.01
cui | 3.3.1, 3.3.2, 3.3.6
hipaa | 164.308(a)(1)(ii)(D), 164.308(a)(5)(ii)(C), 164.310(a)(2)(iv), 164.310(d)(2)(iii), 164.312(b)
isa-62443-2009 | 4.2.3.10, 4.3.2.6.7, 4.3.3.3.9, 4.3.3.5.8, 4.3.3.6.6, 4.3.4.4.7, 4.3.4.5.6, 4.3.4.5.7, 4.3.4.5.8, 4.4.2.1, 4.4.2.2, 4.4.2.4
isa-62443-2013 | SR 1.13, SR 2.10, SR 2.11, SR 2.12, SR 2.6, SR 2.8, SR 2.9, SR 3.1, SR 3.5, SR 3.8, SR 4.1, SR 4.3, SR 5.1, SR 5.2, SR 5.3, SR 6.1, SR 6.2, SR 7.1, SR 7.6
iso27001-2013 | A.11.2.6, A.12.4.1, A.12.4.2, A.12.4.3, A.12.4.4, A.12.7.1, A.13.1.1, A.13.2.1, A.14.1.3, A.14.2.7, A.15.2.1, A.15.2.2, A.16.1.4, A.16.1.5, A.16.1.7, A.6.2.1, A.6.2.2
nerc-cip | CIP-004-6 R3.3, CIP-007-3 R6.5
nist | AC-2(g), AU-3, AU-10, AU-2(d), AU-12(c), AU-14(1), AC-6(9), CM-6(a), SI-4(23)
nist-csf | DE.AE-3, DE.AE-5, DE.CM-1, DE.CM-3, DE.CM-7, ID.SC-4, PR.AC-3, PR.PT-1, PR.PT-4, RS.AN-1, RS.AN-4
ospp | FAU_GEN.1
pcidss | Req-10.1

os-srg

SRG-OS-000062-GPOS-00031, SRG-OS-000037-GPOS-00015, SRG-OS-000038-GPOS-00016, SRG-OS-000039-GPOS-00017, SRG-OS-000040-GPOS-00018, SRG-OS-000041-GPOS-00019, SRG-OS-000042-GPOS-00021, SRG-OS-000051-GPOS-00024, SRG-OS-000054-GPOS-00025, SRG-OS-000122-GPOS-00063, SRG-OS-000254-GPOS-00095, SRG-OS-000255-GPOS-00096, SRG-OS-000337-GPOS-00129, SRG-OS-000348-GPOS-00136, SRG-OS-000349-GPOS-00137, SRG-OS-000350-GPOS-00138, SRG-OS-000351-GPOS-00139, SRG-OS-000352-GPOS-00140, SRG-OS-000353-GPOS-00141, SRG-OS-000354-GPOS-00142, SRG-OS-000358-GPOS-00145, SRG-OS-000365-GPOS-00152, SRG-OS-000392-GPOS-00172, SRG-OS-000475-GPOS-00220

app-srg-ctr | SRG-APP-000095-CTR-000170, SRG-APP-000409-CTR-000990, SRG-APP-000508-CTR-001300, SRG-APP-000510-CTR-001310
anssi | R33, R73
ism | 1409
pcidss4 | 10.2.1, 10.2

Remediation Shell script ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    # Remediation is applicable only in certain platforms
    if dpkg-query --show --showformat='${db:Status-Status}' 'linux-base' 2>/dev/null | grep -q '^installed$' && { dpkg-query --show --showformat='${db:Status-Status}' 'auditd' 2>/dev/null | grep -q '^installed$'; }; then

    SYSTEMCTL_EXEC='/usr/bin/systemctl'
    "$SYSTEMCTL_EXEC" unmask 'auditd.service'
    if [[ $("$SYSTEMCTL_EXEC" is-system-running) != "offline" ]]; then
      "$SYSTEMCTL_EXEC" start 'auditd.service'
    fi
    "$SYSTEMCTL_EXEC" enable 'auditd.service'

    else
        >&2 echo 'Remediation is not applicable, nothing was done'
    fi

Remediation Puppet snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    include enable_auditd

    class enable_auditd {
      service {'auditd':
        enable => true,
        ensure => 'running',
      }
    }

Remediation Ansible snippet ⇲

Complexity: | low
Disruption: | low
Reboot: | false
Strategy: | enable

    - name: Gather the package facts
      package_facts:
        manager: auto
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.3.2
      - NIST-800-171-3.3.6
      - NIST-800-53-AC-2(g)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-14(1)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-4(23)
      - PCI-DSS-Req-10.1
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_auditd_enabled

    - name: Enable auditd Service - Enable service auditd
      block:

      - name: Gather the package facts
        ansible.builtin.package_facts:
          manager: auto

      - name: Enable auditd Service - Enable Service auditd
        ansible.builtin.systemd:
          name: auditd
          enabled: true
          state: started
          masked: false
        when:
        - '"auditd" in ansible_facts.packages'
      tags:
      - CJIS-5.4.1.1
      - NIST-800-171-3.3.1
      - NIST-800-171-3.3.2
      - NIST-800-171-3.3.6
      - NIST-800-53-AC-2(g)
      - NIST-800-53-AC-6(9)
      - NIST-800-53-AU-10
      - NIST-800-53-AU-12(c)
      - NIST-800-53-AU-14(1)
      - NIST-800-53-AU-2(d)
      - NIST-800-53-AU-3
      - NIST-800-53-CM-6(a)
      - NIST-800-53-SI-4(23)
      - PCI-DSS-Req-10.1
      - PCI-DSSv4-10.2
      - PCI-DSSv4-10.2.1
      - enable_strategy
      - low_complexity
      - low_disruption
      - medium_severity
      - no_reboot_needed
      - service_auditd_enabled
      - special_service_block
      when:
      - '"linux-base" in ansible_facts.packages'
      - '"auditd" in ansible_facts.packages'

Remediation OSBuild Blueprint snippet ⇲

    [customizations.services]
    enabled = ["auditd"]

Red Hat and Red Hat Enterprise Linux are either registered trademarks or trademarks of Red Hat, Inc. in the United States and other countries. All other names are registered trademarks or trademarks of their respective companies.